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->isTargetWindows() && !Subtarget->isTargetCygMing()) {
100 // Setup Windows compiler runtime calls.
101 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
102 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
103 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
104 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
105 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
106 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
107 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
108 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
111 if (Subtarget->isTargetDarwin()) {
112 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
113 setUseUnderscoreSetJmp(false);
114 setUseUnderscoreLongJmp(false);
115 } else if (Subtarget->isTargetMingw()) {
116 // MS runtime is weird: it exports _setjmp, but longjmp!
117 setUseUnderscoreSetJmp(true);
118 setUseUnderscoreLongJmp(false);
120 setUseUnderscoreSetJmp(true);
121 setUseUnderscoreLongJmp(true);
124 // Set up the register classes.
125 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
126 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
127 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
128 if (Subtarget->is64Bit())
129 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
131 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
133 // We don't accept any truncstore of integer registers.
134 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
135 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
136 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
137 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
141 // SETOEQ and SETUNE require checking two conditions.
142 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
149 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
151 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
152 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
153 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
155 if (Subtarget->is64Bit()) {
156 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
157 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
158 } else if (!UseSoftFloat) {
159 // We have an algorithm for SSE2->double, and we turn this into a
160 // 64-bit FILD followed by conditional FADD for other targets.
161 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
162 // We have an algorithm for SSE2, and we turn this into a 64-bit
163 // FILD for other targets.
164 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
167 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
169 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
173 // SSE has no i16 to fp conversion, only i32
174 if (X86ScalarSSEf32) {
175 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
176 // f32 and f64 cases are Legal, f80 case is not
177 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
179 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
183 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
184 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
187 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
188 // are Legal, f80 is custom lowered.
189 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
190 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
192 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
194 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
195 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
197 if (X86ScalarSSEf32) {
198 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
199 // f32 and f64 cases are Legal, f80 case is not
200 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
202 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
203 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
206 // Handle FP_TO_UINT by promoting the destination to a larger signed
208 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
209 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
210 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
212 if (Subtarget->is64Bit()) {
213 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
215 } else if (!UseSoftFloat) {
216 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
217 // Expand FP_TO_UINT into a select.
218 // FIXME: We would like to use a Custom expander here eventually to do
219 // the optimal thing for SSE vs. the default expansion in the legalizer.
220 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
222 // With SSE3 we can use fisttpll to convert to a signed i64; without
223 // SSE, we're stuck with a fistpll.
224 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
227 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
228 if (!X86ScalarSSEf64) {
229 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
230 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
231 if (Subtarget->is64Bit()) {
232 setOperationAction(ISD::BIT_CONVERT , MVT::f64 , Expand);
233 // Without SSE, i64->f64 goes through memory.
234 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Expand);
238 // Scalar integer divide and remainder are lowered to use operations that
239 // produce two results, to match the available instructions. This exposes
240 // the two-result form to trivial CSE, which is able to combine x/y and x%y
241 // into a single instruction.
243 // Scalar integer multiply-high is also lowered to use two-result
244 // operations, to match the available instructions. However, plain multiply
245 // (low) operations are left as Legal, as there are single-result
246 // instructions for this in x86. Using the two-result multiply instructions
247 // when both high and low results are needed must be arranged by dagcombine.
248 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
249 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
250 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
251 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
252 setOperationAction(ISD::SREM , MVT::i8 , Expand);
253 setOperationAction(ISD::UREM , MVT::i8 , Expand);
254 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
255 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
256 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
257 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
258 setOperationAction(ISD::SREM , MVT::i16 , Expand);
259 setOperationAction(ISD::UREM , MVT::i16 , Expand);
260 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
261 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
262 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
263 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
264 setOperationAction(ISD::SREM , MVT::i32 , Expand);
265 setOperationAction(ISD::UREM , MVT::i32 , Expand);
266 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
267 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
268 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
269 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
270 setOperationAction(ISD::SREM , MVT::i64 , Expand);
271 setOperationAction(ISD::UREM , MVT::i64 , Expand);
273 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
274 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
275 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
276 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
277 if (Subtarget->is64Bit())
278 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
279 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
280 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
281 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
282 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
283 setOperationAction(ISD::FREM , MVT::f32 , Expand);
284 setOperationAction(ISD::FREM , MVT::f64 , Expand);
285 setOperationAction(ISD::FREM , MVT::f80 , Expand);
286 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
288 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
291 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
292 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
293 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
294 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
295 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
296 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
297 if (Subtarget->is64Bit()) {
298 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
299 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
300 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
303 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
304 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
306 // These should be promoted to a larger select which is supported.
307 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
308 // X86 wants to expand cmov itself.
309 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
310 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
311 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
312 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
313 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
314 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
315 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
316 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
317 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
318 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
319 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
320 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
323 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
325 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
328 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
329 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
330 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
331 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
332 if (Subtarget->is64Bit())
333 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
335 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
338 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
339 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
340 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
341 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
343 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
345 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
346 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
347 if (Subtarget->is64Bit()) {
348 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
349 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
350 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
353 if (Subtarget->hasSSE1())
354 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
356 // We may not have a libcall for MEMBARRIER so we should lower this.
357 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
359 // On X86 and X86-64, atomic operations are lowered to locked instructions.
360 // Locked instructions, in turn, have implicit fence semantics (all memory
361 // operations are flushed before issuing the locked instruction, and they
362 // are not buffered), so we can fold away the common pattern of
363 // fence-atomic-fence.
364 setShouldFoldAtomicFences(true);
366 // Expand certain atomics
367 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
368 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
369 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
370 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
375 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
377 if (!Subtarget->is64Bit()) {
378 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
379 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
380 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
381 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
382 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
383 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
384 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
387 // FIXME - use subtarget debug flags
388 if (!Subtarget->isTargetDarwin() &&
389 !Subtarget->isTargetELF() &&
390 !Subtarget->isTargetCygMing()) {
391 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
394 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
395 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
396 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
397 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
398 if (Subtarget->is64Bit()) {
399 setExceptionPointerRegister(X86::RAX);
400 setExceptionSelectorRegister(X86::RDX);
402 setExceptionPointerRegister(X86::EAX);
403 setExceptionSelectorRegister(X86::EDX);
405 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
406 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
408 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
410 setOperationAction(ISD::TRAP, MVT::Other, Legal);
412 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
413 setOperationAction(ISD::VASTART , MVT::Other, Custom);
414 setOperationAction(ISD::VAEND , MVT::Other, Expand);
415 if (Subtarget->is64Bit()) {
416 setOperationAction(ISD::VAARG , MVT::Other, Custom);
417 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
419 setOperationAction(ISD::VAARG , MVT::Other, Expand);
420 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
423 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
424 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
425 if (Subtarget->is64Bit())
426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
427 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
428 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
430 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
432 if (!UseSoftFloat && X86ScalarSSEf64) {
433 // f32 and f64 use SSE.
434 // Set up the FP register classes.
435 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
436 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
438 // Use ANDPD to simulate FABS.
439 setOperationAction(ISD::FABS , MVT::f64, Custom);
440 setOperationAction(ISD::FABS , MVT::f32, Custom);
442 // Use XORP to simulate FNEG.
443 setOperationAction(ISD::FNEG , MVT::f64, Custom);
444 setOperationAction(ISD::FNEG , MVT::f32, Custom);
446 // Use ANDPD and ORPD to simulate FCOPYSIGN.
447 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
448 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
450 // We don't support sin/cos/fmod
451 setOperationAction(ISD::FSIN , MVT::f64, Expand);
452 setOperationAction(ISD::FCOS , MVT::f64, Expand);
453 setOperationAction(ISD::FSIN , MVT::f32, Expand);
454 setOperationAction(ISD::FCOS , MVT::f32, Expand);
456 // Expand FP immediates into loads from the stack, except for the special
458 addLegalFPImmediate(APFloat(+0.0)); // xorpd
459 addLegalFPImmediate(APFloat(+0.0f)); // xorps
460 } else if (!UseSoftFloat && X86ScalarSSEf32) {
461 // Use SSE for f32, x87 for f64.
462 // Set up the FP register classes.
463 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
466 // Use ANDPS to simulate FABS.
467 setOperationAction(ISD::FABS , MVT::f32, Custom);
469 // Use XORP to simulate FNEG.
470 setOperationAction(ISD::FNEG , MVT::f32, Custom);
472 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
474 // Use ANDPS and ORPS to simulate FCOPYSIGN.
475 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
476 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
478 // We don't support sin/cos/fmod
479 setOperationAction(ISD::FSIN , MVT::f32, Expand);
480 setOperationAction(ISD::FCOS , MVT::f32, Expand);
482 // Special cases we handle for FP constants.
483 addLegalFPImmediate(APFloat(+0.0f)); // xorps
484 addLegalFPImmediate(APFloat(+0.0)); // FLD0
485 addLegalFPImmediate(APFloat(+1.0)); // FLD1
486 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
490 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
491 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
493 } else if (!UseSoftFloat) {
494 // f32 and f64 in x87.
495 // Set up the FP register classes.
496 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
497 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
499 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
500 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
501 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
502 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
505 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
506 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
508 addLegalFPImmediate(APFloat(+0.0)); // FLD0
509 addLegalFPImmediate(APFloat(+1.0)); // FLD1
510 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
511 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
512 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
513 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
514 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
515 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
518 // Long double always uses X87.
520 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
521 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
522 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
525 APFloat TmpFlt(+0.0);
526 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
528 addLegalFPImmediate(TmpFlt); // FLD0
530 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
531 APFloat TmpFlt2(+1.0);
532 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
534 addLegalFPImmediate(TmpFlt2); // FLD1
535 TmpFlt2.changeSign();
536 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
540 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
541 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
545 // Always use a library call for pow.
546 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
547 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
548 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
550 setOperationAction(ISD::FLOG, MVT::f80, Expand);
551 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
552 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
553 setOperationAction(ISD::FEXP, MVT::f80, Expand);
554 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
556 // First set operation action for all vector types to either promote
557 // (for widening) or expand (for scalarization). Then we will selectively
558 // turn on ones that can be effectively codegen'd.
559 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
560 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
561 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
576 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
577 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
610 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
611 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
612 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
613 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
614 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
615 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
616 setTruncStoreAction((MVT::SimpleValueType)VT,
617 (MVT::SimpleValueType)InnerVT, Expand);
618 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
619 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
620 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
623 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
624 // with -msoft-float, disable use of MMX as well.
625 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
626 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
627 // No operations on x86mmx supported, everything uses intrinsics.
630 // MMX-sized vectors (other than x86mmx) are expected to be expanded
631 // into smaller operations.
632 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
633 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
634 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
635 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
636 setOperationAction(ISD::AND, MVT::v8i8, Expand);
637 setOperationAction(ISD::AND, MVT::v4i16, Expand);
638 setOperationAction(ISD::AND, MVT::v2i32, Expand);
639 setOperationAction(ISD::AND, MVT::v1i64, Expand);
640 setOperationAction(ISD::OR, MVT::v8i8, Expand);
641 setOperationAction(ISD::OR, MVT::v4i16, Expand);
642 setOperationAction(ISD::OR, MVT::v2i32, Expand);
643 setOperationAction(ISD::OR, MVT::v1i64, Expand);
644 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
645 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
646 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
647 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
648 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
649 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
652 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
653 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
654 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
655 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
656 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
657 setOperationAction(ISD::BIT_CONVERT, MVT::v8i8, Expand);
658 setOperationAction(ISD::BIT_CONVERT, MVT::v4i16, Expand);
659 setOperationAction(ISD::BIT_CONVERT, MVT::v2i32, Expand);
660 setOperationAction(ISD::BIT_CONVERT, MVT::v1i64, Expand);
662 if (!UseSoftFloat && Subtarget->hasSSE1()) {
663 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
665 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
666 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
667 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
668 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
669 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
670 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
671 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
672 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
673 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
674 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
675 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
676 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
679 if (!UseSoftFloat && Subtarget->hasSSE2()) {
680 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
682 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
683 // registers cannot be used even for integer operations.
684 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
685 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
686 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
687 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
689 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
690 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
691 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
692 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
693 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
694 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
695 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
696 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
697 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
698 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
699 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
700 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
701 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
702 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
703 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
704 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
706 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
707 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
708 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
709 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
711 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
712 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
713 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
714 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
715 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
717 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
718 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
719 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
720 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
721 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
723 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
724 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
725 EVT VT = (MVT::SimpleValueType)i;
726 // Do not attempt to custom lower non-power-of-2 vectors
727 if (!isPowerOf2_32(VT.getVectorNumElements()))
729 // Do not attempt to custom lower non-128-bit vectors
730 if (!VT.is128BitVector())
732 setOperationAction(ISD::BUILD_VECTOR,
733 VT.getSimpleVT().SimpleTy, Custom);
734 setOperationAction(ISD::VECTOR_SHUFFLE,
735 VT.getSimpleVT().SimpleTy, Custom);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
737 VT.getSimpleVT().SimpleTy, Custom);
740 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
741 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
742 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
743 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
744 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
747 if (Subtarget->is64Bit()) {
748 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
752 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
753 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
754 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
757 // Do not attempt to promote non-128-bit vectors
758 if (!VT.is128BitVector())
761 setOperationAction(ISD::AND, SVT, Promote);
762 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
763 setOperationAction(ISD::OR, SVT, Promote);
764 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
765 setOperationAction(ISD::XOR, SVT, Promote);
766 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
767 setOperationAction(ISD::LOAD, SVT, Promote);
768 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
769 setOperationAction(ISD::SELECT, SVT, Promote);
770 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
773 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
775 // Custom lower v2i64 and v2f64 selects.
776 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
777 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
778 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
779 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
781 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
782 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
785 if (Subtarget->hasSSE41()) {
786 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
787 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
788 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
789 setOperationAction(ISD::FRINT, MVT::f32, Legal);
790 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
791 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
792 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
793 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
794 setOperationAction(ISD::FRINT, MVT::f64, Legal);
795 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
797 // FIXME: Do we need to handle scalar-to-vector here?
798 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
800 // Can turn SHL into an integer multiply.
801 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
802 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
804 // i8 and i16 vectors are custom , because the source register and source
805 // source memory operand types are not the same width. f32 vectors are
806 // custom since the immediate controlling the insert encodes additional
808 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
809 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
810 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
811 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
813 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
816 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
818 if (Subtarget->is64Bit()) {
819 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
824 if (Subtarget->hasSSE42()) {
825 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
828 if (!UseSoftFloat && Subtarget->hasAVX()) {
829 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
830 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
831 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
832 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
833 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
835 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
836 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
837 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
838 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
839 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
840 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
841 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
842 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
843 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
844 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
845 setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
846 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
847 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
848 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
849 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
851 // Operations to consider commented out -v16i16 v32i8
852 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
853 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
854 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
855 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
856 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
857 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
858 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
859 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
860 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
861 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
862 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
863 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
864 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
865 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
867 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
868 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
869 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
870 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
872 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
873 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
874 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
878 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
879 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
880 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
881 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
886 // Not sure we want to do this since there are no 256-bit integer
889 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
890 // This includes 256-bit vectors
891 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
892 EVT VT = (MVT::SimpleValueType)i;
894 // Do not attempt to custom lower non-power-of-2 vectors
895 if (!isPowerOf2_32(VT.getVectorNumElements()))
898 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
899 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
900 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
903 if (Subtarget->is64Bit()) {
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
910 // Not sure we want to do this since there are no 256-bit integer
913 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
914 // Including 256-bit vectors
915 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
916 EVT VT = (MVT::SimpleValueType)i;
918 if (!VT.is256BitVector()) {
921 setOperationAction(ISD::AND, VT, Promote);
922 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
923 setOperationAction(ISD::OR, VT, Promote);
924 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
925 setOperationAction(ISD::XOR, VT, Promote);
926 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
927 setOperationAction(ISD::LOAD, VT, Promote);
928 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
929 setOperationAction(ISD::SELECT, VT, Promote);
930 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
933 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
937 // We want to custom lower some of our intrinsics.
938 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
940 // Add/Sub/Mul with overflow operations are custom lowered.
941 setOperationAction(ISD::SADDO, MVT::i32, Custom);
942 setOperationAction(ISD::UADDO, MVT::i32, Custom);
943 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
944 setOperationAction(ISD::USUBO, MVT::i32, Custom);
945 setOperationAction(ISD::SMULO, MVT::i32, Custom);
947 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
948 // handle type legalization for these operations here.
950 // FIXME: We really should do custom legalization for addition and
951 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
952 // than generic legalization for 64-bit multiplication-with-overflow, though.
953 if (Subtarget->is64Bit()) {
954 setOperationAction(ISD::SADDO, MVT::i64, Custom);
955 setOperationAction(ISD::UADDO, MVT::i64, Custom);
956 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
957 setOperationAction(ISD::USUBO, MVT::i64, Custom);
958 setOperationAction(ISD::SMULO, MVT::i64, Custom);
961 if (!Subtarget->is64Bit()) {
962 // These libcalls are not available in 32-bit.
963 setLibcallName(RTLIB::SHL_I128, 0);
964 setLibcallName(RTLIB::SRL_I128, 0);
965 setLibcallName(RTLIB::SRA_I128, 0);
968 // We have target-specific dag combine patterns for the following nodes:
969 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
970 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
971 setTargetDAGCombine(ISD::BUILD_VECTOR);
972 setTargetDAGCombine(ISD::SELECT);
973 setTargetDAGCombine(ISD::SHL);
974 setTargetDAGCombine(ISD::SRA);
975 setTargetDAGCombine(ISD::SRL);
976 setTargetDAGCombine(ISD::OR);
977 setTargetDAGCombine(ISD::STORE);
978 setTargetDAGCombine(ISD::ZERO_EXTEND);
979 if (Subtarget->is64Bit())
980 setTargetDAGCombine(ISD::MUL);
982 computeRegisterProperties();
984 // FIXME: These should be based on subtarget info. Plus, the values should
985 // be smaller when we are in optimizing for size mode.
986 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
987 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
988 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
989 setPrefLoopAlignment(16);
990 benefitFromCodePlacementOpt = true;
994 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
999 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1000 /// the desired ByVal argument alignment.
1001 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1004 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1005 if (VTy->getBitWidth() == 128)
1007 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1008 unsigned EltAlign = 0;
1009 getMaxByValAlign(ATy->getElementType(), EltAlign);
1010 if (EltAlign > MaxAlign)
1011 MaxAlign = EltAlign;
1012 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1013 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1014 unsigned EltAlign = 0;
1015 getMaxByValAlign(STy->getElementType(i), EltAlign);
1016 if (EltAlign > MaxAlign)
1017 MaxAlign = EltAlign;
1025 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1026 /// function arguments in the caller parameter area. For X86, aggregates
1027 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1028 /// are at 4-byte boundaries.
1029 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1030 if (Subtarget->is64Bit()) {
1031 // Max of 8 and alignment of type.
1032 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1039 if (Subtarget->hasSSE1())
1040 getMaxByValAlign(Ty, Align);
1044 /// getOptimalMemOpType - Returns the target specific optimal type for load
1045 /// and store operations as a result of memset, memcpy, and memmove
1046 /// lowering. If DstAlign is zero that means it's safe to destination
1047 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1048 /// means there isn't a need to check it against alignment requirement,
1049 /// probably because the source does not need to be loaded. If
1050 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1051 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1052 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1053 /// constant so it does not need to be loaded.
1054 /// It returns EVT::Other if the type should be determined using generic
1055 /// target-independent logic.
1057 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1058 unsigned DstAlign, unsigned SrcAlign,
1059 bool NonScalarIntSafe,
1061 MachineFunction &MF) const {
1062 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1063 // linux. This is because the stack realignment code can't handle certain
1064 // cases like PR2962. This should be removed when PR2962 is fixed.
1065 const Function *F = MF.getFunction();
1066 if (NonScalarIntSafe &&
1067 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1069 (Subtarget->isUnalignedMemAccessFast() ||
1070 ((DstAlign == 0 || DstAlign >= 16) &&
1071 (SrcAlign == 0 || SrcAlign >= 16))) &&
1072 Subtarget->getStackAlignment() >= 16) {
1073 if (Subtarget->hasSSE2())
1075 if (Subtarget->hasSSE1())
1077 } else if (!MemcpyStrSrc && Size >= 8 &&
1078 !Subtarget->is64Bit() &&
1079 Subtarget->getStackAlignment() >= 8 &&
1080 Subtarget->hasSSE2()) {
1081 // Do not use f64 to lower memcpy if source is string constant. It's
1082 // better to use i32 to avoid the loads.
1086 if (Subtarget->is64Bit() && Size >= 8)
1091 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1092 /// current function. The returned value is a member of the
1093 /// MachineJumpTableInfo::JTEntryKind enum.
1094 unsigned X86TargetLowering::getJumpTableEncoding() const {
1095 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1097 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1098 Subtarget->isPICStyleGOT())
1099 return MachineJumpTableInfo::EK_Custom32;
1101 // Otherwise, use the normal jump table encoding heuristics.
1102 return TargetLowering::getJumpTableEncoding();
1105 /// getPICBaseSymbol - Return the X86-32 PIC base.
1107 X86TargetLowering::getPICBaseSymbol(const MachineFunction &MF) const {
1109 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1110 MCContext &Ctx = MF.getContext();
1111 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1112 Twine(MF.getFunctionNumber())+"$pb");
1117 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1118 const MachineBasicBlock *MBB,
1119 unsigned uid,MCContext &Ctx) const{
1120 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1121 Subtarget->isPICStyleGOT());
1122 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1124 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1125 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1128 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1130 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1131 SelectionDAG &DAG) const {
1132 if (!Subtarget->is64Bit())
1133 // This doesn't have DebugLoc associated with it, but is not really the
1134 // same as a Register.
1135 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1139 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1140 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1142 const MCExpr *X86TargetLowering::
1143 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1144 MCContext &Ctx) const {
1145 // X86-64 uses RIP relative addressing based on the jump table label.
1146 if (Subtarget->isPICStyleRIPRel())
1147 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1149 // Otherwise, the reference is relative to the PIC base.
1150 return MCSymbolRefExpr::Create(getPICBaseSymbol(*MF), Ctx);
1153 /// getFunctionAlignment - Return the Log2 alignment of this function.
1154 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1155 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1158 std::pair<const TargetRegisterClass*, uint8_t>
1159 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1160 const TargetRegisterClass *RRC = 0;
1162 switch (VT.getSimpleVT().SimpleTy) {
1164 return TargetLowering::findRepresentativeClass(VT);
1165 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1166 RRC = (Subtarget->is64Bit()
1167 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1170 RRC = X86::VR64RegisterClass;
1172 case MVT::f32: case MVT::f64:
1173 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1174 case MVT::v4f32: case MVT::v2f64:
1175 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1177 RRC = X86::VR128RegisterClass;
1180 return std::make_pair(RRC, Cost);
1184 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1185 MachineFunction &MF) const {
1186 unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1187 switch (RC->getID()) {
1190 case X86::GR32RegClassID:
1192 case X86::GR64RegClassID:
1194 case X86::VR128RegClassID:
1195 return Subtarget->is64Bit() ? 10 : 4;
1196 case X86::VR64RegClassID:
1201 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1202 unsigned &Offset) const {
1203 if (!Subtarget->isTargetLinux())
1206 if (Subtarget->is64Bit()) {
1207 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1209 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1222 //===----------------------------------------------------------------------===//
1223 // Return Value Calling Convention Implementation
1224 //===----------------------------------------------------------------------===//
1226 #include "X86GenCallingConv.inc"
1229 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1230 const SmallVectorImpl<ISD::OutputArg> &Outs,
1231 LLVMContext &Context) const {
1232 SmallVector<CCValAssign, 16> RVLocs;
1233 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1235 return CCInfo.CheckReturn(Outs, RetCC_X86);
1239 X86TargetLowering::LowerReturn(SDValue Chain,
1240 CallingConv::ID CallConv, bool isVarArg,
1241 const SmallVectorImpl<ISD::OutputArg> &Outs,
1242 const SmallVectorImpl<SDValue> &OutVals,
1243 DebugLoc dl, SelectionDAG &DAG) const {
1244 MachineFunction &MF = DAG.getMachineFunction();
1245 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1247 SmallVector<CCValAssign, 16> RVLocs;
1248 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1249 RVLocs, *DAG.getContext());
1250 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1252 // Add the regs to the liveout set for the function.
1253 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1254 for (unsigned i = 0; i != RVLocs.size(); ++i)
1255 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1256 MRI.addLiveOut(RVLocs[i].getLocReg());
1260 SmallVector<SDValue, 6> RetOps;
1261 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1262 // Operand #1 = Bytes To Pop
1263 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1266 // Copy the result values into the output registers.
1267 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1268 CCValAssign &VA = RVLocs[i];
1269 assert(VA.isRegLoc() && "Can only return in registers!");
1270 SDValue ValToCopy = OutVals[i];
1271 EVT ValVT = ValToCopy.getValueType();
1273 // If this is x86-64, and we disabled SSE, we can't return FP values,
1274 // or SSE or MMX vectors.
1275 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1276 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1277 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1278 report_fatal_error("SSE register return with SSE disabled");
1280 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1281 // llvm-gcc has never done it right and no one has noticed, so this
1282 // should be OK for now.
1283 if (ValVT == MVT::f64 &&
1284 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1285 report_fatal_error("SSE2 register return with SSE2 disabled");
1287 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1288 // the RET instruction and handled by the FP Stackifier.
1289 if (VA.getLocReg() == X86::ST0 ||
1290 VA.getLocReg() == X86::ST1) {
1291 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1292 // change the value to the FP stack register class.
1293 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1294 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1295 RetOps.push_back(ValToCopy);
1296 // Don't emit a copytoreg.
1300 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1301 // which is returned in RAX / RDX.
1302 if (Subtarget->is64Bit()) {
1303 if (ValVT == MVT::x86mmx) {
1304 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1305 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1306 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1308 // If we don't have SSE2 available, convert to v4f32 so the generated
1309 // register is legal.
1310 if (!Subtarget->hasSSE2())
1311 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1316 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1317 Flag = Chain.getValue(1);
1320 // The x86-64 ABI for returning structs by value requires that we copy
1321 // the sret argument into %rax for the return. We saved the argument into
1322 // a virtual register in the entry block, so now we copy the value out
1324 if (Subtarget->is64Bit() &&
1325 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1326 MachineFunction &MF = DAG.getMachineFunction();
1327 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1328 unsigned Reg = FuncInfo->getSRetReturnReg();
1330 "SRetReturnReg should have been set in LowerFormalArguments().");
1331 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1333 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1334 Flag = Chain.getValue(1);
1336 // RAX now acts like a return value.
1337 MRI.addLiveOut(X86::RAX);
1340 RetOps[0] = Chain; // Update chain.
1342 // Add the flag if we have it.
1344 RetOps.push_back(Flag);
1346 return DAG.getNode(X86ISD::RET_FLAG, dl,
1347 MVT::Other, &RetOps[0], RetOps.size());
1350 /// LowerCallResult - Lower the result values of a call into the
1351 /// appropriate copies out of appropriate physical registers.
1354 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1355 CallingConv::ID CallConv, bool isVarArg,
1356 const SmallVectorImpl<ISD::InputArg> &Ins,
1357 DebugLoc dl, SelectionDAG &DAG,
1358 SmallVectorImpl<SDValue> &InVals) const {
1360 // Assign locations to each value returned by this call.
1361 SmallVector<CCValAssign, 16> RVLocs;
1362 bool Is64Bit = Subtarget->is64Bit();
1363 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1364 RVLocs, *DAG.getContext());
1365 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1367 // Copy all of the result registers out of their specified physreg.
1368 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1369 CCValAssign &VA = RVLocs[i];
1370 EVT CopyVT = VA.getValVT();
1372 // If this is x86-64, and we disabled SSE, we can't return FP values
1373 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1374 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1375 report_fatal_error("SSE register return with SSE disabled");
1380 // If this is a call to a function that returns an fp value on the floating
1381 // point stack, we must guarantee the the value is popped from the stack, so
1382 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1383 // if the return value is not used. We use the FpGET_ST0 instructions
1385 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1386 // If we prefer to use the value in xmm registers, copy it out as f80 and
1387 // use a truncate to move it from fp stack reg to xmm reg.
1388 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1389 bool isST0 = VA.getLocReg() == X86::ST0;
1391 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1392 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1393 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1394 SDValue Ops[] = { Chain, InFlag };
1395 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1397 Val = Chain.getValue(0);
1399 // Round the f80 to the right size, which also moves it to the appropriate
1401 if (CopyVT != VA.getValVT())
1402 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1403 // This truncation won't change the value.
1404 DAG.getIntPtrConstant(1));
1405 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1406 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1407 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1408 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1409 MVT::v2i64, InFlag).getValue(1);
1410 Val = Chain.getValue(0);
1411 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1412 Val, DAG.getConstant(0, MVT::i64));
1414 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1415 MVT::i64, InFlag).getValue(1);
1416 Val = Chain.getValue(0);
1418 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1420 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1421 CopyVT, InFlag).getValue(1);
1422 Val = Chain.getValue(0);
1424 InFlag = Chain.getValue(2);
1425 InVals.push_back(Val);
1432 //===----------------------------------------------------------------------===//
1433 // C & StdCall & Fast Calling Convention implementation
1434 //===----------------------------------------------------------------------===//
1435 // StdCall calling convention seems to be standard for many Windows' API
1436 // routines and around. It differs from C calling convention just a little:
1437 // callee should clean up the stack, not caller. Symbols should be also
1438 // decorated in some fancy way :) It doesn't support any vector arguments.
1439 // For info on fast calling convention see Fast Calling Convention (tail call)
1440 // implementation LowerX86_32FastCCCallTo.
1442 /// CallIsStructReturn - Determines whether a call uses struct return
1444 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1448 return Outs[0].Flags.isSRet();
1451 /// ArgsAreStructReturn - Determines whether a function uses struct
1452 /// return semantics.
1454 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1458 return Ins[0].Flags.isSRet();
1461 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1462 /// by "Src" to address "Dst" with size and alignment information specified by
1463 /// the specific parameter attribute. The copy will be passed as a byval
1464 /// function parameter.
1466 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1467 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1469 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1471 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1472 /*isVolatile*/false, /*AlwaysInline=*/true,
1473 MachinePointerInfo(), MachinePointerInfo());
1476 /// IsTailCallConvention - Return true if the calling convention is one that
1477 /// supports tail call optimization.
1478 static bool IsTailCallConvention(CallingConv::ID CC) {
1479 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1482 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1483 /// a tailcall target by changing its ABI.
1484 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1485 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1489 X86TargetLowering::LowerMemArgument(SDValue Chain,
1490 CallingConv::ID CallConv,
1491 const SmallVectorImpl<ISD::InputArg> &Ins,
1492 DebugLoc dl, SelectionDAG &DAG,
1493 const CCValAssign &VA,
1494 MachineFrameInfo *MFI,
1496 // Create the nodes corresponding to a load from this parameter slot.
1497 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1498 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1499 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1502 // If value is passed by pointer we have address passed instead of the value
1504 if (VA.getLocInfo() == CCValAssign::Indirect)
1505 ValVT = VA.getLocVT();
1507 ValVT = VA.getValVT();
1509 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1510 // changed with more analysis.
1511 // In case of tail call optimization mark all arguments mutable. Since they
1512 // could be overwritten by lowering of arguments in case of a tail call.
1513 if (Flags.isByVal()) {
1514 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1515 VA.getLocMemOffset(), isImmutable);
1516 return DAG.getFrameIndex(FI, getPointerTy());
1518 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1519 VA.getLocMemOffset(), isImmutable);
1520 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1521 return DAG.getLoad(ValVT, dl, Chain, FIN,
1522 MachinePointerInfo::getFixedStack(FI),
1528 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1529 CallingConv::ID CallConv,
1531 const SmallVectorImpl<ISD::InputArg> &Ins,
1534 SmallVectorImpl<SDValue> &InVals)
1536 MachineFunction &MF = DAG.getMachineFunction();
1537 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1539 const Function* Fn = MF.getFunction();
1540 if (Fn->hasExternalLinkage() &&
1541 Subtarget->isTargetCygMing() &&
1542 Fn->getName() == "main")
1543 FuncInfo->setForceFramePointer(true);
1545 MachineFrameInfo *MFI = MF.getFrameInfo();
1546 bool Is64Bit = Subtarget->is64Bit();
1547 bool IsWin64 = Subtarget->isTargetWin64();
1549 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1550 "Var args not supported with calling convention fastcc or ghc");
1552 // Assign locations to all of the incoming arguments.
1553 SmallVector<CCValAssign, 16> ArgLocs;
1554 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1555 ArgLocs, *DAG.getContext());
1556 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1558 unsigned LastVal = ~0U;
1560 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1561 CCValAssign &VA = ArgLocs[i];
1562 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1564 assert(VA.getValNo() != LastVal &&
1565 "Don't support value assigned to multiple locs yet");
1566 LastVal = VA.getValNo();
1568 if (VA.isRegLoc()) {
1569 EVT RegVT = VA.getLocVT();
1570 TargetRegisterClass *RC = NULL;
1571 if (RegVT == MVT::i32)
1572 RC = X86::GR32RegisterClass;
1573 else if (Is64Bit && RegVT == MVT::i64)
1574 RC = X86::GR64RegisterClass;
1575 else if (RegVT == MVT::f32)
1576 RC = X86::FR32RegisterClass;
1577 else if (RegVT == MVT::f64)
1578 RC = X86::FR64RegisterClass;
1579 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1580 RC = X86::VR256RegisterClass;
1581 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1582 RC = X86::VR128RegisterClass;
1583 else if (RegVT == MVT::x86mmx)
1584 RC = X86::VR64RegisterClass;
1586 llvm_unreachable("Unknown argument type!");
1588 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1589 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1591 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1592 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1594 if (VA.getLocInfo() == CCValAssign::SExt)
1595 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1596 DAG.getValueType(VA.getValVT()));
1597 else if (VA.getLocInfo() == CCValAssign::ZExt)
1598 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1599 DAG.getValueType(VA.getValVT()));
1600 else if (VA.getLocInfo() == CCValAssign::BCvt)
1601 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1603 if (VA.isExtInLoc()) {
1604 // Handle MMX values passed in XMM regs.
1605 if (RegVT.isVector()) {
1606 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1609 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1612 assert(VA.isMemLoc());
1613 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1616 // If value is passed via pointer - do a load.
1617 if (VA.getLocInfo() == CCValAssign::Indirect)
1618 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1619 MachinePointerInfo(), false, false, 0);
1621 InVals.push_back(ArgValue);
1624 // The x86-64 ABI for returning structs by value requires that we copy
1625 // the sret argument into %rax for the return. Save the argument into
1626 // a virtual register so that we can access it from the return points.
1627 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1628 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1629 unsigned Reg = FuncInfo->getSRetReturnReg();
1631 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1632 FuncInfo->setSRetReturnReg(Reg);
1634 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1635 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1638 unsigned StackSize = CCInfo.getNextStackOffset();
1639 // Align stack specially for tail calls.
1640 if (FuncIsMadeTailCallSafe(CallConv))
1641 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1643 // If the function takes variable number of arguments, make a frame index for
1644 // the start of the first vararg value... for expansion of llvm.va_start.
1646 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1647 CallConv != CallingConv::X86_ThisCall))) {
1648 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1651 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1653 // FIXME: We should really autogenerate these arrays
1654 static const unsigned GPR64ArgRegsWin64[] = {
1655 X86::RCX, X86::RDX, X86::R8, X86::R9
1657 static const unsigned GPR64ArgRegs64Bit[] = {
1658 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1660 static const unsigned XMMArgRegs64Bit[] = {
1661 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1662 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1664 const unsigned *GPR64ArgRegs;
1665 unsigned NumXMMRegs = 0;
1668 // The XMM registers which might contain var arg parameters are shadowed
1669 // in their paired GPR. So we only need to save the GPR to their home
1671 TotalNumIntRegs = 4;
1672 GPR64ArgRegs = GPR64ArgRegsWin64;
1674 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1675 GPR64ArgRegs = GPR64ArgRegs64Bit;
1677 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1679 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1682 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1683 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1684 "SSE register cannot be used when SSE is disabled!");
1685 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1686 "SSE register cannot be used when SSE is disabled!");
1687 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1688 // Kernel mode asks for SSE to be disabled, so don't push them
1690 TotalNumXMMRegs = 0;
1693 const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1694 // Get to the caller-allocated home save location. Add 8 to account
1695 // for the return address.
1696 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1697 FuncInfo->setRegSaveFrameIndex(
1698 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1699 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1701 // For X86-64, if there are vararg parameters that are passed via
1702 // registers, then we must store them to their spots on the stack so they
1703 // may be loaded by deferencing the result of va_next.
1704 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1705 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1706 FuncInfo->setRegSaveFrameIndex(
1707 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1711 // Store the integer parameter registers.
1712 SmallVector<SDValue, 8> MemOps;
1713 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1715 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1716 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1717 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1718 DAG.getIntPtrConstant(Offset));
1719 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1720 X86::GR64RegisterClass);
1721 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1723 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1724 MachinePointerInfo::getFixedStack(
1725 FuncInfo->getRegSaveFrameIndex(), Offset),
1727 MemOps.push_back(Store);
1731 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1732 // Now store the XMM (fp + vector) parameter registers.
1733 SmallVector<SDValue, 11> SaveXMMOps;
1734 SaveXMMOps.push_back(Chain);
1736 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1737 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1738 SaveXMMOps.push_back(ALVal);
1740 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1741 FuncInfo->getRegSaveFrameIndex()));
1742 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1743 FuncInfo->getVarArgsFPOffset()));
1745 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1746 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1747 X86::VR128RegisterClass);
1748 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1749 SaveXMMOps.push_back(Val);
1751 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1753 &SaveXMMOps[0], SaveXMMOps.size()));
1756 if (!MemOps.empty())
1757 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1758 &MemOps[0], MemOps.size());
1762 // Some CCs need callee pop.
1763 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1764 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1766 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1767 // If this is an sret function, the return should pop the hidden pointer.
1768 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1769 FuncInfo->setBytesToPopOnReturn(4);
1773 // RegSaveFrameIndex is X86-64 only.
1774 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1775 if (CallConv == CallingConv::X86_FastCall ||
1776 CallConv == CallingConv::X86_ThisCall)
1777 // fastcc functions can't have varargs.
1778 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1785 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1786 SDValue StackPtr, SDValue Arg,
1787 DebugLoc dl, SelectionDAG &DAG,
1788 const CCValAssign &VA,
1789 ISD::ArgFlagsTy Flags) const {
1790 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1791 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1792 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1793 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1794 if (Flags.isByVal())
1795 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1797 return DAG.getStore(Chain, dl, Arg, PtrOff,
1798 MachinePointerInfo::getStack(LocMemOffset),
1802 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1803 /// optimization is performed and it is required.
1805 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1806 SDValue &OutRetAddr, SDValue Chain,
1807 bool IsTailCall, bool Is64Bit,
1808 int FPDiff, DebugLoc dl) const {
1809 // Adjust the Return address stack slot.
1810 EVT VT = getPointerTy();
1811 OutRetAddr = getReturnAddressFrameIndex(DAG);
1813 // Load the "old" Return address.
1814 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1816 return SDValue(OutRetAddr.getNode(), 1);
1819 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1820 /// optimization is performed and it is required (FPDiff!=0).
1822 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1823 SDValue Chain, SDValue RetAddrFrIdx,
1824 bool Is64Bit, int FPDiff, DebugLoc dl) {
1825 // Store the return address to the appropriate stack slot.
1826 if (!FPDiff) return Chain;
1827 // Calculate the new stack slot for the return address.
1828 int SlotSize = Is64Bit ? 8 : 4;
1829 int NewReturnAddrFI =
1830 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1831 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1832 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1833 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1834 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1840 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1841 CallingConv::ID CallConv, bool isVarArg,
1843 const SmallVectorImpl<ISD::OutputArg> &Outs,
1844 const SmallVectorImpl<SDValue> &OutVals,
1845 const SmallVectorImpl<ISD::InputArg> &Ins,
1846 DebugLoc dl, SelectionDAG &DAG,
1847 SmallVectorImpl<SDValue> &InVals) const {
1848 MachineFunction &MF = DAG.getMachineFunction();
1849 bool Is64Bit = Subtarget->is64Bit();
1850 bool IsStructRet = CallIsStructReturn(Outs);
1851 bool IsSibcall = false;
1854 // Check if it's really possible to do a tail call.
1855 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1856 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1857 Outs, OutVals, Ins, DAG);
1859 // Sibcalls are automatically detected tailcalls which do not require
1861 if (!GuaranteedTailCallOpt && isTailCall)
1868 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1869 "Var args not supported with calling convention fastcc or ghc");
1871 // Analyze operands of the call, assigning locations to each operand.
1872 SmallVector<CCValAssign, 16> ArgLocs;
1873 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1874 ArgLocs, *DAG.getContext());
1875 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1877 // Get a count of how many bytes are to be pushed on the stack.
1878 unsigned NumBytes = CCInfo.getNextStackOffset();
1880 // This is a sibcall. The memory operands are available in caller's
1881 // own caller's stack.
1883 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1884 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1887 if (isTailCall && !IsSibcall) {
1888 // Lower arguments at fp - stackoffset + fpdiff.
1889 unsigned NumBytesCallerPushed =
1890 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1891 FPDiff = NumBytesCallerPushed - NumBytes;
1893 // Set the delta of movement of the returnaddr stackslot.
1894 // But only set if delta is greater than previous delta.
1895 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1896 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1900 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1902 SDValue RetAddrFrIdx;
1903 // Load return adress for tail calls.
1904 if (isTailCall && FPDiff)
1905 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1906 Is64Bit, FPDiff, dl);
1908 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1909 SmallVector<SDValue, 8> MemOpChains;
1912 // Walk the register/memloc assignments, inserting copies/loads. In the case
1913 // of tail call optimization arguments are handle later.
1914 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1915 CCValAssign &VA = ArgLocs[i];
1916 EVT RegVT = VA.getLocVT();
1917 SDValue Arg = OutVals[i];
1918 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1919 bool isByVal = Flags.isByVal();
1921 // Promote the value if needed.
1922 switch (VA.getLocInfo()) {
1923 default: llvm_unreachable("Unknown loc info!");
1924 case CCValAssign::Full: break;
1925 case CCValAssign::SExt:
1926 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1928 case CCValAssign::ZExt:
1929 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1931 case CCValAssign::AExt:
1932 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1933 // Special case: passing MMX values in XMM registers.
1934 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1935 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1936 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1938 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1940 case CCValAssign::BCvt:
1941 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1943 case CCValAssign::Indirect: {
1944 // Store the argument.
1945 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1946 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1947 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1948 MachinePointerInfo::getFixedStack(FI),
1955 if (VA.isRegLoc()) {
1956 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1957 if (isVarArg && Subtarget->isTargetWin64()) {
1958 // Win64 ABI requires argument XMM reg to be copied to the corresponding
1959 // shadow reg if callee is a varargs function.
1960 unsigned ShadowReg = 0;
1961 switch (VA.getLocReg()) {
1962 case X86::XMM0: ShadowReg = X86::RCX; break;
1963 case X86::XMM1: ShadowReg = X86::RDX; break;
1964 case X86::XMM2: ShadowReg = X86::R8; break;
1965 case X86::XMM3: ShadowReg = X86::R9; break;
1968 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1970 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1971 assert(VA.isMemLoc());
1972 if (StackPtr.getNode() == 0)
1973 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1974 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1975 dl, DAG, VA, Flags));
1979 if (!MemOpChains.empty())
1980 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1981 &MemOpChains[0], MemOpChains.size());
1983 // Build a sequence of copy-to-reg nodes chained together with token chain
1984 // and flag operands which copy the outgoing args into registers.
1986 // Tail call byval lowering might overwrite argument registers so in case of
1987 // tail call optimization the copies to registers are lowered later.
1989 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1990 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1991 RegsToPass[i].second, InFlag);
1992 InFlag = Chain.getValue(1);
1995 if (Subtarget->isPICStyleGOT()) {
1996 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1999 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2000 DAG.getNode(X86ISD::GlobalBaseReg,
2001 DebugLoc(), getPointerTy()),
2003 InFlag = Chain.getValue(1);
2005 // If we are tail calling and generating PIC/GOT style code load the
2006 // address of the callee into ECX. The value in ecx is used as target of
2007 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2008 // for tail calls on PIC/GOT architectures. Normally we would just put the
2009 // address of GOT into ebx and then call target@PLT. But for tail calls
2010 // ebx would be restored (since ebx is callee saved) before jumping to the
2013 // Note: The actual moving to ECX is done further down.
2014 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2015 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2016 !G->getGlobal()->hasProtectedVisibility())
2017 Callee = LowerGlobalAddress(Callee, DAG);
2018 else if (isa<ExternalSymbolSDNode>(Callee))
2019 Callee = LowerExternalSymbol(Callee, DAG);
2023 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2024 // From AMD64 ABI document:
2025 // For calls that may call functions that use varargs or stdargs
2026 // (prototype-less calls or calls to functions containing ellipsis (...) in
2027 // the declaration) %al is used as hidden argument to specify the number
2028 // of SSE registers used. The contents of %al do not need to match exactly
2029 // the number of registers, but must be an ubound on the number of SSE
2030 // registers used and is in the range 0 - 8 inclusive.
2032 // Count the number of XMM registers allocated.
2033 static const unsigned XMMArgRegs[] = {
2034 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2035 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2037 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2038 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2039 && "SSE registers cannot be used when SSE is disabled");
2041 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2042 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2043 InFlag = Chain.getValue(1);
2047 // For tail calls lower the arguments to the 'real' stack slot.
2049 // Force all the incoming stack arguments to be loaded from the stack
2050 // before any new outgoing arguments are stored to the stack, because the
2051 // outgoing stack slots may alias the incoming argument stack slots, and
2052 // the alias isn't otherwise explicit. This is slightly more conservative
2053 // than necessary, because it means that each store effectively depends
2054 // on every argument instead of just those arguments it would clobber.
2055 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2057 SmallVector<SDValue, 8> MemOpChains2;
2060 // Do not flag preceeding copytoreg stuff together with the following stuff.
2062 if (GuaranteedTailCallOpt) {
2063 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2064 CCValAssign &VA = ArgLocs[i];
2067 assert(VA.isMemLoc());
2068 SDValue Arg = OutVals[i];
2069 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2070 // Create frame index.
2071 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2072 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2073 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2074 FIN = DAG.getFrameIndex(FI, getPointerTy());
2076 if (Flags.isByVal()) {
2077 // Copy relative to framepointer.
2078 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2079 if (StackPtr.getNode() == 0)
2080 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2082 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2084 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2088 // Store relative to framepointer.
2089 MemOpChains2.push_back(
2090 DAG.getStore(ArgChain, dl, Arg, FIN,
2091 MachinePointerInfo::getFixedStack(FI),
2097 if (!MemOpChains2.empty())
2098 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2099 &MemOpChains2[0], MemOpChains2.size());
2101 // Copy arguments to their registers.
2102 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2103 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2104 RegsToPass[i].second, InFlag);
2105 InFlag = Chain.getValue(1);
2109 // Store the return address to the appropriate stack slot.
2110 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2114 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2115 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2116 // In the 64-bit large code model, we have to make all calls
2117 // through a register, since the call instruction's 32-bit
2118 // pc-relative offset may not be large enough to hold the whole
2120 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2121 // If the callee is a GlobalAddress node (quite common, every direct call
2122 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2125 // We should use extra load for direct calls to dllimported functions in
2127 const GlobalValue *GV = G->getGlobal();
2128 if (!GV->hasDLLImportLinkage()) {
2129 unsigned char OpFlags = 0;
2131 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2132 // external symbols most go through the PLT in PIC mode. If the symbol
2133 // has hidden or protected visibility, or if it is static or local, then
2134 // we don't need to use the PLT - we can directly call it.
2135 if (Subtarget->isTargetELF() &&
2136 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2137 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2138 OpFlags = X86II::MO_PLT;
2139 } else if (Subtarget->isPICStyleStubAny() &&
2140 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2141 Subtarget->getDarwinVers() < 9) {
2142 // PC-relative references to external symbols should go through $stub,
2143 // unless we're building with the leopard linker or later, which
2144 // automatically synthesizes these stubs.
2145 OpFlags = X86II::MO_DARWIN_STUB;
2148 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2149 G->getOffset(), OpFlags);
2151 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2152 unsigned char OpFlags = 0;
2154 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2155 // symbols should go through the PLT.
2156 if (Subtarget->isTargetELF() &&
2157 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2158 OpFlags = X86II::MO_PLT;
2159 } else if (Subtarget->isPICStyleStubAny() &&
2160 Subtarget->getDarwinVers() < 9) {
2161 // PC-relative references to external symbols should go through $stub,
2162 // unless we're building with the leopard linker or later, which
2163 // automatically synthesizes these stubs.
2164 OpFlags = X86II::MO_DARWIN_STUB;
2167 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2171 // Returns a chain & a flag for retval copy to use.
2172 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2173 SmallVector<SDValue, 8> Ops;
2175 if (!IsSibcall && isTailCall) {
2176 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2177 DAG.getIntPtrConstant(0, true), InFlag);
2178 InFlag = Chain.getValue(1);
2181 Ops.push_back(Chain);
2182 Ops.push_back(Callee);
2185 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2187 // Add argument registers to the end of the list so that they are known live
2189 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2190 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2191 RegsToPass[i].second.getValueType()));
2193 // Add an implicit use GOT pointer in EBX.
2194 if (!isTailCall && Subtarget->isPICStyleGOT())
2195 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2197 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2198 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2199 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2201 if (InFlag.getNode())
2202 Ops.push_back(InFlag);
2206 //// If this is the first return lowered for this function, add the regs
2207 //// to the liveout set for the function.
2208 // This isn't right, although it's probably harmless on x86; liveouts
2209 // should be computed from returns not tail calls. Consider a void
2210 // function making a tail call to a function returning int.
2211 return DAG.getNode(X86ISD::TC_RETURN, dl,
2212 NodeTys, &Ops[0], Ops.size());
2215 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2216 InFlag = Chain.getValue(1);
2218 // Create the CALLSEQ_END node.
2219 unsigned NumBytesForCalleeToPush;
2220 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2221 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2222 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2223 // If this is a call to a struct-return function, the callee
2224 // pops the hidden struct pointer, so we have to push it back.
2225 // This is common for Darwin/X86, Linux & Mingw32 targets.
2226 NumBytesForCalleeToPush = 4;
2228 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2230 // Returns a flag for retval copy to use.
2232 Chain = DAG.getCALLSEQ_END(Chain,
2233 DAG.getIntPtrConstant(NumBytes, true),
2234 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2237 InFlag = Chain.getValue(1);
2240 // Handle result values, copying them out of physregs into vregs that we
2242 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2243 Ins, dl, DAG, InVals);
2247 //===----------------------------------------------------------------------===//
2248 // Fast Calling Convention (tail call) implementation
2249 //===----------------------------------------------------------------------===//
2251 // Like std call, callee cleans arguments, convention except that ECX is
2252 // reserved for storing the tail called function address. Only 2 registers are
2253 // free for argument passing (inreg). Tail call optimization is performed
2255 // * tailcallopt is enabled
2256 // * caller/callee are fastcc
2257 // On X86_64 architecture with GOT-style position independent code only local
2258 // (within module) calls are supported at the moment.
2259 // To keep the stack aligned according to platform abi the function
2260 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2261 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2262 // If a tail called function callee has more arguments than the caller the
2263 // caller needs to make sure that there is room to move the RETADDR to. This is
2264 // achieved by reserving an area the size of the argument delta right after the
2265 // original REtADDR, but before the saved framepointer or the spilled registers
2266 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2278 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2279 /// for a 16 byte align requirement.
2281 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2282 SelectionDAG& DAG) const {
2283 MachineFunction &MF = DAG.getMachineFunction();
2284 const TargetMachine &TM = MF.getTarget();
2285 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2286 unsigned StackAlignment = TFI.getStackAlignment();
2287 uint64_t AlignMask = StackAlignment - 1;
2288 int64_t Offset = StackSize;
2289 uint64_t SlotSize = TD->getPointerSize();
2290 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2291 // Number smaller than 12 so just add the difference.
2292 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2294 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2295 Offset = ((~AlignMask) & Offset) + StackAlignment +
2296 (StackAlignment-SlotSize);
2301 /// MatchingStackOffset - Return true if the given stack call argument is
2302 /// already available in the same position (relatively) of the caller's
2303 /// incoming argument stack.
2305 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2306 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2307 const X86InstrInfo *TII) {
2308 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2310 if (Arg.getOpcode() == ISD::CopyFromReg) {
2311 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2312 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2314 MachineInstr *Def = MRI->getVRegDef(VR);
2317 if (!Flags.isByVal()) {
2318 if (!TII->isLoadFromStackSlot(Def, FI))
2321 unsigned Opcode = Def->getOpcode();
2322 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2323 Def->getOperand(1).isFI()) {
2324 FI = Def->getOperand(1).getIndex();
2325 Bytes = Flags.getByValSize();
2329 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2330 if (Flags.isByVal())
2331 // ByVal argument is passed in as a pointer but it's now being
2332 // dereferenced. e.g.
2333 // define @foo(%struct.X* %A) {
2334 // tail call @bar(%struct.X* byval %A)
2337 SDValue Ptr = Ld->getBasePtr();
2338 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2341 FI = FINode->getIndex();
2345 assert(FI != INT_MAX);
2346 if (!MFI->isFixedObjectIndex(FI))
2348 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2351 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2352 /// for tail call optimization. Targets which want to do tail call
2353 /// optimization should implement this function.
2355 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2356 CallingConv::ID CalleeCC,
2358 bool isCalleeStructRet,
2359 bool isCallerStructRet,
2360 const SmallVectorImpl<ISD::OutputArg> &Outs,
2361 const SmallVectorImpl<SDValue> &OutVals,
2362 const SmallVectorImpl<ISD::InputArg> &Ins,
2363 SelectionDAG& DAG) const {
2364 if (!IsTailCallConvention(CalleeCC) &&
2365 CalleeCC != CallingConv::C)
2368 // If -tailcallopt is specified, make fastcc functions tail-callable.
2369 const MachineFunction &MF = DAG.getMachineFunction();
2370 const Function *CallerF = DAG.getMachineFunction().getFunction();
2371 CallingConv::ID CallerCC = CallerF->getCallingConv();
2372 bool CCMatch = CallerCC == CalleeCC;
2374 if (GuaranteedTailCallOpt) {
2375 if (IsTailCallConvention(CalleeCC) && CCMatch)
2380 // Look for obvious safe cases to perform tail call optimization that do not
2381 // require ABI changes. This is what gcc calls sibcall.
2383 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2384 // emit a special epilogue.
2385 if (RegInfo->needsStackRealignment(MF))
2388 // Do not sibcall optimize vararg calls unless the call site is not passing
2390 if (isVarArg && !Outs.empty())
2393 // Also avoid sibcall optimization if either caller or callee uses struct
2394 // return semantics.
2395 if (isCalleeStructRet || isCallerStructRet)
2398 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2399 // Therefore if it's not used by the call it is not safe to optimize this into
2401 bool Unused = false;
2402 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2409 SmallVector<CCValAssign, 16> RVLocs;
2410 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2411 RVLocs, *DAG.getContext());
2412 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2413 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2414 CCValAssign &VA = RVLocs[i];
2415 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2420 // If the calling conventions do not match, then we'd better make sure the
2421 // results are returned in the same way as what the caller expects.
2423 SmallVector<CCValAssign, 16> RVLocs1;
2424 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2425 RVLocs1, *DAG.getContext());
2426 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2428 SmallVector<CCValAssign, 16> RVLocs2;
2429 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2430 RVLocs2, *DAG.getContext());
2431 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2433 if (RVLocs1.size() != RVLocs2.size())
2435 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2436 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2438 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2440 if (RVLocs1[i].isRegLoc()) {
2441 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2444 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2450 // If the callee takes no arguments then go on to check the results of the
2452 if (!Outs.empty()) {
2453 // Check if stack adjustment is needed. For now, do not do this if any
2454 // argument is passed on the stack.
2455 SmallVector<CCValAssign, 16> ArgLocs;
2456 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2457 ArgLocs, *DAG.getContext());
2458 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2459 if (CCInfo.getNextStackOffset()) {
2460 MachineFunction &MF = DAG.getMachineFunction();
2461 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2463 if (Subtarget->isTargetWin64())
2464 // Win64 ABI has additional complications.
2467 // Check if the arguments are already laid out in the right way as
2468 // the caller's fixed stack objects.
2469 MachineFrameInfo *MFI = MF.getFrameInfo();
2470 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2471 const X86InstrInfo *TII =
2472 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2473 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2474 CCValAssign &VA = ArgLocs[i];
2475 SDValue Arg = OutVals[i];
2476 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2477 if (VA.getLocInfo() == CCValAssign::Indirect)
2479 if (!VA.isRegLoc()) {
2480 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2487 // If the tailcall address may be in a register, then make sure it's
2488 // possible to register allocate for it. In 32-bit, the call address can
2489 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2490 // callee-saved registers are restored. These happen to be the same
2491 // registers used to pass 'inreg' arguments so watch out for those.
2492 if (!Subtarget->is64Bit() &&
2493 !isa<GlobalAddressSDNode>(Callee) &&
2494 !isa<ExternalSymbolSDNode>(Callee)) {
2495 unsigned NumInRegs = 0;
2496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2497 CCValAssign &VA = ArgLocs[i];
2500 unsigned Reg = VA.getLocReg();
2503 case X86::EAX: case X86::EDX: case X86::ECX:
2504 if (++NumInRegs == 3)
2512 // An stdcall caller is expected to clean up its arguments; the callee
2513 // isn't going to do that.
2514 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2521 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2522 return X86::createFastISel(funcInfo);
2526 //===----------------------------------------------------------------------===//
2527 // Other Lowering Hooks
2528 //===----------------------------------------------------------------------===//
2530 static bool MayFoldLoad(SDValue Op) {
2531 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2534 static bool MayFoldIntoStore(SDValue Op) {
2535 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2538 static bool isTargetShuffle(unsigned Opcode) {
2540 default: return false;
2541 case X86ISD::PSHUFD:
2542 case X86ISD::PSHUFHW:
2543 case X86ISD::PSHUFLW:
2544 case X86ISD::SHUFPD:
2545 case X86ISD::PALIGN:
2546 case X86ISD::SHUFPS:
2547 case X86ISD::MOVLHPS:
2548 case X86ISD::MOVLHPD:
2549 case X86ISD::MOVHLPS:
2550 case X86ISD::MOVLPS:
2551 case X86ISD::MOVLPD:
2552 case X86ISD::MOVSHDUP:
2553 case X86ISD::MOVSLDUP:
2554 case X86ISD::MOVDDUP:
2557 case X86ISD::UNPCKLPS:
2558 case X86ISD::UNPCKLPD:
2559 case X86ISD::PUNPCKLWD:
2560 case X86ISD::PUNPCKLBW:
2561 case X86ISD::PUNPCKLDQ:
2562 case X86ISD::PUNPCKLQDQ:
2563 case X86ISD::UNPCKHPS:
2564 case X86ISD::UNPCKHPD:
2565 case X86ISD::PUNPCKHWD:
2566 case X86ISD::PUNPCKHBW:
2567 case X86ISD::PUNPCKHDQ:
2568 case X86ISD::PUNPCKHQDQ:
2574 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2575 SDValue V1, SelectionDAG &DAG) {
2577 default: llvm_unreachable("Unknown x86 shuffle node");
2578 case X86ISD::MOVSHDUP:
2579 case X86ISD::MOVSLDUP:
2580 case X86ISD::MOVDDUP:
2581 return DAG.getNode(Opc, dl, VT, V1);
2587 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2588 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2590 default: llvm_unreachable("Unknown x86 shuffle node");
2591 case X86ISD::PSHUFD:
2592 case X86ISD::PSHUFHW:
2593 case X86ISD::PSHUFLW:
2594 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2600 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2601 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2603 default: llvm_unreachable("Unknown x86 shuffle node");
2604 case X86ISD::PALIGN:
2605 case X86ISD::SHUFPD:
2606 case X86ISD::SHUFPS:
2607 return DAG.getNode(Opc, dl, VT, V1, V2,
2608 DAG.getConstant(TargetMask, MVT::i8));
2613 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2614 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2616 default: llvm_unreachable("Unknown x86 shuffle node");
2617 case X86ISD::MOVLHPS:
2618 case X86ISD::MOVLHPD:
2619 case X86ISD::MOVHLPS:
2620 case X86ISD::MOVLPS:
2621 case X86ISD::MOVLPD:
2624 case X86ISD::UNPCKLPS:
2625 case X86ISD::UNPCKLPD:
2626 case X86ISD::PUNPCKLWD:
2627 case X86ISD::PUNPCKLBW:
2628 case X86ISD::PUNPCKLDQ:
2629 case X86ISD::PUNPCKLQDQ:
2630 case X86ISD::UNPCKHPS:
2631 case X86ISD::UNPCKHPD:
2632 case X86ISD::PUNPCKHWD:
2633 case X86ISD::PUNPCKHBW:
2634 case X86ISD::PUNPCKHDQ:
2635 case X86ISD::PUNPCKHQDQ:
2636 return DAG.getNode(Opc, dl, VT, V1, V2);
2641 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2642 MachineFunction &MF = DAG.getMachineFunction();
2643 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2644 int ReturnAddrIndex = FuncInfo->getRAIndex();
2646 if (ReturnAddrIndex == 0) {
2647 // Set up a frame object for the return address.
2648 uint64_t SlotSize = TD->getPointerSize();
2649 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2651 FuncInfo->setRAIndex(ReturnAddrIndex);
2654 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2658 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2659 bool hasSymbolicDisplacement) {
2660 // Offset should fit into 32 bit immediate field.
2661 if (!isInt<32>(Offset))
2664 // If we don't have a symbolic displacement - we don't have any extra
2666 if (!hasSymbolicDisplacement)
2669 // FIXME: Some tweaks might be needed for medium code model.
2670 if (M != CodeModel::Small && M != CodeModel::Kernel)
2673 // For small code model we assume that latest object is 16MB before end of 31
2674 // bits boundary. We may also accept pretty large negative constants knowing
2675 // that all objects are in the positive half of address space.
2676 if (M == CodeModel::Small && Offset < 16*1024*1024)
2679 // For kernel code model we know that all object resist in the negative half
2680 // of 32bits address space. We may not accept negative offsets, since they may
2681 // be just off and we may accept pretty large positive ones.
2682 if (M == CodeModel::Kernel && Offset > 0)
2688 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2689 /// specific condition code, returning the condition code and the LHS/RHS of the
2690 /// comparison to make.
2691 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2692 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2694 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2695 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2696 // X > -1 -> X == 0, jump !sign.
2697 RHS = DAG.getConstant(0, RHS.getValueType());
2698 return X86::COND_NS;
2699 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2700 // X < 0 -> X == 0, jump on sign.
2702 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2704 RHS = DAG.getConstant(0, RHS.getValueType());
2705 return X86::COND_LE;
2709 switch (SetCCOpcode) {
2710 default: llvm_unreachable("Invalid integer condition!");
2711 case ISD::SETEQ: return X86::COND_E;
2712 case ISD::SETGT: return X86::COND_G;
2713 case ISD::SETGE: return X86::COND_GE;
2714 case ISD::SETLT: return X86::COND_L;
2715 case ISD::SETLE: return X86::COND_LE;
2716 case ISD::SETNE: return X86::COND_NE;
2717 case ISD::SETULT: return X86::COND_B;
2718 case ISD::SETUGT: return X86::COND_A;
2719 case ISD::SETULE: return X86::COND_BE;
2720 case ISD::SETUGE: return X86::COND_AE;
2724 // First determine if it is required or is profitable to flip the operands.
2726 // If LHS is a foldable load, but RHS is not, flip the condition.
2727 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2728 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2729 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2730 std::swap(LHS, RHS);
2733 switch (SetCCOpcode) {
2739 std::swap(LHS, RHS);
2743 // On a floating point condition, the flags are set as follows:
2745 // 0 | 0 | 0 | X > Y
2746 // 0 | 0 | 1 | X < Y
2747 // 1 | 0 | 0 | X == Y
2748 // 1 | 1 | 1 | unordered
2749 switch (SetCCOpcode) {
2750 default: llvm_unreachable("Condcode should be pre-legalized away");
2752 case ISD::SETEQ: return X86::COND_E;
2753 case ISD::SETOLT: // flipped
2755 case ISD::SETGT: return X86::COND_A;
2756 case ISD::SETOLE: // flipped
2758 case ISD::SETGE: return X86::COND_AE;
2759 case ISD::SETUGT: // flipped
2761 case ISD::SETLT: return X86::COND_B;
2762 case ISD::SETUGE: // flipped
2764 case ISD::SETLE: return X86::COND_BE;
2766 case ISD::SETNE: return X86::COND_NE;
2767 case ISD::SETUO: return X86::COND_P;
2768 case ISD::SETO: return X86::COND_NP;
2770 case ISD::SETUNE: return X86::COND_INVALID;
2774 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2775 /// code. Current x86 isa includes the following FP cmov instructions:
2776 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2777 static bool hasFPCMov(unsigned X86CC) {
2793 /// isFPImmLegal - Returns true if the target can instruction select the
2794 /// specified FP immediate natively. If false, the legalizer will
2795 /// materialize the FP immediate as a load from a constant pool.
2796 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2797 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2798 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2804 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2805 /// the specified range (L, H].
2806 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2807 return (Val < 0) || (Val >= Low && Val < Hi);
2810 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2811 /// specified value.
2812 static bool isUndefOrEqual(int Val, int CmpVal) {
2813 if (Val < 0 || Val == CmpVal)
2818 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2819 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2820 /// the second operand.
2821 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2822 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2823 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2824 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2825 return (Mask[0] < 2 && Mask[1] < 2);
2829 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2830 SmallVector<int, 8> M;
2832 return ::isPSHUFDMask(M, N->getValueType(0));
2835 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2836 /// is suitable for input to PSHUFHW.
2837 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2838 if (VT != MVT::v8i16)
2841 // Lower quadword copied in order or undef.
2842 for (int i = 0; i != 4; ++i)
2843 if (Mask[i] >= 0 && Mask[i] != i)
2846 // Upper quadword shuffled.
2847 for (int i = 4; i != 8; ++i)
2848 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2854 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2855 SmallVector<int, 8> M;
2857 return ::isPSHUFHWMask(M, N->getValueType(0));
2860 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2861 /// is suitable for input to PSHUFLW.
2862 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2863 if (VT != MVT::v8i16)
2866 // Upper quadword copied in order.
2867 for (int i = 4; i != 8; ++i)
2868 if (Mask[i] >= 0 && Mask[i] != i)
2871 // Lower quadword shuffled.
2872 for (int i = 0; i != 4; ++i)
2879 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2880 SmallVector<int, 8> M;
2882 return ::isPSHUFLWMask(M, N->getValueType(0));
2885 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2886 /// is suitable for input to PALIGNR.
2887 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2889 int i, e = VT.getVectorNumElements();
2891 // Do not handle v2i64 / v2f64 shuffles with palignr.
2892 if (e < 4 || !hasSSSE3)
2895 for (i = 0; i != e; ++i)
2899 // All undef, not a palignr.
2903 // Determine if it's ok to perform a palignr with only the LHS, since we
2904 // don't have access to the actual shuffle elements to see if RHS is undef.
2905 bool Unary = Mask[i] < (int)e;
2906 bool NeedsUnary = false;
2908 int s = Mask[i] - i;
2910 // Check the rest of the elements to see if they are consecutive.
2911 for (++i; i != e; ++i) {
2916 Unary = Unary && (m < (int)e);
2917 NeedsUnary = NeedsUnary || (m < s);
2919 if (NeedsUnary && !Unary)
2921 if (Unary && m != ((s+i) & (e-1)))
2923 if (!Unary && m != (s+i))
2929 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2930 SmallVector<int, 8> M;
2932 return ::isPALIGNRMask(M, N->getValueType(0), true);
2935 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2936 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2937 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2938 int NumElems = VT.getVectorNumElements();
2939 if (NumElems != 2 && NumElems != 4)
2942 int Half = NumElems / 2;
2943 for (int i = 0; i < Half; ++i)
2944 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2946 for (int i = Half; i < NumElems; ++i)
2947 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2953 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2954 SmallVector<int, 8> M;
2956 return ::isSHUFPMask(M, N->getValueType(0));
2959 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2960 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2961 /// half elements to come from vector 1 (which would equal the dest.) and
2962 /// the upper half to come from vector 2.
2963 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2964 int NumElems = VT.getVectorNumElements();
2966 if (NumElems != 2 && NumElems != 4)
2969 int Half = NumElems / 2;
2970 for (int i = 0; i < Half; ++i)
2971 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2973 for (int i = Half; i < NumElems; ++i)
2974 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2979 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2980 SmallVector<int, 8> M;
2982 return isCommutedSHUFPMask(M, N->getValueType(0));
2985 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2986 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2987 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2988 if (N->getValueType(0).getVectorNumElements() != 4)
2991 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2992 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2993 isUndefOrEqual(N->getMaskElt(1), 7) &&
2994 isUndefOrEqual(N->getMaskElt(2), 2) &&
2995 isUndefOrEqual(N->getMaskElt(3), 3);
2998 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2999 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3001 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3002 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3007 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3008 isUndefOrEqual(N->getMaskElt(1), 3) &&
3009 isUndefOrEqual(N->getMaskElt(2), 2) &&
3010 isUndefOrEqual(N->getMaskElt(3), 3);
3013 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3014 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3015 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3016 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3018 if (NumElems != 2 && NumElems != 4)
3021 for (unsigned i = 0; i < NumElems/2; ++i)
3022 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3025 for (unsigned i = NumElems/2; i < NumElems; ++i)
3026 if (!isUndefOrEqual(N->getMaskElt(i), i))
3032 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3033 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3034 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3035 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3037 if (NumElems != 2 && NumElems != 4)
3040 for (unsigned i = 0; i < NumElems/2; ++i)
3041 if (!isUndefOrEqual(N->getMaskElt(i), i))
3044 for (unsigned i = 0; i < NumElems/2; ++i)
3045 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3051 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3052 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3053 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3054 bool V2IsSplat = false) {
3055 int NumElts = VT.getVectorNumElements();
3056 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3059 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3061 int BitI1 = Mask[i+1];
3062 if (!isUndefOrEqual(BitI, j))
3065 if (!isUndefOrEqual(BitI1, NumElts))
3068 if (!isUndefOrEqual(BitI1, j + NumElts))
3075 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3076 SmallVector<int, 8> M;
3078 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3081 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3082 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3083 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3084 bool V2IsSplat = false) {
3085 int NumElts = VT.getVectorNumElements();
3086 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3089 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3091 int BitI1 = Mask[i+1];
3092 if (!isUndefOrEqual(BitI, j + NumElts/2))
3095 if (isUndefOrEqual(BitI1, NumElts))
3098 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3105 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3106 SmallVector<int, 8> M;
3108 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3111 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3112 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3114 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3115 int NumElems = VT.getVectorNumElements();
3116 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3119 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3121 int BitI1 = Mask[i+1];
3122 if (!isUndefOrEqual(BitI, j))
3124 if (!isUndefOrEqual(BitI1, j))
3130 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3131 SmallVector<int, 8> M;
3133 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3136 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3137 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3139 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3140 int NumElems = VT.getVectorNumElements();
3141 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3144 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3146 int BitI1 = Mask[i+1];
3147 if (!isUndefOrEqual(BitI, j))
3149 if (!isUndefOrEqual(BitI1, j))
3155 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3156 SmallVector<int, 8> M;
3158 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3161 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3162 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3163 /// MOVSD, and MOVD, i.e. setting the lowest element.
3164 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3165 if (VT.getVectorElementType().getSizeInBits() < 32)
3168 int NumElts = VT.getVectorNumElements();
3170 if (!isUndefOrEqual(Mask[0], NumElts))
3173 for (int i = 1; i < NumElts; ++i)
3174 if (!isUndefOrEqual(Mask[i], i))
3180 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3181 SmallVector<int, 8> M;
3183 return ::isMOVLMask(M, N->getValueType(0));
3186 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3187 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3188 /// element of vector 2 and the other elements to come from vector 1 in order.
3189 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3190 bool V2IsSplat = false, bool V2IsUndef = false) {
3191 int NumOps = VT.getVectorNumElements();
3192 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3195 if (!isUndefOrEqual(Mask[0], 0))
3198 for (int i = 1; i < NumOps; ++i)
3199 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3200 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3201 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3207 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3208 bool V2IsUndef = false) {
3209 SmallVector<int, 8> M;
3211 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3214 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3215 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3216 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3217 if (N->getValueType(0).getVectorNumElements() != 4)
3220 // Expect 1, 1, 3, 3
3221 for (unsigned i = 0; i < 2; ++i) {
3222 int Elt = N->getMaskElt(i);
3223 if (Elt >= 0 && Elt != 1)
3228 for (unsigned i = 2; i < 4; ++i) {
3229 int Elt = N->getMaskElt(i);
3230 if (Elt >= 0 && Elt != 3)
3235 // Don't use movshdup if it can be done with a shufps.
3236 // FIXME: verify that matching u, u, 3, 3 is what we want.
3240 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3241 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3242 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3243 if (N->getValueType(0).getVectorNumElements() != 4)
3246 // Expect 0, 0, 2, 2
3247 for (unsigned i = 0; i < 2; ++i)
3248 if (N->getMaskElt(i) > 0)
3252 for (unsigned i = 2; i < 4; ++i) {
3253 int Elt = N->getMaskElt(i);
3254 if (Elt >= 0 && Elt != 2)
3259 // Don't use movsldup if it can be done with a shufps.
3263 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3264 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3265 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3266 int e = N->getValueType(0).getVectorNumElements() / 2;
3268 for (int i = 0; i < e; ++i)
3269 if (!isUndefOrEqual(N->getMaskElt(i), i))
3271 for (int i = 0; i < e; ++i)
3272 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3277 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3278 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3279 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3280 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3281 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3283 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3285 for (int i = 0; i < NumOperands; ++i) {
3286 int Val = SVOp->getMaskElt(NumOperands-i-1);
3287 if (Val < 0) Val = 0;
3288 if (Val >= NumOperands) Val -= NumOperands;
3290 if (i != NumOperands - 1)
3296 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3297 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3298 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3299 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3301 // 8 nodes, but we only care about the last 4.
3302 for (unsigned i = 7; i >= 4; --i) {
3303 int Val = SVOp->getMaskElt(i);
3312 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3313 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3314 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3315 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3317 // 8 nodes, but we only care about the first 4.
3318 for (int i = 3; i >= 0; --i) {
3319 int Val = SVOp->getMaskElt(i);
3328 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3329 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3330 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3331 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3332 EVT VVT = N->getValueType(0);
3333 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3337 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3338 Val = SVOp->getMaskElt(i);
3342 return (Val - i) * EltSize;
3345 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3347 bool X86::isZeroNode(SDValue Elt) {
3348 return ((isa<ConstantSDNode>(Elt) &&
3349 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3350 (isa<ConstantFPSDNode>(Elt) &&
3351 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3354 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3355 /// their permute mask.
3356 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3357 SelectionDAG &DAG) {
3358 EVT VT = SVOp->getValueType(0);
3359 unsigned NumElems = VT.getVectorNumElements();
3360 SmallVector<int, 8> MaskVec;
3362 for (unsigned i = 0; i != NumElems; ++i) {
3363 int idx = SVOp->getMaskElt(i);
3365 MaskVec.push_back(idx);
3366 else if (idx < (int)NumElems)
3367 MaskVec.push_back(idx + NumElems);
3369 MaskVec.push_back(idx - NumElems);
3371 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3372 SVOp->getOperand(0), &MaskVec[0]);
3375 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3376 /// the two vector operands have swapped position.
3377 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3378 unsigned NumElems = VT.getVectorNumElements();
3379 for (unsigned i = 0; i != NumElems; ++i) {
3383 else if (idx < (int)NumElems)
3384 Mask[i] = idx + NumElems;
3386 Mask[i] = idx - NumElems;
3390 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3391 /// match movhlps. The lower half elements should come from upper half of
3392 /// V1 (and in order), and the upper half elements should come from the upper
3393 /// half of V2 (and in order).
3394 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3395 if (Op->getValueType(0).getVectorNumElements() != 4)
3397 for (unsigned i = 0, e = 2; i != e; ++i)
3398 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3400 for (unsigned i = 2; i != 4; ++i)
3401 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3406 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3407 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3409 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3410 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3412 N = N->getOperand(0).getNode();
3413 if (!ISD::isNON_EXTLoad(N))
3416 *LD = cast<LoadSDNode>(N);
3420 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3421 /// match movlp{s|d}. The lower half elements should come from lower half of
3422 /// V1 (and in order), and the upper half elements should come from the upper
3423 /// half of V2 (and in order). And since V1 will become the source of the
3424 /// MOVLP, it must be either a vector load or a scalar load to vector.
3425 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3426 ShuffleVectorSDNode *Op) {
3427 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3429 // Is V2 is a vector load, don't do this transformation. We will try to use
3430 // load folding shufps op.
3431 if (ISD::isNON_EXTLoad(V2))
3434 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3436 if (NumElems != 2 && NumElems != 4)
3438 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3439 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3441 for (unsigned i = NumElems/2; i != NumElems; ++i)
3442 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3447 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3449 static bool isSplatVector(SDNode *N) {
3450 if (N->getOpcode() != ISD::BUILD_VECTOR)
3453 SDValue SplatValue = N->getOperand(0);
3454 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3455 if (N->getOperand(i) != SplatValue)
3460 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3461 /// to an zero vector.
3462 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3463 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3464 SDValue V1 = N->getOperand(0);
3465 SDValue V2 = N->getOperand(1);
3466 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3467 for (unsigned i = 0; i != NumElems; ++i) {
3468 int Idx = N->getMaskElt(i);
3469 if (Idx >= (int)NumElems) {
3470 unsigned Opc = V2.getOpcode();
3471 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3473 if (Opc != ISD::BUILD_VECTOR ||
3474 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3476 } else if (Idx >= 0) {
3477 unsigned Opc = V1.getOpcode();
3478 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3480 if (Opc != ISD::BUILD_VECTOR ||
3481 !X86::isZeroNode(V1.getOperand(Idx)))
3488 /// getZeroVector - Returns a vector of specified type with all zero elements.
3490 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3492 assert(VT.isVector() && "Expected a vector type");
3494 // Always build SSE zero vectors as <4 x i32> bitcasted
3495 // to their dest type. This ensures they get CSE'd.
3497 if (VT.getSizeInBits() == 128) { // SSE
3498 if (HasSSE2) { // SSE2
3499 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3500 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3502 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3503 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3505 } else if (VT.getSizeInBits() == 256) { // AVX
3506 // 256-bit logic and arithmetic instructions in AVX are
3507 // all floating-point, no support for integer ops. Default
3508 // to emitting fp zeroed vectors then.
3509 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3510 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3511 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3513 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3516 /// getOnesVector - Returns a vector of specified type with all bits set.
3518 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3519 assert(VT.isVector() && "Expected a vector type");
3521 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3522 // type. This ensures they get CSE'd.
3523 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3525 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3526 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3530 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3531 /// that point to V2 points to its first element.
3532 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3533 EVT VT = SVOp->getValueType(0);
3534 unsigned NumElems = VT.getVectorNumElements();
3536 bool Changed = false;
3537 SmallVector<int, 8> MaskVec;
3538 SVOp->getMask(MaskVec);
3540 for (unsigned i = 0; i != NumElems; ++i) {
3541 if (MaskVec[i] > (int)NumElems) {
3542 MaskVec[i] = NumElems;
3547 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3548 SVOp->getOperand(1), &MaskVec[0]);
3549 return SDValue(SVOp, 0);
3552 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3553 /// operation of specified width.
3554 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3556 unsigned NumElems = VT.getVectorNumElements();
3557 SmallVector<int, 8> Mask;
3558 Mask.push_back(NumElems);
3559 for (unsigned i = 1; i != NumElems; ++i)
3561 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3564 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3565 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3567 unsigned NumElems = VT.getVectorNumElements();
3568 SmallVector<int, 8> Mask;
3569 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3571 Mask.push_back(i + NumElems);
3573 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3576 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3577 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3579 unsigned NumElems = VT.getVectorNumElements();
3580 unsigned Half = NumElems/2;
3581 SmallVector<int, 8> Mask;
3582 for (unsigned i = 0; i != Half; ++i) {
3583 Mask.push_back(i + Half);
3584 Mask.push_back(i + NumElems + Half);
3586 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3589 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3590 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3591 EVT PVT = MVT::v4f32;
3592 EVT VT = SV->getValueType(0);
3593 DebugLoc dl = SV->getDebugLoc();
3594 SDValue V1 = SV->getOperand(0);
3595 int NumElems = VT.getVectorNumElements();
3596 int EltNo = SV->getSplatIndex();
3598 // unpack elements to the correct location
3599 while (NumElems > 4) {
3600 if (EltNo < NumElems/2) {
3601 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3603 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3604 EltNo -= NumElems/2;
3609 // Perform the splat.
3610 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3611 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3612 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3613 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3616 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3617 /// vector of zero or undef vector. This produces a shuffle where the low
3618 /// element of V2 is swizzled into the zero/undef vector, landing at element
3619 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3620 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3621 bool isZero, bool HasSSE2,
3622 SelectionDAG &DAG) {
3623 EVT VT = V2.getValueType();
3625 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3626 unsigned NumElems = VT.getVectorNumElements();
3627 SmallVector<int, 16> MaskVec;
3628 for (unsigned i = 0; i != NumElems; ++i)
3629 // If this is the insertion idx, put the low elt of V2 here.
3630 MaskVec.push_back(i == Idx ? NumElems : i);
3631 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3634 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3635 /// element of the result of the vector shuffle.
3636 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3639 return SDValue(); // Limit search depth.
3641 SDValue V = SDValue(N, 0);
3642 EVT VT = V.getValueType();
3643 unsigned Opcode = V.getOpcode();
3645 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3646 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3647 Index = SV->getMaskElt(Index);
3650 return DAG.getUNDEF(VT.getVectorElementType());
3652 int NumElems = VT.getVectorNumElements();
3653 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3654 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3657 // Recurse into target specific vector shuffles to find scalars.
3658 if (isTargetShuffle(Opcode)) {
3659 int NumElems = VT.getVectorNumElements();
3660 SmallVector<unsigned, 16> ShuffleMask;
3664 case X86ISD::SHUFPS:
3665 case X86ISD::SHUFPD:
3666 ImmN = N->getOperand(N->getNumOperands()-1);
3667 DecodeSHUFPSMask(NumElems,
3668 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3671 case X86ISD::PUNPCKHBW:
3672 case X86ISD::PUNPCKHWD:
3673 case X86ISD::PUNPCKHDQ:
3674 case X86ISD::PUNPCKHQDQ:
3675 DecodePUNPCKHMask(NumElems, ShuffleMask);
3677 case X86ISD::UNPCKHPS:
3678 case X86ISD::UNPCKHPD:
3679 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3681 case X86ISD::PUNPCKLBW:
3682 case X86ISD::PUNPCKLWD:
3683 case X86ISD::PUNPCKLDQ:
3684 case X86ISD::PUNPCKLQDQ:
3685 DecodePUNPCKLMask(NumElems, ShuffleMask);
3687 case X86ISD::UNPCKLPS:
3688 case X86ISD::UNPCKLPD:
3689 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3691 case X86ISD::MOVHLPS:
3692 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3694 case X86ISD::MOVLHPS:
3695 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3697 case X86ISD::PSHUFD:
3698 ImmN = N->getOperand(N->getNumOperands()-1);
3699 DecodePSHUFMask(NumElems,
3700 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3703 case X86ISD::PSHUFHW:
3704 ImmN = N->getOperand(N->getNumOperands()-1);
3705 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3708 case X86ISD::PSHUFLW:
3709 ImmN = N->getOperand(N->getNumOperands()-1);
3710 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3714 case X86ISD::MOVSD: {
3715 // The index 0 always comes from the first element of the second source,
3716 // this is why MOVSS and MOVSD are used in the first place. The other
3717 // elements come from the other positions of the first source vector.
3718 unsigned OpNum = (Index == 0) ? 1 : 0;
3719 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3723 assert("not implemented for target shuffle node");
3727 Index = ShuffleMask[Index];
3729 return DAG.getUNDEF(VT.getVectorElementType());
3731 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3732 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3736 // Actual nodes that may contain scalar elements
3737 if (Opcode == ISD::BIT_CONVERT) {
3738 V = V.getOperand(0);
3739 EVT SrcVT = V.getValueType();
3740 unsigned NumElems = VT.getVectorNumElements();
3742 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3746 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3747 return (Index == 0) ? V.getOperand(0)
3748 : DAG.getUNDEF(VT.getVectorElementType());
3750 if (V.getOpcode() == ISD::BUILD_VECTOR)
3751 return V.getOperand(Index);
3756 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3757 /// shuffle operation which come from a consecutively from a zero. The
3758 /// search can start in two diferent directions, from left or right.
3760 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3761 bool ZerosFromLeft, SelectionDAG &DAG) {
3764 while (i < NumElems) {
3765 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3766 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3767 if (!(Elt.getNode() &&
3768 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3776 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3777 /// MaskE correspond consecutively to elements from one of the vector operands,
3778 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3780 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3781 int OpIdx, int NumElems, unsigned &OpNum) {
3782 bool SeenV1 = false;
3783 bool SeenV2 = false;
3785 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3786 int Idx = SVOp->getMaskElt(i);
3787 // Ignore undef indicies
3796 // Only accept consecutive elements from the same vector
3797 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3801 OpNum = SeenV1 ? 0 : 1;
3805 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3806 /// logical left shift of a vector.
3807 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3808 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3809 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3810 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3811 false /* check zeros from right */, DAG);
3817 // Considering the elements in the mask that are not consecutive zeros,
3818 // check if they consecutively come from only one of the source vectors.
3820 // V1 = {X, A, B, C} 0
3822 // vector_shuffle V1, V2 <1, 2, 3, X>
3824 if (!isShuffleMaskConsecutive(SVOp,
3825 0, // Mask Start Index
3826 NumElems-NumZeros-1, // Mask End Index
3827 NumZeros, // Where to start looking in the src vector
3828 NumElems, // Number of elements in vector
3829 OpSrc)) // Which source operand ?
3834 ShVal = SVOp->getOperand(OpSrc);
3838 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3839 /// logical left shift of a vector.
3840 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3841 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3842 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3843 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3844 true /* check zeros from left */, DAG);
3850 // Considering the elements in the mask that are not consecutive zeros,
3851 // check if they consecutively come from only one of the source vectors.
3853 // 0 { A, B, X, X } = V2
3855 // vector_shuffle V1, V2 <X, X, 4, 5>
3857 if (!isShuffleMaskConsecutive(SVOp,
3858 NumZeros, // Mask Start Index
3859 NumElems-1, // Mask End Index
3860 0, // Where to start looking in the src vector
3861 NumElems, // Number of elements in vector
3862 OpSrc)) // Which source operand ?
3867 ShVal = SVOp->getOperand(OpSrc);
3871 /// isVectorShift - Returns true if the shuffle can be implemented as a
3872 /// logical left or right shift of a vector.
3873 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3874 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3875 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3876 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3882 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3884 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3885 unsigned NumNonZero, unsigned NumZero,
3887 const TargetLowering &TLI) {
3891 DebugLoc dl = Op.getDebugLoc();
3894 for (unsigned i = 0; i < 16; ++i) {
3895 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3896 if (ThisIsNonZero && First) {
3898 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3900 V = DAG.getUNDEF(MVT::v8i16);
3905 SDValue ThisElt(0, 0), LastElt(0, 0);
3906 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3907 if (LastIsNonZero) {
3908 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3909 MVT::i16, Op.getOperand(i-1));
3911 if (ThisIsNonZero) {
3912 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3913 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3914 ThisElt, DAG.getConstant(8, MVT::i8));
3916 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3920 if (ThisElt.getNode())
3921 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3922 DAG.getIntPtrConstant(i/2));
3926 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3929 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3931 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3932 unsigned NumNonZero, unsigned NumZero,
3934 const TargetLowering &TLI) {
3938 DebugLoc dl = Op.getDebugLoc();
3941 for (unsigned i = 0; i < 8; ++i) {
3942 bool isNonZero = (NonZeros & (1 << i)) != 0;
3946 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3948 V = DAG.getUNDEF(MVT::v8i16);
3951 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3952 MVT::v8i16, V, Op.getOperand(i),
3953 DAG.getIntPtrConstant(i));
3960 /// getVShift - Return a vector logical shift node.
3962 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3963 unsigned NumBits, SelectionDAG &DAG,
3964 const TargetLowering &TLI, DebugLoc dl) {
3965 EVT ShVT = MVT::v2i64;
3966 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3967 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3968 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3969 DAG.getNode(Opc, dl, ShVT, SrcOp,
3970 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3974 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3975 SelectionDAG &DAG) const {
3977 // Check if the scalar load can be widened into a vector load. And if
3978 // the address is "base + cst" see if the cst can be "absorbed" into
3979 // the shuffle mask.
3980 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3981 SDValue Ptr = LD->getBasePtr();
3982 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3984 EVT PVT = LD->getValueType(0);
3985 if (PVT != MVT::i32 && PVT != MVT::f32)
3990 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3991 FI = FINode->getIndex();
3993 } else if (Ptr.getOpcode() == ISD::ADD &&
3994 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3995 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3996 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3997 Offset = Ptr.getConstantOperandVal(1);
3998 Ptr = Ptr.getOperand(0);
4003 SDValue Chain = LD->getChain();
4004 // Make sure the stack object alignment is at least 16.
4005 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4006 if (DAG.InferPtrAlignment(Ptr) < 16) {
4007 if (MFI->isFixedObjectIndex(FI)) {
4008 // Can't change the alignment. FIXME: It's possible to compute
4009 // the exact stack offset and reference FI + adjust offset instead.
4010 // If someone *really* cares about this. That's the way to implement it.
4013 MFI->setObjectAlignment(FI, 16);
4017 // (Offset % 16) must be multiple of 4. Then address is then
4018 // Ptr + (Offset & ~15).
4021 if ((Offset % 16) & 3)
4023 int64_t StartOffset = Offset & ~15;
4025 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4026 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4028 int EltNo = (Offset - StartOffset) >> 2;
4029 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4030 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4031 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4032 LD->getPointerInfo().getWithOffset(StartOffset),
4034 // Canonicalize it to a v4i32 shuffle.
4035 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4036 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4037 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4038 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4044 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4045 /// vector of type 'VT', see if the elements can be replaced by a single large
4046 /// load which has the same value as a build_vector whose operands are 'elts'.
4048 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4050 /// FIXME: we'd also like to handle the case where the last elements are zero
4051 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4052 /// There's even a handy isZeroNode for that purpose.
4053 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4054 DebugLoc &DL, SelectionDAG &DAG) {
4055 EVT EltVT = VT.getVectorElementType();
4056 unsigned NumElems = Elts.size();
4058 LoadSDNode *LDBase = NULL;
4059 unsigned LastLoadedElt = -1U;
4061 // For each element in the initializer, see if we've found a load or an undef.
4062 // If we don't find an initial load element, or later load elements are
4063 // non-consecutive, bail out.
4064 for (unsigned i = 0; i < NumElems; ++i) {
4065 SDValue Elt = Elts[i];
4067 if (!Elt.getNode() ||
4068 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4071 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4073 LDBase = cast<LoadSDNode>(Elt.getNode());
4077 if (Elt.getOpcode() == ISD::UNDEF)
4080 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4081 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4086 // If we have found an entire vector of loads and undefs, then return a large
4087 // load of the entire vector width starting at the base pointer. If we found
4088 // consecutive loads for the low half, generate a vzext_load node.
4089 if (LastLoadedElt == NumElems - 1) {
4090 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4091 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4092 LDBase->getPointerInfo(),
4093 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4094 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4095 LDBase->getPointerInfo(),
4096 LDBase->isVolatile(), LDBase->isNonTemporal(),
4097 LDBase->getAlignment());
4098 } else if (NumElems == 4 && LastLoadedElt == 1) {
4099 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4100 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4101 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4103 LDBase->getMemOperand());
4104 return DAG.getNode(ISD::BIT_CONVERT, DL, VT, ResNode);
4110 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4111 DebugLoc dl = Op.getDebugLoc();
4112 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4113 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4114 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4115 // is present, so AllOnes is ignored.
4116 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4117 (Op.getValueType().getSizeInBits() != 256 &&
4118 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4119 // Canonicalize this to <4 x i32> (SSE) to
4120 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4121 // eliminated on x86-32 hosts.
4122 if (Op.getValueType() == MVT::v4i32)
4125 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4126 return getOnesVector(Op.getValueType(), DAG, dl);
4127 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4130 EVT VT = Op.getValueType();
4131 EVT ExtVT = VT.getVectorElementType();
4132 unsigned EVTBits = ExtVT.getSizeInBits();
4134 unsigned NumElems = Op.getNumOperands();
4135 unsigned NumZero = 0;
4136 unsigned NumNonZero = 0;
4137 unsigned NonZeros = 0;
4138 bool IsAllConstants = true;
4139 SmallSet<SDValue, 8> Values;
4140 for (unsigned i = 0; i < NumElems; ++i) {
4141 SDValue Elt = Op.getOperand(i);
4142 if (Elt.getOpcode() == ISD::UNDEF)
4145 if (Elt.getOpcode() != ISD::Constant &&
4146 Elt.getOpcode() != ISD::ConstantFP)
4147 IsAllConstants = false;
4148 if (X86::isZeroNode(Elt))
4151 NonZeros |= (1 << i);
4156 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4157 if (NumNonZero == 0)
4158 return DAG.getUNDEF(VT);
4160 // Special case for single non-zero, non-undef, element.
4161 if (NumNonZero == 1) {
4162 unsigned Idx = CountTrailingZeros_32(NonZeros);
4163 SDValue Item = Op.getOperand(Idx);
4165 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4166 // the value are obviously zero, truncate the value to i32 and do the
4167 // insertion that way. Only do this if the value is non-constant or if the
4168 // value is a constant being inserted into element 0. It is cheaper to do
4169 // a constant pool load than it is to do a movd + shuffle.
4170 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4171 (!IsAllConstants || Idx == 0)) {
4172 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4174 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4175 EVT VecVT = MVT::v4i32;
4176 unsigned VecElts = 4;
4178 // Truncate the value (which may itself be a constant) to i32, and
4179 // convert it to a vector with movd (S2V+shuffle to zero extend).
4180 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4181 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4182 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4183 Subtarget->hasSSE2(), DAG);
4185 // Now we have our 32-bit value zero extended in the low element of
4186 // a vector. If Idx != 0, swizzle it into place.
4188 SmallVector<int, 4> Mask;
4189 Mask.push_back(Idx);
4190 for (unsigned i = 1; i != VecElts; ++i)
4192 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4193 DAG.getUNDEF(Item.getValueType()),
4196 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4200 // If we have a constant or non-constant insertion into the low element of
4201 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4202 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4203 // depending on what the source datatype is.
4206 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4207 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4208 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4209 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4210 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4211 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4213 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4214 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4215 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4216 EVT MiddleVT = MVT::v4i32;
4217 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4218 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4219 Subtarget->hasSSE2(), DAG);
4220 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4224 // Is it a vector logical left shift?
4225 if (NumElems == 2 && Idx == 1 &&
4226 X86::isZeroNode(Op.getOperand(0)) &&
4227 !X86::isZeroNode(Op.getOperand(1))) {
4228 unsigned NumBits = VT.getSizeInBits();
4229 return getVShift(true, VT,
4230 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4231 VT, Op.getOperand(1)),
4232 NumBits/2, DAG, *this, dl);
4235 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4238 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4239 // is a non-constant being inserted into an element other than the low one,
4240 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4241 // movd/movss) to move this into the low element, then shuffle it into
4243 if (EVTBits == 32) {
4244 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4246 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4247 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4248 Subtarget->hasSSE2(), DAG);
4249 SmallVector<int, 8> MaskVec;
4250 for (unsigned i = 0; i < NumElems; i++)
4251 MaskVec.push_back(i == Idx ? 0 : 1);
4252 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4256 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4257 if (Values.size() == 1) {
4258 if (EVTBits == 32) {
4259 // Instead of a shuffle like this:
4260 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4261 // Check if it's possible to issue this instead.
4262 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4263 unsigned Idx = CountTrailingZeros_32(NonZeros);
4264 SDValue Item = Op.getOperand(Idx);
4265 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4266 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4271 // A vector full of immediates; various special cases are already
4272 // handled, so this is best done with a single constant-pool load.
4276 // Let legalizer expand 2-wide build_vectors.
4277 if (EVTBits == 64) {
4278 if (NumNonZero == 1) {
4279 // One half is zero or undef.
4280 unsigned Idx = CountTrailingZeros_32(NonZeros);
4281 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4282 Op.getOperand(Idx));
4283 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4284 Subtarget->hasSSE2(), DAG);
4289 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4290 if (EVTBits == 8 && NumElems == 16) {
4291 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4293 if (V.getNode()) return V;
4296 if (EVTBits == 16 && NumElems == 8) {
4297 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4299 if (V.getNode()) return V;
4302 // If element VT is == 32 bits, turn it into a number of shuffles.
4303 SmallVector<SDValue, 8> V;
4305 if (NumElems == 4 && NumZero > 0) {
4306 for (unsigned i = 0; i < 4; ++i) {
4307 bool isZero = !(NonZeros & (1 << i));
4309 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4311 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4314 for (unsigned i = 0; i < 2; ++i) {
4315 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4318 V[i] = V[i*2]; // Must be a zero vector.
4321 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4324 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4327 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4332 SmallVector<int, 8> MaskVec;
4333 bool Reverse = (NonZeros & 0x3) == 2;
4334 for (unsigned i = 0; i < 2; ++i)
4335 MaskVec.push_back(Reverse ? 1-i : i);
4336 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4337 for (unsigned i = 0; i < 2; ++i)
4338 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4339 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4342 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4343 // Check for a build vector of consecutive loads.
4344 for (unsigned i = 0; i < NumElems; ++i)
4345 V[i] = Op.getOperand(i);
4347 // Check for elements which are consecutive loads.
4348 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4352 // For SSE 4.1, use insertps to put the high elements into the low element.
4353 if (getSubtarget()->hasSSE41()) {
4355 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4356 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4358 Result = DAG.getUNDEF(VT);
4360 for (unsigned i = 1; i < NumElems; ++i) {
4361 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4362 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4363 Op.getOperand(i), DAG.getIntPtrConstant(i));
4368 // Otherwise, expand into a number of unpckl*, start by extending each of
4369 // our (non-undef) elements to the full vector width with the element in the
4370 // bottom slot of the vector (which generates no code for SSE).
4371 for (unsigned i = 0; i < NumElems; ++i) {
4372 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4373 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4375 V[i] = DAG.getUNDEF(VT);
4378 // Next, we iteratively mix elements, e.g. for v4f32:
4379 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4380 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4381 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4382 unsigned EltStride = NumElems >> 1;
4383 while (EltStride != 0) {
4384 for (unsigned i = 0; i < EltStride; ++i) {
4385 // If V[i+EltStride] is undef and this is the first round of mixing,
4386 // then it is safe to just drop this shuffle: V[i] is already in the
4387 // right place, the one element (since it's the first round) being
4388 // inserted as undef can be dropped. This isn't safe for successive
4389 // rounds because they will permute elements within both vectors.
4390 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4391 EltStride == NumElems/2)
4394 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4404 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4405 // We support concatenate two MMX registers and place them in a MMX
4406 // register. This is better than doing a stack convert.
4407 DebugLoc dl = Op.getDebugLoc();
4408 EVT ResVT = Op.getValueType();
4409 assert(Op.getNumOperands() == 2);
4410 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4411 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4413 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4414 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4415 InVec = Op.getOperand(1);
4416 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4417 unsigned NumElts = ResVT.getVectorNumElements();
4418 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4419 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4420 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4422 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4423 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4424 Mask[0] = 0; Mask[1] = 2;
4425 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4427 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4430 // v8i16 shuffles - Prefer shuffles in the following order:
4431 // 1. [all] pshuflw, pshufhw, optional move
4432 // 2. [ssse3] 1 x pshufb
4433 // 3. [ssse3] 2 x pshufb + 1 x por
4434 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4436 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4437 SelectionDAG &DAG) const {
4438 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4439 SDValue V1 = SVOp->getOperand(0);
4440 SDValue V2 = SVOp->getOperand(1);
4441 DebugLoc dl = SVOp->getDebugLoc();
4442 SmallVector<int, 8> MaskVals;
4444 // Determine if more than 1 of the words in each of the low and high quadwords
4445 // of the result come from the same quadword of one of the two inputs. Undef
4446 // mask values count as coming from any quadword, for better codegen.
4447 SmallVector<unsigned, 4> LoQuad(4);
4448 SmallVector<unsigned, 4> HiQuad(4);
4449 BitVector InputQuads(4);
4450 for (unsigned i = 0; i < 8; ++i) {
4451 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4452 int EltIdx = SVOp->getMaskElt(i);
4453 MaskVals.push_back(EltIdx);
4462 InputQuads.set(EltIdx / 4);
4465 int BestLoQuad = -1;
4466 unsigned MaxQuad = 1;
4467 for (unsigned i = 0; i < 4; ++i) {
4468 if (LoQuad[i] > MaxQuad) {
4470 MaxQuad = LoQuad[i];
4474 int BestHiQuad = -1;
4476 for (unsigned i = 0; i < 4; ++i) {
4477 if (HiQuad[i] > MaxQuad) {
4479 MaxQuad = HiQuad[i];
4483 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4484 // of the two input vectors, shuffle them into one input vector so only a
4485 // single pshufb instruction is necessary. If There are more than 2 input
4486 // quads, disable the next transformation since it does not help SSSE3.
4487 bool V1Used = InputQuads[0] || InputQuads[1];
4488 bool V2Used = InputQuads[2] || InputQuads[3];
4489 if (Subtarget->hasSSSE3()) {
4490 if (InputQuads.count() == 2 && V1Used && V2Used) {
4491 BestLoQuad = InputQuads.find_first();
4492 BestHiQuad = InputQuads.find_next(BestLoQuad);
4494 if (InputQuads.count() > 2) {
4500 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4501 // the shuffle mask. If a quad is scored as -1, that means that it contains
4502 // words from all 4 input quadwords.
4504 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4505 SmallVector<int, 8> MaskV;
4506 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4507 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4508 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4509 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4510 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4511 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4513 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4514 // source words for the shuffle, to aid later transformations.
4515 bool AllWordsInNewV = true;
4516 bool InOrder[2] = { true, true };
4517 for (unsigned i = 0; i != 8; ++i) {
4518 int idx = MaskVals[i];
4520 InOrder[i/4] = false;
4521 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4523 AllWordsInNewV = false;
4527 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4528 if (AllWordsInNewV) {
4529 for (int i = 0; i != 8; ++i) {
4530 int idx = MaskVals[i];
4533 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4534 if ((idx != i) && idx < 4)
4536 if ((idx != i) && idx > 3)
4545 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4546 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4547 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4548 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4549 unsigned TargetMask = 0;
4550 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4551 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4552 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4553 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4554 V1 = NewV.getOperand(0);
4555 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4559 // If we have SSSE3, and all words of the result are from 1 input vector,
4560 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4561 // is present, fall back to case 4.
4562 if (Subtarget->hasSSSE3()) {
4563 SmallVector<SDValue,16> pshufbMask;
4565 // If we have elements from both input vectors, set the high bit of the
4566 // shuffle mask element to zero out elements that come from V2 in the V1
4567 // mask, and elements that come from V1 in the V2 mask, so that the two
4568 // results can be OR'd together.
4569 bool TwoInputs = V1Used && V2Used;
4570 for (unsigned i = 0; i != 8; ++i) {
4571 int EltIdx = MaskVals[i] * 2;
4572 if (TwoInputs && (EltIdx >= 16)) {
4573 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4574 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4577 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4578 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4580 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4581 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4582 DAG.getNode(ISD::BUILD_VECTOR, dl,
4583 MVT::v16i8, &pshufbMask[0], 16));
4585 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4587 // Calculate the shuffle mask for the second input, shuffle it, and
4588 // OR it with the first shuffled input.
4590 for (unsigned i = 0; i != 8; ++i) {
4591 int EltIdx = MaskVals[i] * 2;
4593 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4594 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4597 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4598 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4600 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4601 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4602 DAG.getNode(ISD::BUILD_VECTOR, dl,
4603 MVT::v16i8, &pshufbMask[0], 16));
4604 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4605 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4608 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4609 // and update MaskVals with new element order.
4610 BitVector InOrder(8);
4611 if (BestLoQuad >= 0) {
4612 SmallVector<int, 8> MaskV;
4613 for (int i = 0; i != 4; ++i) {
4614 int idx = MaskVals[i];
4616 MaskV.push_back(-1);
4618 } else if ((idx / 4) == BestLoQuad) {
4619 MaskV.push_back(idx & 3);
4622 MaskV.push_back(-1);
4625 for (unsigned i = 4; i != 8; ++i)
4627 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4630 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4631 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4633 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4637 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4638 // and update MaskVals with the new element order.
4639 if (BestHiQuad >= 0) {
4640 SmallVector<int, 8> MaskV;
4641 for (unsigned i = 0; i != 4; ++i)
4643 for (unsigned i = 4; i != 8; ++i) {
4644 int idx = MaskVals[i];
4646 MaskV.push_back(-1);
4648 } else if ((idx / 4) == BestHiQuad) {
4649 MaskV.push_back((idx & 3) + 4);
4652 MaskV.push_back(-1);
4655 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4658 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4659 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4661 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4665 // In case BestHi & BestLo were both -1, which means each quadword has a word
4666 // from each of the four input quadwords, calculate the InOrder bitvector now
4667 // before falling through to the insert/extract cleanup.
4668 if (BestLoQuad == -1 && BestHiQuad == -1) {
4670 for (int i = 0; i != 8; ++i)
4671 if (MaskVals[i] < 0 || MaskVals[i] == i)
4675 // The other elements are put in the right place using pextrw and pinsrw.
4676 for (unsigned i = 0; i != 8; ++i) {
4679 int EltIdx = MaskVals[i];
4682 SDValue ExtOp = (EltIdx < 8)
4683 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4684 DAG.getIntPtrConstant(EltIdx))
4685 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4686 DAG.getIntPtrConstant(EltIdx - 8));
4687 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4688 DAG.getIntPtrConstant(i));
4693 // v16i8 shuffles - Prefer shuffles in the following order:
4694 // 1. [ssse3] 1 x pshufb
4695 // 2. [ssse3] 2 x pshufb + 1 x por
4696 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4698 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4700 const X86TargetLowering &TLI) {
4701 SDValue V1 = SVOp->getOperand(0);
4702 SDValue V2 = SVOp->getOperand(1);
4703 DebugLoc dl = SVOp->getDebugLoc();
4704 SmallVector<int, 16> MaskVals;
4705 SVOp->getMask(MaskVals);
4707 // If we have SSSE3, case 1 is generated when all result bytes come from
4708 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4709 // present, fall back to case 3.
4710 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4713 for (unsigned i = 0; i < 16; ++i) {
4714 int EltIdx = MaskVals[i];
4723 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4724 if (TLI.getSubtarget()->hasSSSE3()) {
4725 SmallVector<SDValue,16> pshufbMask;
4727 // If all result elements are from one input vector, then only translate
4728 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4730 // Otherwise, we have elements from both input vectors, and must zero out
4731 // elements that come from V2 in the first mask, and V1 in the second mask
4732 // so that we can OR them together.
4733 bool TwoInputs = !(V1Only || V2Only);
4734 for (unsigned i = 0; i != 16; ++i) {
4735 int EltIdx = MaskVals[i];
4736 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4737 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4740 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4742 // If all the elements are from V2, assign it to V1 and return after
4743 // building the first pshufb.
4746 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4747 DAG.getNode(ISD::BUILD_VECTOR, dl,
4748 MVT::v16i8, &pshufbMask[0], 16));
4752 // Calculate the shuffle mask for the second input, shuffle it, and
4753 // OR it with the first shuffled input.
4755 for (unsigned i = 0; i != 16; ++i) {
4756 int EltIdx = MaskVals[i];
4758 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4761 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4763 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4764 DAG.getNode(ISD::BUILD_VECTOR, dl,
4765 MVT::v16i8, &pshufbMask[0], 16));
4766 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4769 // No SSSE3 - Calculate in place words and then fix all out of place words
4770 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4771 // the 16 different words that comprise the two doublequadword input vectors.
4772 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4773 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4774 SDValue NewV = V2Only ? V2 : V1;
4775 for (int i = 0; i != 8; ++i) {
4776 int Elt0 = MaskVals[i*2];
4777 int Elt1 = MaskVals[i*2+1];
4779 // This word of the result is all undef, skip it.
4780 if (Elt0 < 0 && Elt1 < 0)
4783 // This word of the result is already in the correct place, skip it.
4784 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4786 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4789 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4790 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4793 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4794 // using a single extract together, load it and store it.
4795 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4796 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4797 DAG.getIntPtrConstant(Elt1 / 2));
4798 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4799 DAG.getIntPtrConstant(i));
4803 // If Elt1 is defined, extract it from the appropriate source. If the
4804 // source byte is not also odd, shift the extracted word left 8 bits
4805 // otherwise clear the bottom 8 bits if we need to do an or.
4807 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4808 DAG.getIntPtrConstant(Elt1 / 2));
4809 if ((Elt1 & 1) == 0)
4810 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4811 DAG.getConstant(8, TLI.getShiftAmountTy()));
4813 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4814 DAG.getConstant(0xFF00, MVT::i16));
4816 // If Elt0 is defined, extract it from the appropriate source. If the
4817 // source byte is not also even, shift the extracted word right 8 bits. If
4818 // Elt1 was also defined, OR the extracted values together before
4819 // inserting them in the result.
4821 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4822 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4823 if ((Elt0 & 1) != 0)
4824 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4825 DAG.getConstant(8, TLI.getShiftAmountTy()));
4827 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4828 DAG.getConstant(0x00FF, MVT::i16));
4829 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4832 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4833 DAG.getIntPtrConstant(i));
4835 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4838 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4839 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4840 /// done when every pair / quad of shuffle mask elements point to elements in
4841 /// the right sequence. e.g.
4842 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4844 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4845 SelectionDAG &DAG, DebugLoc dl) {
4846 EVT VT = SVOp->getValueType(0);
4847 SDValue V1 = SVOp->getOperand(0);
4848 SDValue V2 = SVOp->getOperand(1);
4849 unsigned NumElems = VT.getVectorNumElements();
4850 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4852 switch (VT.getSimpleVT().SimpleTy) {
4853 default: assert(false && "Unexpected!");
4854 case MVT::v4f32: NewVT = MVT::v2f64; break;
4855 case MVT::v4i32: NewVT = MVT::v2i64; break;
4856 case MVT::v8i16: NewVT = MVT::v4i32; break;
4857 case MVT::v16i8: NewVT = MVT::v4i32; break;
4860 int Scale = NumElems / NewWidth;
4861 SmallVector<int, 8> MaskVec;
4862 for (unsigned i = 0; i < NumElems; i += Scale) {
4864 for (int j = 0; j < Scale; ++j) {
4865 int EltIdx = SVOp->getMaskElt(i+j);
4869 StartIdx = EltIdx - (EltIdx % Scale);
4870 if (EltIdx != StartIdx + j)
4874 MaskVec.push_back(-1);
4876 MaskVec.push_back(StartIdx / Scale);
4879 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4880 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4881 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4884 /// getVZextMovL - Return a zero-extending vector move low node.
4886 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4887 SDValue SrcOp, SelectionDAG &DAG,
4888 const X86Subtarget *Subtarget, DebugLoc dl) {
4889 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4890 LoadSDNode *LD = NULL;
4891 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4892 LD = dyn_cast<LoadSDNode>(SrcOp);
4894 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4896 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4897 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4898 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4899 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4900 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4902 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4903 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4904 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4905 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4913 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4914 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4915 DAG.getNode(ISD::BIT_CONVERT, dl,
4919 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4922 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4923 SDValue V1 = SVOp->getOperand(0);
4924 SDValue V2 = SVOp->getOperand(1);
4925 DebugLoc dl = SVOp->getDebugLoc();
4926 EVT VT = SVOp->getValueType(0);
4928 SmallVector<std::pair<int, int>, 8> Locs;
4930 SmallVector<int, 8> Mask1(4U, -1);
4931 SmallVector<int, 8> PermMask;
4932 SVOp->getMask(PermMask);
4936 for (unsigned i = 0; i != 4; ++i) {
4937 int Idx = PermMask[i];
4939 Locs[i] = std::make_pair(-1, -1);
4941 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4943 Locs[i] = std::make_pair(0, NumLo);
4947 Locs[i] = std::make_pair(1, NumHi);
4949 Mask1[2+NumHi] = Idx;
4955 if (NumLo <= 2 && NumHi <= 2) {
4956 // If no more than two elements come from either vector. This can be
4957 // implemented with two shuffles. First shuffle gather the elements.
4958 // The second shuffle, which takes the first shuffle as both of its
4959 // vector operands, put the elements into the right order.
4960 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4962 SmallVector<int, 8> Mask2(4U, -1);
4964 for (unsigned i = 0; i != 4; ++i) {
4965 if (Locs[i].first == -1)
4968 unsigned Idx = (i < 2) ? 0 : 4;
4969 Idx += Locs[i].first * 2 + Locs[i].second;
4974 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4975 } else if (NumLo == 3 || NumHi == 3) {
4976 // Otherwise, we must have three elements from one vector, call it X, and
4977 // one element from the other, call it Y. First, use a shufps to build an
4978 // intermediate vector with the one element from Y and the element from X
4979 // that will be in the same half in the final destination (the indexes don't
4980 // matter). Then, use a shufps to build the final vector, taking the half
4981 // containing the element from Y from the intermediate, and the other half
4984 // Normalize it so the 3 elements come from V1.
4985 CommuteVectorShuffleMask(PermMask, VT);
4989 // Find the element from V2.
4991 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4992 int Val = PermMask[HiIndex];
4999 Mask1[0] = PermMask[HiIndex];
5001 Mask1[2] = PermMask[HiIndex^1];
5003 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5006 Mask1[0] = PermMask[0];
5007 Mask1[1] = PermMask[1];
5008 Mask1[2] = HiIndex & 1 ? 6 : 4;
5009 Mask1[3] = HiIndex & 1 ? 4 : 6;
5010 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5012 Mask1[0] = HiIndex & 1 ? 2 : 0;
5013 Mask1[1] = HiIndex & 1 ? 0 : 2;
5014 Mask1[2] = PermMask[2];
5015 Mask1[3] = PermMask[3];
5020 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5024 // Break it into (shuffle shuffle_hi, shuffle_lo).
5026 SmallVector<int,8> LoMask(4U, -1);
5027 SmallVector<int,8> HiMask(4U, -1);
5029 SmallVector<int,8> *MaskPtr = &LoMask;
5030 unsigned MaskIdx = 0;
5033 for (unsigned i = 0; i != 4; ++i) {
5040 int Idx = PermMask[i];
5042 Locs[i] = std::make_pair(-1, -1);
5043 } else if (Idx < 4) {
5044 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5045 (*MaskPtr)[LoIdx] = Idx;
5048 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5049 (*MaskPtr)[HiIdx] = Idx;
5054 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5055 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5056 SmallVector<int, 8> MaskOps;
5057 for (unsigned i = 0; i != 4; ++i) {
5058 if (Locs[i].first == -1) {
5059 MaskOps.push_back(-1);
5061 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5062 MaskOps.push_back(Idx);
5065 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5068 static bool MayFoldVectorLoad(SDValue V) {
5069 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5070 V = V.getOperand(0);
5071 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5072 V = V.getOperand(0);
5078 // FIXME: the version above should always be used. Since there's
5079 // a bug where several vector shuffles can't be folded because the
5080 // DAG is not updated during lowering and a node claims to have two
5081 // uses while it only has one, use this version, and let isel match
5082 // another instruction if the load really happens to have more than
5083 // one use. Remove this version after this bug get fixed.
5084 // rdar://8434668, PR8156
5085 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5086 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5087 V = V.getOperand(0);
5088 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5089 V = V.getOperand(0);
5090 if (ISD::isNormalLoad(V.getNode()))
5095 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5096 /// a vector extract, and if both can be later optimized into a single load.
5097 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5098 /// here because otherwise a target specific shuffle node is going to be
5099 /// emitted for this shuffle, and the optimization not done.
5100 /// FIXME: This is probably not the best approach, but fix the problem
5101 /// until the right path is decided.
5103 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5104 const TargetLowering &TLI) {
5105 EVT VT = V.getValueType();
5106 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5108 // Be sure that the vector shuffle is present in a pattern like this:
5109 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5113 SDNode *N = *V.getNode()->use_begin();
5114 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5117 SDValue EltNo = N->getOperand(1);
5118 if (!isa<ConstantSDNode>(EltNo))
5121 // If the bit convert changed the number of elements, it is unsafe
5122 // to examine the mask.
5123 bool HasShuffleIntoBitcast = false;
5124 if (V.getOpcode() == ISD::BIT_CONVERT) {
5125 EVT SrcVT = V.getOperand(0).getValueType();
5126 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5128 V = V.getOperand(0);
5129 HasShuffleIntoBitcast = true;
5132 // Select the input vector, guarding against out of range extract vector.
5133 unsigned NumElems = VT.getVectorNumElements();
5134 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5135 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5136 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5138 // Skip one more bit_convert if necessary
5139 if (V.getOpcode() == ISD::BIT_CONVERT)
5140 V = V.getOperand(0);
5142 if (ISD::isNormalLoad(V.getNode())) {
5143 // Is the original load suitable?
5144 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5146 // FIXME: avoid the multi-use bug that is preventing lots of
5147 // of foldings to be detected, this is still wrong of course, but
5148 // give the temporary desired behavior, and if it happens that
5149 // the load has real more uses, during isel it will not fold, and
5150 // will generate poor code.
5151 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5154 if (!HasShuffleIntoBitcast)
5157 // If there's a bitcast before the shuffle, check if the load type and
5158 // alignment is valid.
5159 unsigned Align = LN0->getAlignment();
5161 TLI.getTargetData()->getABITypeAlignment(
5162 VT.getTypeForEVT(*DAG.getContext()));
5164 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5172 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5173 EVT VT = Op.getValueType();
5175 // Canonizalize to v2f64.
5176 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, V1);
5177 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5178 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5183 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5185 SDValue V1 = Op.getOperand(0);
5186 SDValue V2 = Op.getOperand(1);
5187 EVT VT = Op.getValueType();
5189 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5191 if (HasSSE2 && VT == MVT::v2f64)
5192 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5195 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5199 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5200 SDValue V1 = Op.getOperand(0);
5201 SDValue V2 = Op.getOperand(1);
5202 EVT VT = Op.getValueType();
5204 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5205 "unsupported shuffle type");
5207 if (V2.getOpcode() == ISD::UNDEF)
5211 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5215 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5216 SDValue V1 = Op.getOperand(0);
5217 SDValue V2 = Op.getOperand(1);
5218 EVT VT = Op.getValueType();
5219 unsigned NumElems = VT.getVectorNumElements();
5221 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5222 // operand of these instructions is only memory, so check if there's a
5223 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5225 bool CanFoldLoad = false;
5227 // Trivial case, when V2 comes from a load.
5228 if (MayFoldVectorLoad(V2))
5231 // When V1 is a load, it can be folded later into a store in isel, example:
5232 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5234 // (MOVLPSmr addr:$src1, VR128:$src2)
5235 // So, recognize this potential and also use MOVLPS or MOVLPD
5236 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5240 if (HasSSE2 && NumElems == 2)
5241 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5244 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5247 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5248 // movl and movlp will both match v2i64, but v2i64 is never matched by
5249 // movl earlier because we make it strict to avoid messing with the movlp load
5250 // folding logic (see the code above getMOVLP call). Match it here then,
5251 // this is horrible, but will stay like this until we move all shuffle
5252 // matching to x86 specific nodes. Note that for the 1st condition all
5253 // types are matched with movsd.
5254 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5255 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5257 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5260 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5262 // Invert the operand order and use SHUFPS to match it.
5263 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5264 X86::getShuffleSHUFImmediate(SVOp), DAG);
5267 static inline unsigned getUNPCKLOpcode(EVT VT) {
5268 switch(VT.getSimpleVT().SimpleTy) {
5269 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5270 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5271 case MVT::v4f32: return X86ISD::UNPCKLPS;
5272 case MVT::v2f64: return X86ISD::UNPCKLPD;
5273 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5274 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5276 llvm_unreachable("Unknow type for unpckl");
5281 static inline unsigned getUNPCKHOpcode(EVT VT) {
5282 switch(VT.getSimpleVT().SimpleTy) {
5283 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5284 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5285 case MVT::v4f32: return X86ISD::UNPCKHPS;
5286 case MVT::v2f64: return X86ISD::UNPCKHPD;
5287 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5288 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5290 llvm_unreachable("Unknow type for unpckh");
5296 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5297 const TargetLowering &TLI,
5298 const X86Subtarget *Subtarget) {
5299 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5300 EVT VT = Op.getValueType();
5301 DebugLoc dl = Op.getDebugLoc();
5302 SDValue V1 = Op.getOperand(0);
5303 SDValue V2 = Op.getOperand(1);
5305 if (isZeroShuffle(SVOp))
5306 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5308 // Handle splat operations
5309 if (SVOp->isSplat()) {
5310 // Special case, this is the only place now where it's
5311 // allowed to return a vector_shuffle operation without
5312 // using a target specific node, because *hopefully* it
5313 // will be optimized away by the dag combiner.
5314 if (VT.getVectorNumElements() <= 4 &&
5315 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5318 // Handle splats by matching through known masks
5319 if (VT.getVectorNumElements() <= 4)
5322 // Canonicalize all of the remaining to v4f32.
5323 return PromoteSplat(SVOp, DAG);
5326 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5328 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5329 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5330 if (NewOp.getNode())
5331 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5332 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5333 // FIXME: Figure out a cleaner way to do this.
5334 // Try to make use of movq to zero out the top part.
5335 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5336 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5337 if (NewOp.getNode()) {
5338 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5339 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5340 DAG, Subtarget, dl);
5342 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5343 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5344 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5345 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5346 DAG, Subtarget, dl);
5353 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5354 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5355 SDValue V1 = Op.getOperand(0);
5356 SDValue V2 = Op.getOperand(1);
5357 EVT VT = Op.getValueType();
5358 DebugLoc dl = Op.getDebugLoc();
5359 unsigned NumElems = VT.getVectorNumElements();
5360 bool isMMX = VT.getSizeInBits() == 64;
5361 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5362 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5363 bool V1IsSplat = false;
5364 bool V2IsSplat = false;
5365 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5366 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5367 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5368 MachineFunction &MF = DAG.getMachineFunction();
5369 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5371 // Shuffle operations on MMX not supported.
5375 // Vector shuffle lowering takes 3 steps:
5377 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5378 // narrowing and commutation of operands should be handled.
5379 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5381 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5382 // so the shuffle can be broken into other shuffles and the legalizer can
5383 // try the lowering again.
5385 // The general ideia is that no vector_shuffle operation should be left to
5386 // be matched during isel, all of them must be converted to a target specific
5389 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5390 // narrowing and commutation of operands should be handled. The actual code
5391 // doesn't include all of those, work in progress...
5392 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5393 if (NewOp.getNode())
5396 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5397 // unpckh_undef). Only use pshufd if speed is more important than size.
5398 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5399 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5400 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5401 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5402 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5403 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5405 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5406 RelaxedMayFoldVectorLoad(V1))
5407 return getMOVDDup(Op, dl, V1, DAG);
5409 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5410 return getMOVHighToLow(Op, dl, DAG);
5412 // Use to match splats
5413 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5414 (VT == MVT::v2f64 || VT == MVT::v2i64))
5415 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5417 if (X86::isPSHUFDMask(SVOp)) {
5418 // The actual implementation will match the mask in the if above and then
5419 // during isel it can match several different instructions, not only pshufd
5420 // as its name says, sad but true, emulate the behavior for now...
5421 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5422 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5424 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5426 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5427 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5429 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5430 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5433 if (VT == MVT::v4f32)
5434 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5438 // Check if this can be converted into a logical shift.
5439 bool isLeft = false;
5442 bool isShift = getSubtarget()->hasSSE2() &&
5443 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5444 if (isShift && ShVal.hasOneUse()) {
5445 // If the shifted value has multiple uses, it may be cheaper to use
5446 // v_set0 + movlhps or movhlps, etc.
5447 EVT EltVT = VT.getVectorElementType();
5448 ShAmt *= EltVT.getSizeInBits();
5449 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5452 if (X86::isMOVLMask(SVOp)) {
5455 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5456 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5457 if (!X86::isMOVLPMask(SVOp)) {
5458 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5459 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5461 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5462 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5466 // FIXME: fold these into legal mask.
5467 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5468 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5470 if (X86::isMOVHLPSMask(SVOp))
5471 return getMOVHighToLow(Op, dl, DAG);
5473 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5474 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5476 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5477 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5479 if (X86::isMOVLPMask(SVOp))
5480 return getMOVLP(Op, dl, DAG, HasSSE2);
5482 if (ShouldXformToMOVHLPS(SVOp) ||
5483 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5484 return CommuteVectorShuffle(SVOp, DAG);
5487 // No better options. Use a vshl / vsrl.
5488 EVT EltVT = VT.getVectorElementType();
5489 ShAmt *= EltVT.getSizeInBits();
5490 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5493 bool Commuted = false;
5494 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5495 // 1,1,1,1 -> v8i16 though.
5496 V1IsSplat = isSplatVector(V1.getNode());
5497 V2IsSplat = isSplatVector(V2.getNode());
5499 // Canonicalize the splat or undef, if present, to be on the RHS.
5500 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5501 Op = CommuteVectorShuffle(SVOp, DAG);
5502 SVOp = cast<ShuffleVectorSDNode>(Op);
5503 V1 = SVOp->getOperand(0);
5504 V2 = SVOp->getOperand(1);
5505 std::swap(V1IsSplat, V2IsSplat);
5506 std::swap(V1IsUndef, V2IsUndef);
5510 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5511 // Shuffling low element of v1 into undef, just return v1.
5514 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5515 // the instruction selector will not match, so get a canonical MOVL with
5516 // swapped operands to undo the commute.
5517 return getMOVL(DAG, dl, VT, V2, V1);
5520 if (X86::isUNPCKLMask(SVOp))
5521 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5523 if (X86::isUNPCKHMask(SVOp))
5524 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5527 // Normalize mask so all entries that point to V2 points to its first
5528 // element then try to match unpck{h|l} again. If match, return a
5529 // new vector_shuffle with the corrected mask.
5530 SDValue NewMask = NormalizeMask(SVOp, DAG);
5531 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5532 if (NSVOp != SVOp) {
5533 if (X86::isUNPCKLMask(NSVOp, true)) {
5535 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5542 // Commute is back and try unpck* again.
5543 // FIXME: this seems wrong.
5544 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5545 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5547 if (X86::isUNPCKLMask(NewSVOp))
5548 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5550 if (X86::isUNPCKHMask(NewSVOp))
5551 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5554 // Normalize the node to match x86 shuffle ops if needed
5555 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5556 return CommuteVectorShuffle(SVOp, DAG);
5558 // The checks below are all present in isShuffleMaskLegal, but they are
5559 // inlined here right now to enable us to directly emit target specific
5560 // nodes, and remove one by one until they don't return Op anymore.
5561 SmallVector<int, 16> M;
5564 if (isPALIGNRMask(M, VT, HasSSSE3))
5565 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5566 X86::getShufflePALIGNRImmediate(SVOp),
5569 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5570 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5571 if (VT == MVT::v2f64)
5572 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5573 if (VT == MVT::v2i64)
5574 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5577 if (isPSHUFHWMask(M, VT))
5578 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5579 X86::getShufflePSHUFHWImmediate(SVOp),
5582 if (isPSHUFLWMask(M, VT))
5583 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5584 X86::getShufflePSHUFLWImmediate(SVOp),
5587 if (isSHUFPMask(M, VT)) {
5588 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5589 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5590 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5592 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5593 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5597 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5598 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5599 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5600 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5601 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5602 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5604 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5605 if (VT == MVT::v8i16) {
5606 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5607 if (NewOp.getNode())
5611 if (VT == MVT::v16i8) {
5612 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5613 if (NewOp.getNode())
5617 // Handle all 4 wide cases with a number of shuffles.
5619 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5625 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5626 SelectionDAG &DAG) const {
5627 EVT VT = Op.getValueType();
5628 DebugLoc dl = Op.getDebugLoc();
5629 if (VT.getSizeInBits() == 8) {
5630 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5631 Op.getOperand(0), Op.getOperand(1));
5632 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5633 DAG.getValueType(VT));
5634 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5635 } else if (VT.getSizeInBits() == 16) {
5636 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5637 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5639 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5640 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5641 DAG.getNode(ISD::BIT_CONVERT, dl,
5645 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5646 Op.getOperand(0), Op.getOperand(1));
5647 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5648 DAG.getValueType(VT));
5649 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5650 } else if (VT == MVT::f32) {
5651 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5652 // the result back to FR32 register. It's only worth matching if the
5653 // result has a single use which is a store or a bitcast to i32. And in
5654 // the case of a store, it's not worth it if the index is a constant 0,
5655 // because a MOVSSmr can be used instead, which is smaller and faster.
5656 if (!Op.hasOneUse())
5658 SDNode *User = *Op.getNode()->use_begin();
5659 if ((User->getOpcode() != ISD::STORE ||
5660 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5661 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5662 (User->getOpcode() != ISD::BIT_CONVERT ||
5663 User->getValueType(0) != MVT::i32))
5665 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5666 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5669 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5670 } else if (VT == MVT::i32) {
5671 // ExtractPS works with constant index.
5672 if (isa<ConstantSDNode>(Op.getOperand(1)))
5680 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5681 SelectionDAG &DAG) const {
5682 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5685 if (Subtarget->hasSSE41()) {
5686 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5691 EVT VT = Op.getValueType();
5692 DebugLoc dl = Op.getDebugLoc();
5693 // TODO: handle v16i8.
5694 if (VT.getSizeInBits() == 16) {
5695 SDValue Vec = Op.getOperand(0);
5696 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5698 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5699 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5700 DAG.getNode(ISD::BIT_CONVERT, dl,
5703 // Transform it so it match pextrw which produces a 32-bit result.
5704 EVT EltVT = MVT::i32;
5705 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5706 Op.getOperand(0), Op.getOperand(1));
5707 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5708 DAG.getValueType(VT));
5709 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5710 } else if (VT.getSizeInBits() == 32) {
5711 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5715 // SHUFPS the element to the lowest double word, then movss.
5716 int Mask[4] = { Idx, -1, -1, -1 };
5717 EVT VVT = Op.getOperand(0).getValueType();
5718 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5719 DAG.getUNDEF(VVT), Mask);
5720 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5721 DAG.getIntPtrConstant(0));
5722 } else if (VT.getSizeInBits() == 64) {
5723 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5724 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5725 // to match extract_elt for f64.
5726 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5730 // UNPCKHPD the element to the lowest double word, then movsd.
5731 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5732 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5733 int Mask[2] = { 1, -1 };
5734 EVT VVT = Op.getOperand(0).getValueType();
5735 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5736 DAG.getUNDEF(VVT), Mask);
5737 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5738 DAG.getIntPtrConstant(0));
5745 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5746 SelectionDAG &DAG) const {
5747 EVT VT = Op.getValueType();
5748 EVT EltVT = VT.getVectorElementType();
5749 DebugLoc dl = Op.getDebugLoc();
5751 SDValue N0 = Op.getOperand(0);
5752 SDValue N1 = Op.getOperand(1);
5753 SDValue N2 = Op.getOperand(2);
5755 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5756 isa<ConstantSDNode>(N2)) {
5758 if (VT == MVT::v8i16)
5759 Opc = X86ISD::PINSRW;
5760 else if (VT == MVT::v16i8)
5761 Opc = X86ISD::PINSRB;
5763 Opc = X86ISD::PINSRB;
5765 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5767 if (N1.getValueType() != MVT::i32)
5768 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5769 if (N2.getValueType() != MVT::i32)
5770 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5771 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5772 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5773 // Bits [7:6] of the constant are the source select. This will always be
5774 // zero here. The DAG Combiner may combine an extract_elt index into these
5775 // bits. For example (insert (extract, 3), 2) could be matched by putting
5776 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5777 // Bits [5:4] of the constant are the destination select. This is the
5778 // value of the incoming immediate.
5779 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5780 // combine either bitwise AND or insert of float 0.0 to set these bits.
5781 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5782 // Create this as a scalar to vector..
5783 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5784 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5785 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5786 // PINSR* works with constant index.
5793 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5794 EVT VT = Op.getValueType();
5795 EVT EltVT = VT.getVectorElementType();
5797 if (Subtarget->hasSSE41())
5798 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5800 if (EltVT == MVT::i8)
5803 DebugLoc dl = Op.getDebugLoc();
5804 SDValue N0 = Op.getOperand(0);
5805 SDValue N1 = Op.getOperand(1);
5806 SDValue N2 = Op.getOperand(2);
5808 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5809 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5810 // as its second argument.
5811 if (N1.getValueType() != MVT::i32)
5812 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5813 if (N2.getValueType() != MVT::i32)
5814 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5815 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5821 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5822 DebugLoc dl = Op.getDebugLoc();
5824 if (Op.getValueType() == MVT::v1i64 &&
5825 Op.getOperand(0).getValueType() == MVT::i64)
5826 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5828 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5829 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5830 "Expected an SSE type!");
5831 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5832 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5835 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5836 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5837 // one of the above mentioned nodes. It has to be wrapped because otherwise
5838 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5839 // be used to form addressing mode. These wrapped nodes will be selected
5842 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5843 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5845 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5847 unsigned char OpFlag = 0;
5848 unsigned WrapperKind = X86ISD::Wrapper;
5849 CodeModel::Model M = getTargetMachine().getCodeModel();
5851 if (Subtarget->isPICStyleRIPRel() &&
5852 (M == CodeModel::Small || M == CodeModel::Kernel))
5853 WrapperKind = X86ISD::WrapperRIP;
5854 else if (Subtarget->isPICStyleGOT())
5855 OpFlag = X86II::MO_GOTOFF;
5856 else if (Subtarget->isPICStyleStubPIC())
5857 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5859 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5861 CP->getOffset(), OpFlag);
5862 DebugLoc DL = CP->getDebugLoc();
5863 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5864 // With PIC, the address is actually $g + Offset.
5866 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5867 DAG.getNode(X86ISD::GlobalBaseReg,
5868 DebugLoc(), getPointerTy()),
5875 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5876 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5878 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5880 unsigned char OpFlag = 0;
5881 unsigned WrapperKind = X86ISD::Wrapper;
5882 CodeModel::Model M = getTargetMachine().getCodeModel();
5884 if (Subtarget->isPICStyleRIPRel() &&
5885 (M == CodeModel::Small || M == CodeModel::Kernel))
5886 WrapperKind = X86ISD::WrapperRIP;
5887 else if (Subtarget->isPICStyleGOT())
5888 OpFlag = X86II::MO_GOTOFF;
5889 else if (Subtarget->isPICStyleStubPIC())
5890 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5892 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5894 DebugLoc DL = JT->getDebugLoc();
5895 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5897 // With PIC, the address is actually $g + Offset.
5899 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5900 DAG.getNode(X86ISD::GlobalBaseReg,
5901 DebugLoc(), getPointerTy()),
5909 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5910 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5912 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5914 unsigned char OpFlag = 0;
5915 unsigned WrapperKind = X86ISD::Wrapper;
5916 CodeModel::Model M = getTargetMachine().getCodeModel();
5918 if (Subtarget->isPICStyleRIPRel() &&
5919 (M == CodeModel::Small || M == CodeModel::Kernel))
5920 WrapperKind = X86ISD::WrapperRIP;
5921 else if (Subtarget->isPICStyleGOT())
5922 OpFlag = X86II::MO_GOTOFF;
5923 else if (Subtarget->isPICStyleStubPIC())
5924 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5926 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5928 DebugLoc DL = Op.getDebugLoc();
5929 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5932 // With PIC, the address is actually $g + Offset.
5933 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5934 !Subtarget->is64Bit()) {
5935 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5936 DAG.getNode(X86ISD::GlobalBaseReg,
5937 DebugLoc(), getPointerTy()),
5945 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5946 // Create the TargetBlockAddressAddress node.
5947 unsigned char OpFlags =
5948 Subtarget->ClassifyBlockAddressReference();
5949 CodeModel::Model M = getTargetMachine().getCodeModel();
5950 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5951 DebugLoc dl = Op.getDebugLoc();
5952 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5953 /*isTarget=*/true, OpFlags);
5955 if (Subtarget->isPICStyleRIPRel() &&
5956 (M == CodeModel::Small || M == CodeModel::Kernel))
5957 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5959 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5961 // With PIC, the address is actually $g + Offset.
5962 if (isGlobalRelativeToPICBase(OpFlags)) {
5963 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5964 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5972 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5974 SelectionDAG &DAG) const {
5975 // Create the TargetGlobalAddress node, folding in the constant
5976 // offset if it is legal.
5977 unsigned char OpFlags =
5978 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5979 CodeModel::Model M = getTargetMachine().getCodeModel();
5981 if (OpFlags == X86II::MO_NO_FLAG &&
5982 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5983 // A direct static reference to a global.
5984 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5987 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5990 if (Subtarget->isPICStyleRIPRel() &&
5991 (M == CodeModel::Small || M == CodeModel::Kernel))
5992 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5994 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5996 // With PIC, the address is actually $g + Offset.
5997 if (isGlobalRelativeToPICBase(OpFlags)) {
5998 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5999 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6003 // For globals that require a load from a stub to get the address, emit the
6005 if (isGlobalStubReference(OpFlags))
6006 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6007 MachinePointerInfo::getGOT(), false, false, 0);
6009 // If there was a non-zero offset that we didn't fold, create an explicit
6012 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6013 DAG.getConstant(Offset, getPointerTy()));
6019 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6020 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6021 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6022 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6026 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6027 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6028 unsigned char OperandFlags) {
6029 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6030 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6031 DebugLoc dl = GA->getDebugLoc();
6032 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6033 GA->getValueType(0),
6037 SDValue Ops[] = { Chain, TGA, *InFlag };
6038 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6040 SDValue Ops[] = { Chain, TGA };
6041 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6044 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6045 MFI->setAdjustsStack(true);
6047 SDValue Flag = Chain.getValue(1);
6048 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6051 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6053 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6056 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6057 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6058 DAG.getNode(X86ISD::GlobalBaseReg,
6059 DebugLoc(), PtrVT), InFlag);
6060 InFlag = Chain.getValue(1);
6062 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6065 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6067 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6069 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6070 X86::RAX, X86II::MO_TLSGD);
6073 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6074 // "local exec" model.
6075 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6076 const EVT PtrVT, TLSModel::Model model,
6078 DebugLoc dl = GA->getDebugLoc();
6080 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6081 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6082 is64Bit ? 257 : 256));
6084 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6085 DAG.getIntPtrConstant(0),
6086 MachinePointerInfo(Ptr), false, false, 0);
6088 unsigned char OperandFlags = 0;
6089 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6091 unsigned WrapperKind = X86ISD::Wrapper;
6092 if (model == TLSModel::LocalExec) {
6093 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6094 } else if (is64Bit) {
6095 assert(model == TLSModel::InitialExec);
6096 OperandFlags = X86II::MO_GOTTPOFF;
6097 WrapperKind = X86ISD::WrapperRIP;
6099 assert(model == TLSModel::InitialExec);
6100 OperandFlags = X86II::MO_INDNTPOFF;
6103 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6105 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6106 GA->getValueType(0),
6107 GA->getOffset(), OperandFlags);
6108 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6110 if (model == TLSModel::InitialExec)
6111 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6112 MachinePointerInfo::getGOT(), false, false, 0);
6114 // The address of the thread local variable is the add of the thread
6115 // pointer with the offset of the variable.
6116 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6120 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6122 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6123 const GlobalValue *GV = GA->getGlobal();
6125 if (Subtarget->isTargetELF()) {
6126 // TODO: implement the "local dynamic" model
6127 // TODO: implement the "initial exec"model for pic executables
6129 // If GV is an alias then use the aliasee for determining
6130 // thread-localness.
6131 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6132 GV = GA->resolveAliasedGlobal(false);
6134 TLSModel::Model model
6135 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6138 case TLSModel::GeneralDynamic:
6139 case TLSModel::LocalDynamic: // not implemented
6140 if (Subtarget->is64Bit())
6141 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6142 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6144 case TLSModel::InitialExec:
6145 case TLSModel::LocalExec:
6146 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6147 Subtarget->is64Bit());
6149 } else if (Subtarget->isTargetDarwin()) {
6150 // Darwin only has one model of TLS. Lower to that.
6151 unsigned char OpFlag = 0;
6152 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6153 X86ISD::WrapperRIP : X86ISD::Wrapper;
6155 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6157 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6158 !Subtarget->is64Bit();
6160 OpFlag = X86II::MO_TLVP_PIC_BASE;
6162 OpFlag = X86II::MO_TLVP;
6163 DebugLoc DL = Op.getDebugLoc();
6164 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6166 GA->getOffset(), OpFlag);
6167 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6169 // With PIC32, the address is actually $g + Offset.
6171 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6172 DAG.getNode(X86ISD::GlobalBaseReg,
6173 DebugLoc(), getPointerTy()),
6176 // Lowering the machine isd will make sure everything is in the right
6178 SDValue Args[] = { Offset };
6179 SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6181 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6182 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6183 MFI->setAdjustsStack(true);
6185 // And our return value (tls address) is in the standard call return value
6187 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6188 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6192 "TLS not implemented for this target.");
6194 llvm_unreachable("Unreachable");
6199 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6200 /// take a 2 x i32 value to shift plus a shift amount.
6201 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6202 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6203 EVT VT = Op.getValueType();
6204 unsigned VTBits = VT.getSizeInBits();
6205 DebugLoc dl = Op.getDebugLoc();
6206 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6207 SDValue ShOpLo = Op.getOperand(0);
6208 SDValue ShOpHi = Op.getOperand(1);
6209 SDValue ShAmt = Op.getOperand(2);
6210 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6211 DAG.getConstant(VTBits - 1, MVT::i8))
6212 : DAG.getConstant(0, VT);
6215 if (Op.getOpcode() == ISD::SHL_PARTS) {
6216 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6217 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6219 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6220 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6223 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6224 DAG.getConstant(VTBits, MVT::i8));
6225 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6226 AndNode, DAG.getConstant(0, MVT::i8));
6229 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6230 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6231 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6233 if (Op.getOpcode() == ISD::SHL_PARTS) {
6234 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6235 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6237 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6238 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6241 SDValue Ops[2] = { Lo, Hi };
6242 return DAG.getMergeValues(Ops, 2, dl);
6245 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6246 SelectionDAG &DAG) const {
6247 EVT SrcVT = Op.getOperand(0).getValueType();
6249 if (SrcVT.isVector())
6252 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6253 "Unknown SINT_TO_FP to lower!");
6255 // These are really Legal; return the operand so the caller accepts it as
6257 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6259 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6260 Subtarget->is64Bit()) {
6264 DebugLoc dl = Op.getDebugLoc();
6265 unsigned Size = SrcVT.getSizeInBits()/8;
6266 MachineFunction &MF = DAG.getMachineFunction();
6267 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6268 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6269 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6271 MachinePointerInfo::getFixedStack(SSFI),
6273 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6276 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6278 SelectionDAG &DAG) const {
6280 DebugLoc DL = Op.getDebugLoc();
6282 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6284 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6286 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6288 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6290 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6291 MachineMemOperand *MMO =
6292 DAG.getMachineFunction()
6293 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6294 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6296 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6297 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6299 Tys, Ops, array_lengthof(Ops),
6303 Chain = Result.getValue(1);
6304 SDValue InFlag = Result.getValue(2);
6306 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6307 // shouldn't be necessary except that RFP cannot be live across
6308 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6309 MachineFunction &MF = DAG.getMachineFunction();
6310 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6311 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6312 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6313 Tys = DAG.getVTList(MVT::Other);
6315 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6317 MachineMemOperand *MMO =
6318 DAG.getMachineFunction()
6319 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6320 MachineMemOperand::MOStore, SSFISize, SSFISize);
6322 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6323 Ops, array_lengthof(Ops),
6324 Op.getValueType(), MMO);
6325 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6326 MachinePointerInfo::getFixedStack(SSFI),
6333 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6334 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6335 SelectionDAG &DAG) const {
6336 // This algorithm is not obvious. Here it is in C code, more or less:
6338 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6339 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6340 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6342 // Copy ints to xmm registers.
6343 __m128i xh = _mm_cvtsi32_si128( hi );
6344 __m128i xl = _mm_cvtsi32_si128( lo );
6346 // Combine into low half of a single xmm register.
6347 __m128i x = _mm_unpacklo_epi32( xh, xl );
6351 // Merge in appropriate exponents to give the integer bits the right
6353 x = _mm_unpacklo_epi32( x, exp );
6355 // Subtract away the biases to deal with the IEEE-754 double precision
6357 d = _mm_sub_pd( (__m128d) x, bias );
6359 // All conversions up to here are exact. The correctly rounded result is
6360 // calculated using the current rounding mode using the following
6362 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6363 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6364 // store doesn't really need to be here (except
6365 // maybe to zero the other double)
6370 DebugLoc dl = Op.getDebugLoc();
6371 LLVMContext *Context = DAG.getContext();
6373 // Build some magic constants.
6374 std::vector<Constant*> CV0;
6375 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6376 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6377 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6378 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6379 Constant *C0 = ConstantVector::get(CV0);
6380 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6382 std::vector<Constant*> CV1;
6384 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6386 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6387 Constant *C1 = ConstantVector::get(CV1);
6388 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6390 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6391 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6393 DAG.getIntPtrConstant(1)));
6394 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6395 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6397 DAG.getIntPtrConstant(0)));
6398 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6399 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6400 MachinePointerInfo::getConstantPool(),
6402 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6403 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6404 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6405 MachinePointerInfo::getConstantPool(),
6407 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6409 // Add the halves; easiest way is to swap them into another reg first.
6410 int ShufMask[2] = { 1, -1 };
6411 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6412 DAG.getUNDEF(MVT::v2f64), ShufMask);
6413 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6414 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6415 DAG.getIntPtrConstant(0));
6418 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6419 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6420 SelectionDAG &DAG) const {
6421 DebugLoc dl = Op.getDebugLoc();
6422 // FP constant to bias correct the final result.
6423 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6426 // Load the 32-bit value into an XMM register.
6427 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6428 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6430 DAG.getIntPtrConstant(0)));
6432 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6433 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6434 DAG.getIntPtrConstant(0));
6436 // Or the load with the bias.
6437 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6438 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6439 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6441 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6442 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6443 MVT::v2f64, Bias)));
6444 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6445 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6446 DAG.getIntPtrConstant(0));
6448 // Subtract the bias.
6449 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6451 // Handle final rounding.
6452 EVT DestVT = Op.getValueType();
6454 if (DestVT.bitsLT(MVT::f64)) {
6455 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6456 DAG.getIntPtrConstant(0));
6457 } else if (DestVT.bitsGT(MVT::f64)) {
6458 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6461 // Handle final rounding.
6465 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6466 SelectionDAG &DAG) const {
6467 SDValue N0 = Op.getOperand(0);
6468 DebugLoc dl = Op.getDebugLoc();
6470 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6471 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6472 // the optimization here.
6473 if (DAG.SignBitIsZero(N0))
6474 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6476 EVT SrcVT = N0.getValueType();
6477 EVT DstVT = Op.getValueType();
6478 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6479 return LowerUINT_TO_FP_i64(Op, DAG);
6480 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6481 return LowerUINT_TO_FP_i32(Op, DAG);
6483 // Make a 64-bit buffer, and use it to build an FILD.
6484 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6485 if (SrcVT == MVT::i32) {
6486 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6487 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6488 getPointerTy(), StackSlot, WordOff);
6489 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6490 StackSlot, MachinePointerInfo(),
6492 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6493 OffsetSlot, MachinePointerInfo(),
6495 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6499 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6500 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6501 StackSlot, MachinePointerInfo(),
6503 // For i64 source, we need to add the appropriate power of 2 if the input
6504 // was negative. This is the same as the optimization in
6505 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6506 // we must be careful to do the computation in x87 extended precision, not
6507 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6508 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6509 MachineMemOperand *MMO =
6510 DAG.getMachineFunction()
6511 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6512 MachineMemOperand::MOLoad, 8, 8);
6514 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6515 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6516 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6519 APInt FF(32, 0x5F800000ULL);
6521 // Check whether the sign bit is set.
6522 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6523 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6526 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6527 SDValue FudgePtr = DAG.getConstantPool(
6528 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6531 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6532 SDValue Zero = DAG.getIntPtrConstant(0);
6533 SDValue Four = DAG.getIntPtrConstant(4);
6534 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6536 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6538 // Load the value out, extending it from f32 to f80.
6539 // FIXME: Avoid the extend by constructing the right constant pool?
6540 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6541 FudgePtr, MachinePointerInfo::getConstantPool(),
6542 MVT::f32, false, false, 4);
6543 // Extend everything to 80 bits to force it to be done on x87.
6544 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6545 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6548 std::pair<SDValue,SDValue> X86TargetLowering::
6549 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6550 DebugLoc DL = Op.getDebugLoc();
6552 EVT DstTy = Op.getValueType();
6555 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6559 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6560 DstTy.getSimpleVT() >= MVT::i16 &&
6561 "Unknown FP_TO_SINT to lower!");
6563 // These are really Legal.
6564 if (DstTy == MVT::i32 &&
6565 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6566 return std::make_pair(SDValue(), SDValue());
6567 if (Subtarget->is64Bit() &&
6568 DstTy == MVT::i64 &&
6569 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6570 return std::make_pair(SDValue(), SDValue());
6572 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6574 MachineFunction &MF = DAG.getMachineFunction();
6575 unsigned MemSize = DstTy.getSizeInBits()/8;
6576 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6577 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6582 switch (DstTy.getSimpleVT().SimpleTy) {
6583 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6584 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6585 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6586 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6589 SDValue Chain = DAG.getEntryNode();
6590 SDValue Value = Op.getOperand(0);
6591 EVT TheVT = Op.getOperand(0).getValueType();
6592 if (isScalarFPTypeInSSEReg(TheVT)) {
6593 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6594 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6595 MachinePointerInfo::getFixedStack(SSFI),
6597 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6599 Chain, StackSlot, DAG.getValueType(TheVT)
6602 MachineMemOperand *MMO =
6603 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6604 MachineMemOperand::MOLoad, MemSize, MemSize);
6605 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6607 Chain = Value.getValue(1);
6608 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6609 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6612 MachineMemOperand *MMO =
6613 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6614 MachineMemOperand::MOStore, MemSize, MemSize);
6616 // Build the FP_TO_INT*_IN_MEM
6617 SDValue Ops[] = { Chain, Value, StackSlot };
6618 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6619 Ops, 3, DstTy, MMO);
6621 return std::make_pair(FIST, StackSlot);
6624 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6625 SelectionDAG &DAG) const {
6626 if (Op.getValueType().isVector())
6629 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6630 SDValue FIST = Vals.first, StackSlot = Vals.second;
6631 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6632 if (FIST.getNode() == 0) return Op;
6635 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6636 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6639 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6640 SelectionDAG &DAG) const {
6641 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6642 SDValue FIST = Vals.first, StackSlot = Vals.second;
6643 assert(FIST.getNode() && "Unexpected failure");
6646 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6647 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6650 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6651 SelectionDAG &DAG) const {
6652 LLVMContext *Context = DAG.getContext();
6653 DebugLoc dl = Op.getDebugLoc();
6654 EVT VT = Op.getValueType();
6657 EltVT = VT.getVectorElementType();
6658 std::vector<Constant*> CV;
6659 if (EltVT == MVT::f64) {
6660 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6664 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6670 Constant *C = ConstantVector::get(CV);
6671 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6672 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6673 MachinePointerInfo::getConstantPool(),
6675 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6678 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6679 LLVMContext *Context = DAG.getContext();
6680 DebugLoc dl = Op.getDebugLoc();
6681 EVT VT = Op.getValueType();
6684 EltVT = VT.getVectorElementType();
6685 std::vector<Constant*> CV;
6686 if (EltVT == MVT::f64) {
6687 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6691 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6697 Constant *C = ConstantVector::get(CV);
6698 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6699 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6700 MachinePointerInfo::getConstantPool(),
6702 if (VT.isVector()) {
6703 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6704 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6705 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6707 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6709 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6713 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6714 LLVMContext *Context = DAG.getContext();
6715 SDValue Op0 = Op.getOperand(0);
6716 SDValue Op1 = Op.getOperand(1);
6717 DebugLoc dl = Op.getDebugLoc();
6718 EVT VT = Op.getValueType();
6719 EVT SrcVT = Op1.getValueType();
6721 // If second operand is smaller, extend it first.
6722 if (SrcVT.bitsLT(VT)) {
6723 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6726 // And if it is bigger, shrink it first.
6727 if (SrcVT.bitsGT(VT)) {
6728 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6732 // At this point the operands and the result should have the same
6733 // type, and that won't be f80 since that is not custom lowered.
6735 // First get the sign bit of second operand.
6736 std::vector<Constant*> CV;
6737 if (SrcVT == MVT::f64) {
6738 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6739 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6741 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6742 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6743 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6744 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6746 Constant *C = ConstantVector::get(CV);
6747 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6748 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6749 MachinePointerInfo::getConstantPool(),
6751 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6753 // Shift sign bit right or left if the two operands have different types.
6754 if (SrcVT.bitsGT(VT)) {
6755 // Op0 is MVT::f32, Op1 is MVT::f64.
6756 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6757 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6758 DAG.getConstant(32, MVT::i32));
6759 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6760 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6761 DAG.getIntPtrConstant(0));
6764 // Clear first operand sign bit.
6766 if (VT == MVT::f64) {
6767 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6768 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6770 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6771 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6772 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6773 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6775 C = ConstantVector::get(CV);
6776 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6777 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6778 MachinePointerInfo::getConstantPool(),
6780 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6782 // Or the value with the sign bit.
6783 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6786 /// Emit nodes that will be selected as "test Op0,Op0", or something
6788 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6789 SelectionDAG &DAG) const {
6790 DebugLoc dl = Op.getDebugLoc();
6792 // CF and OF aren't always set the way we want. Determine which
6793 // of these we need.
6794 bool NeedCF = false;
6795 bool NeedOF = false;
6798 case X86::COND_A: case X86::COND_AE:
6799 case X86::COND_B: case X86::COND_BE:
6802 case X86::COND_G: case X86::COND_GE:
6803 case X86::COND_L: case X86::COND_LE:
6804 case X86::COND_O: case X86::COND_NO:
6809 // See if we can use the EFLAGS value from the operand instead of
6810 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6811 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6812 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6813 // Emit a CMP with 0, which is the TEST pattern.
6814 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6815 DAG.getConstant(0, Op.getValueType()));
6817 unsigned Opcode = 0;
6818 unsigned NumOperands = 0;
6819 switch (Op.getNode()->getOpcode()) {
6821 // Due to an isel shortcoming, be conservative if this add is likely to be
6822 // selected as part of a load-modify-store instruction. When the root node
6823 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6824 // uses of other nodes in the match, such as the ADD in this case. This
6825 // leads to the ADD being left around and reselected, with the result being
6826 // two adds in the output. Alas, even if none our users are stores, that
6827 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6828 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6829 // climbing the DAG back to the root, and it doesn't seem to be worth the
6831 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6832 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6833 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6836 if (ConstantSDNode *C =
6837 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6838 // An add of one will be selected as an INC.
6839 if (C->getAPIntValue() == 1) {
6840 Opcode = X86ISD::INC;
6845 // An add of negative one (subtract of one) will be selected as a DEC.
6846 if (C->getAPIntValue().isAllOnesValue()) {
6847 Opcode = X86ISD::DEC;
6853 // Otherwise use a regular EFLAGS-setting add.
6854 Opcode = X86ISD::ADD;
6858 // If the primary and result isn't used, don't bother using X86ISD::AND,
6859 // because a TEST instruction will be better.
6860 bool NonFlagUse = false;
6861 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6862 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6864 unsigned UOpNo = UI.getOperandNo();
6865 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6866 // Look pass truncate.
6867 UOpNo = User->use_begin().getOperandNo();
6868 User = *User->use_begin();
6871 if (User->getOpcode() != ISD::BRCOND &&
6872 User->getOpcode() != ISD::SETCC &&
6873 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6886 // Due to the ISEL shortcoming noted above, be conservative if this op is
6887 // likely to be selected as part of a load-modify-store instruction.
6888 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6889 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6890 if (UI->getOpcode() == ISD::STORE)
6893 // Otherwise use a regular EFLAGS-setting instruction.
6894 switch (Op.getNode()->getOpcode()) {
6895 default: llvm_unreachable("unexpected operator!");
6896 case ISD::SUB: Opcode = X86ISD::SUB; break;
6897 case ISD::OR: Opcode = X86ISD::OR; break;
6898 case ISD::XOR: Opcode = X86ISD::XOR; break;
6899 case ISD::AND: Opcode = X86ISD::AND; break;
6911 return SDValue(Op.getNode(), 1);
6918 // Emit a CMP with 0, which is the TEST pattern.
6919 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6920 DAG.getConstant(0, Op.getValueType()));
6922 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6923 SmallVector<SDValue, 4> Ops;
6924 for (unsigned i = 0; i != NumOperands; ++i)
6925 Ops.push_back(Op.getOperand(i));
6927 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6928 DAG.ReplaceAllUsesWith(Op, New);
6929 return SDValue(New.getNode(), 1);
6932 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6934 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6935 SelectionDAG &DAG) const {
6936 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6937 if (C->getAPIntValue() == 0)
6938 return EmitTest(Op0, X86CC, DAG);
6940 DebugLoc dl = Op0.getDebugLoc();
6941 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6944 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6945 /// if it's possible.
6946 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6947 DebugLoc dl, SelectionDAG &DAG) const {
6948 SDValue Op0 = And.getOperand(0);
6949 SDValue Op1 = And.getOperand(1);
6950 if (Op0.getOpcode() == ISD::TRUNCATE)
6951 Op0 = Op0.getOperand(0);
6952 if (Op1.getOpcode() == ISD::TRUNCATE)
6953 Op1 = Op1.getOperand(0);
6956 if (Op1.getOpcode() == ISD::SHL)
6957 std::swap(Op0, Op1);
6958 if (Op0.getOpcode() == ISD::SHL) {
6959 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6960 if (And00C->getZExtValue() == 1) {
6961 // If we looked past a truncate, check that it's only truncating away
6963 unsigned BitWidth = Op0.getValueSizeInBits();
6964 unsigned AndBitWidth = And.getValueSizeInBits();
6965 if (BitWidth > AndBitWidth) {
6966 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6967 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6968 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6972 RHS = Op0.getOperand(1);
6974 } else if (Op1.getOpcode() == ISD::Constant) {
6975 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6976 SDValue AndLHS = Op0;
6977 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6978 LHS = AndLHS.getOperand(0);
6979 RHS = AndLHS.getOperand(1);
6983 if (LHS.getNode()) {
6984 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6985 // instruction. Since the shift amount is in-range-or-undefined, we know
6986 // that doing a bittest on the i32 value is ok. We extend to i32 because
6987 // the encoding for the i16 version is larger than the i32 version.
6988 // Also promote i16 to i32 for performance / code size reason.
6989 if (LHS.getValueType() == MVT::i8 ||
6990 LHS.getValueType() == MVT::i16)
6991 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6993 // If the operand types disagree, extend the shift amount to match. Since
6994 // BT ignores high bits (like shifts) we can use anyextend.
6995 if (LHS.getValueType() != RHS.getValueType())
6996 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6998 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6999 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7000 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7001 DAG.getConstant(Cond, MVT::i8), BT);
7007 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7008 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7009 SDValue Op0 = Op.getOperand(0);
7010 SDValue Op1 = Op.getOperand(1);
7011 DebugLoc dl = Op.getDebugLoc();
7012 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7014 // Optimize to BT if possible.
7015 // Lower (X & (1 << N)) == 0 to BT(X, N).
7016 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7017 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7018 if (Op0.getOpcode() == ISD::AND &&
7020 Op1.getOpcode() == ISD::Constant &&
7021 cast<ConstantSDNode>(Op1)->isNullValue() &&
7022 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7023 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7024 if (NewSetCC.getNode())
7028 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7029 if (Op0.getOpcode() == X86ISD::SETCC &&
7030 Op1.getOpcode() == ISD::Constant &&
7031 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7032 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7033 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7034 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7035 bool Invert = (CC == ISD::SETNE) ^
7036 cast<ConstantSDNode>(Op1)->isNullValue();
7038 CCode = X86::GetOppositeBranchCondition(CCode);
7039 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7040 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7043 bool isFP = Op1.getValueType().isFloatingPoint();
7044 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7045 if (X86CC == X86::COND_INVALID)
7048 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7050 // Use sbb x, x to materialize carry bit into a GPR.
7051 if (X86CC == X86::COND_B)
7052 return DAG.getNode(ISD::AND, dl, MVT::i8,
7053 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7054 DAG.getConstant(X86CC, MVT::i8), Cond),
7055 DAG.getConstant(1, MVT::i8));
7057 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7058 DAG.getConstant(X86CC, MVT::i8), Cond);
7061 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7063 SDValue Op0 = Op.getOperand(0);
7064 SDValue Op1 = Op.getOperand(1);
7065 SDValue CC = Op.getOperand(2);
7066 EVT VT = Op.getValueType();
7067 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7068 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7069 DebugLoc dl = Op.getDebugLoc();
7073 EVT VT0 = Op0.getValueType();
7074 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7075 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7078 switch (SetCCOpcode) {
7081 case ISD::SETEQ: SSECC = 0; break;
7083 case ISD::SETGT: Swap = true; // Fallthrough
7085 case ISD::SETOLT: SSECC = 1; break;
7087 case ISD::SETGE: Swap = true; // Fallthrough
7089 case ISD::SETOLE: SSECC = 2; break;
7090 case ISD::SETUO: SSECC = 3; break;
7092 case ISD::SETNE: SSECC = 4; break;
7093 case ISD::SETULE: Swap = true;
7094 case ISD::SETUGE: SSECC = 5; break;
7095 case ISD::SETULT: Swap = true;
7096 case ISD::SETUGT: SSECC = 6; break;
7097 case ISD::SETO: SSECC = 7; break;
7100 std::swap(Op0, Op1);
7102 // In the two special cases we can't handle, emit two comparisons.
7104 if (SetCCOpcode == ISD::SETUEQ) {
7106 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7107 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7108 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7110 else if (SetCCOpcode == ISD::SETONE) {
7112 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7113 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7114 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7116 llvm_unreachable("Illegal FP comparison");
7118 // Handle all other FP comparisons here.
7119 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7122 // We are handling one of the integer comparisons here. Since SSE only has
7123 // GT and EQ comparisons for integer, swapping operands and multiple
7124 // operations may be required for some comparisons.
7125 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7126 bool Swap = false, Invert = false, FlipSigns = false;
7128 switch (VT.getSimpleVT().SimpleTy) {
7130 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7131 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7132 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7133 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7136 switch (SetCCOpcode) {
7138 case ISD::SETNE: Invert = true;
7139 case ISD::SETEQ: Opc = EQOpc; break;
7140 case ISD::SETLT: Swap = true;
7141 case ISD::SETGT: Opc = GTOpc; break;
7142 case ISD::SETGE: Swap = true;
7143 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7144 case ISD::SETULT: Swap = true;
7145 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7146 case ISD::SETUGE: Swap = true;
7147 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7150 std::swap(Op0, Op1);
7152 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7153 // bits of the inputs before performing those operations.
7155 EVT EltVT = VT.getVectorElementType();
7156 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7158 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7159 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7161 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7162 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7165 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7167 // If the logical-not of the result is required, perform that now.
7169 Result = DAG.getNOT(dl, Result, VT);
7174 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7175 static bool isX86LogicalCmp(SDValue Op) {
7176 unsigned Opc = Op.getNode()->getOpcode();
7177 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7179 if (Op.getResNo() == 1 &&
7180 (Opc == X86ISD::ADD ||
7181 Opc == X86ISD::SUB ||
7182 Opc == X86ISD::SMUL ||
7183 Opc == X86ISD::UMUL ||
7184 Opc == X86ISD::INC ||
7185 Opc == X86ISD::DEC ||
7186 Opc == X86ISD::OR ||
7187 Opc == X86ISD::XOR ||
7188 Opc == X86ISD::AND))
7194 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7195 bool addTest = true;
7196 SDValue Cond = Op.getOperand(0);
7197 DebugLoc dl = Op.getDebugLoc();
7200 if (Cond.getOpcode() == ISD::SETCC) {
7201 SDValue NewCond = LowerSETCC(Cond, DAG);
7202 if (NewCond.getNode())
7206 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7207 SDValue Op1 = Op.getOperand(1);
7208 SDValue Op2 = Op.getOperand(2);
7209 if (Cond.getOpcode() == X86ISD::SETCC &&
7210 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7211 SDValue Cmp = Cond.getOperand(1);
7212 if (Cmp.getOpcode() == X86ISD::CMP) {
7213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7214 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7215 ConstantSDNode *RHSC =
7216 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7217 if (N1C && N1C->isAllOnesValue() &&
7218 N2C && N2C->isNullValue() &&
7219 RHSC && RHSC->isNullValue()) {
7220 SDValue CmpOp0 = Cmp.getOperand(0);
7221 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7222 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7223 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7224 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7229 // Look pass (and (setcc_carry (cmp ...)), 1).
7230 if (Cond.getOpcode() == ISD::AND &&
7231 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7232 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7233 if (C && C->getAPIntValue() == 1)
7234 Cond = Cond.getOperand(0);
7237 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7238 // setting operand in place of the X86ISD::SETCC.
7239 if (Cond.getOpcode() == X86ISD::SETCC ||
7240 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7241 CC = Cond.getOperand(0);
7243 SDValue Cmp = Cond.getOperand(1);
7244 unsigned Opc = Cmp.getOpcode();
7245 EVT VT = Op.getValueType();
7247 bool IllegalFPCMov = false;
7248 if (VT.isFloatingPoint() && !VT.isVector() &&
7249 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7250 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7252 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7253 Opc == X86ISD::BT) { // FIXME
7260 // Look pass the truncate.
7261 if (Cond.getOpcode() == ISD::TRUNCATE)
7262 Cond = Cond.getOperand(0);
7264 // We know the result of AND is compared against zero. Try to match
7266 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7267 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7268 if (NewSetCC.getNode()) {
7269 CC = NewSetCC.getOperand(0);
7270 Cond = NewSetCC.getOperand(1);
7277 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7278 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7281 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7282 // condition is true.
7283 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7284 SDValue Ops[] = { Op2, Op1, CC, Cond };
7285 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7288 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7289 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7290 // from the AND / OR.
7291 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7292 Opc = Op.getOpcode();
7293 if (Opc != ISD::OR && Opc != ISD::AND)
7295 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7296 Op.getOperand(0).hasOneUse() &&
7297 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7298 Op.getOperand(1).hasOneUse());
7301 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7302 // 1 and that the SETCC node has a single use.
7303 static bool isXor1OfSetCC(SDValue Op) {
7304 if (Op.getOpcode() != ISD::XOR)
7306 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7307 if (N1C && N1C->getAPIntValue() == 1) {
7308 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7309 Op.getOperand(0).hasOneUse();
7314 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7315 bool addTest = true;
7316 SDValue Chain = Op.getOperand(0);
7317 SDValue Cond = Op.getOperand(1);
7318 SDValue Dest = Op.getOperand(2);
7319 DebugLoc dl = Op.getDebugLoc();
7322 if (Cond.getOpcode() == ISD::SETCC) {
7323 SDValue NewCond = LowerSETCC(Cond, DAG);
7324 if (NewCond.getNode())
7328 // FIXME: LowerXALUO doesn't handle these!!
7329 else if (Cond.getOpcode() == X86ISD::ADD ||
7330 Cond.getOpcode() == X86ISD::SUB ||
7331 Cond.getOpcode() == X86ISD::SMUL ||
7332 Cond.getOpcode() == X86ISD::UMUL)
7333 Cond = LowerXALUO(Cond, DAG);
7336 // Look pass (and (setcc_carry (cmp ...)), 1).
7337 if (Cond.getOpcode() == ISD::AND &&
7338 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7339 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7340 if (C && C->getAPIntValue() == 1)
7341 Cond = Cond.getOperand(0);
7344 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7345 // setting operand in place of the X86ISD::SETCC.
7346 if (Cond.getOpcode() == X86ISD::SETCC ||
7347 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7348 CC = Cond.getOperand(0);
7350 SDValue Cmp = Cond.getOperand(1);
7351 unsigned Opc = Cmp.getOpcode();
7352 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7353 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7357 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7361 // These can only come from an arithmetic instruction with overflow,
7362 // e.g. SADDO, UADDO.
7363 Cond = Cond.getNode()->getOperand(1);
7370 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7371 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7372 if (CondOpc == ISD::OR) {
7373 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7374 // two branches instead of an explicit OR instruction with a
7376 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7377 isX86LogicalCmp(Cmp)) {
7378 CC = Cond.getOperand(0).getOperand(0);
7379 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7380 Chain, Dest, CC, Cmp);
7381 CC = Cond.getOperand(1).getOperand(0);
7385 } else { // ISD::AND
7386 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7387 // two branches instead of an explicit AND instruction with a
7388 // separate test. However, we only do this if this block doesn't
7389 // have a fall-through edge, because this requires an explicit
7390 // jmp when the condition is false.
7391 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7392 isX86LogicalCmp(Cmp) &&
7393 Op.getNode()->hasOneUse()) {
7394 X86::CondCode CCode =
7395 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7396 CCode = X86::GetOppositeBranchCondition(CCode);
7397 CC = DAG.getConstant(CCode, MVT::i8);
7398 SDNode *User = *Op.getNode()->use_begin();
7399 // Look for an unconditional branch following this conditional branch.
7400 // We need this because we need to reverse the successors in order
7401 // to implement FCMP_OEQ.
7402 if (User->getOpcode() == ISD::BR) {
7403 SDValue FalseBB = User->getOperand(1);
7405 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7406 assert(NewBR == User);
7410 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7411 Chain, Dest, CC, Cmp);
7412 X86::CondCode CCode =
7413 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7414 CCode = X86::GetOppositeBranchCondition(CCode);
7415 CC = DAG.getConstant(CCode, MVT::i8);
7421 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7422 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7423 // It should be transformed during dag combiner except when the condition
7424 // is set by a arithmetics with overflow node.
7425 X86::CondCode CCode =
7426 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7427 CCode = X86::GetOppositeBranchCondition(CCode);
7428 CC = DAG.getConstant(CCode, MVT::i8);
7429 Cond = Cond.getOperand(0).getOperand(1);
7435 // Look pass the truncate.
7436 if (Cond.getOpcode() == ISD::TRUNCATE)
7437 Cond = Cond.getOperand(0);
7439 // We know the result of AND is compared against zero. Try to match
7441 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7442 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7443 if (NewSetCC.getNode()) {
7444 CC = NewSetCC.getOperand(0);
7445 Cond = NewSetCC.getOperand(1);
7452 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7453 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7455 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7456 Chain, Dest, CC, Cond);
7460 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7461 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7462 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7463 // that the guard pages used by the OS virtual memory manager are allocated in
7464 // correct sequence.
7466 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7467 SelectionDAG &DAG) const {
7468 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7469 "This should be used only on Windows targets");
7470 DebugLoc dl = Op.getDebugLoc();
7473 SDValue Chain = Op.getOperand(0);
7474 SDValue Size = Op.getOperand(1);
7475 // FIXME: Ensure alignment here
7479 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7481 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7482 Flag = Chain.getValue(1);
7484 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7486 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7487 Flag = Chain.getValue(1);
7489 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7491 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7492 return DAG.getMergeValues(Ops1, 2, dl);
7495 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7496 MachineFunction &MF = DAG.getMachineFunction();
7497 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7499 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7500 DebugLoc DL = Op.getDebugLoc();
7502 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7503 // vastart just stores the address of the VarArgsFrameIndex slot into the
7504 // memory location argument.
7505 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7507 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7508 MachinePointerInfo(SV), false, false, 0);
7512 // gp_offset (0 - 6 * 8)
7513 // fp_offset (48 - 48 + 8 * 16)
7514 // overflow_arg_area (point to parameters coming in memory).
7516 SmallVector<SDValue, 8> MemOps;
7517 SDValue FIN = Op.getOperand(1);
7519 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7520 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7522 FIN, MachinePointerInfo(SV), false, false, 0);
7523 MemOps.push_back(Store);
7526 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7527 FIN, DAG.getIntPtrConstant(4));
7528 Store = DAG.getStore(Op.getOperand(0), DL,
7529 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7531 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7532 MemOps.push_back(Store);
7534 // Store ptr to overflow_arg_area
7535 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7536 FIN, DAG.getIntPtrConstant(4));
7537 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7539 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7540 MachinePointerInfo(SV, 8),
7542 MemOps.push_back(Store);
7544 // Store ptr to reg_save_area.
7545 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7546 FIN, DAG.getIntPtrConstant(8));
7547 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7549 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7550 MachinePointerInfo(SV, 16), false, false, 0);
7551 MemOps.push_back(Store);
7552 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7553 &MemOps[0], MemOps.size());
7556 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7557 assert(Subtarget->is64Bit() &&
7558 "LowerVAARG only handles 64-bit va_arg!");
7559 assert((Subtarget->isTargetLinux() ||
7560 Subtarget->isTargetDarwin()) &&
7561 "Unhandled target in LowerVAARG");
7562 assert(Op.getNode()->getNumOperands() == 4);
7563 SDValue Chain = Op.getOperand(0);
7564 SDValue SrcPtr = Op.getOperand(1);
7565 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7566 unsigned Align = Op.getConstantOperandVal(3);
7567 DebugLoc dl = Op.getDebugLoc();
7569 EVT ArgVT = Op.getNode()->getValueType(0);
7570 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7571 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7574 // Decide which area this value should be read from.
7575 // TODO: Implement the AMD64 ABI in its entirety. This simple
7576 // selection mechanism works only for the basic types.
7577 if (ArgVT == MVT::f80) {
7578 llvm_unreachable("va_arg for f80 not yet implemented");
7579 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7580 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
7581 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7582 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
7584 llvm_unreachable("Unhandled argument type in LowerVAARG");
7588 // Sanity Check: Make sure using fp_offset makes sense.
7589 assert(!UseSoftFloat &&
7590 !(DAG.getMachineFunction()
7591 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7592 Subtarget->hasSSE1());
7595 // Insert VAARG_64 node into the DAG
7596 // VAARG_64 returns two values: Variable Argument Address, Chain
7597 SmallVector<SDValue, 11> InstOps;
7598 InstOps.push_back(Chain);
7599 InstOps.push_back(SrcPtr);
7600 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7601 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7602 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7603 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7604 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7605 VTs, &InstOps[0], InstOps.size(),
7607 MachinePointerInfo(SV),
7612 Chain = VAARG.getValue(1);
7614 // Load the next argument and return it
7615 return DAG.getLoad(ArgVT, dl,
7618 MachinePointerInfo(),
7622 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7623 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7624 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7625 SDValue Chain = Op.getOperand(0);
7626 SDValue DstPtr = Op.getOperand(1);
7627 SDValue SrcPtr = Op.getOperand(2);
7628 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7629 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7630 DebugLoc DL = Op.getDebugLoc();
7632 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7633 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7635 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7639 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7640 DebugLoc dl = Op.getDebugLoc();
7641 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7643 default: return SDValue(); // Don't custom lower most intrinsics.
7644 // Comparison intrinsics.
7645 case Intrinsic::x86_sse_comieq_ss:
7646 case Intrinsic::x86_sse_comilt_ss:
7647 case Intrinsic::x86_sse_comile_ss:
7648 case Intrinsic::x86_sse_comigt_ss:
7649 case Intrinsic::x86_sse_comige_ss:
7650 case Intrinsic::x86_sse_comineq_ss:
7651 case Intrinsic::x86_sse_ucomieq_ss:
7652 case Intrinsic::x86_sse_ucomilt_ss:
7653 case Intrinsic::x86_sse_ucomile_ss:
7654 case Intrinsic::x86_sse_ucomigt_ss:
7655 case Intrinsic::x86_sse_ucomige_ss:
7656 case Intrinsic::x86_sse_ucomineq_ss:
7657 case Intrinsic::x86_sse2_comieq_sd:
7658 case Intrinsic::x86_sse2_comilt_sd:
7659 case Intrinsic::x86_sse2_comile_sd:
7660 case Intrinsic::x86_sse2_comigt_sd:
7661 case Intrinsic::x86_sse2_comige_sd:
7662 case Intrinsic::x86_sse2_comineq_sd:
7663 case Intrinsic::x86_sse2_ucomieq_sd:
7664 case Intrinsic::x86_sse2_ucomilt_sd:
7665 case Intrinsic::x86_sse2_ucomile_sd:
7666 case Intrinsic::x86_sse2_ucomigt_sd:
7667 case Intrinsic::x86_sse2_ucomige_sd:
7668 case Intrinsic::x86_sse2_ucomineq_sd: {
7670 ISD::CondCode CC = ISD::SETCC_INVALID;
7673 case Intrinsic::x86_sse_comieq_ss:
7674 case Intrinsic::x86_sse2_comieq_sd:
7678 case Intrinsic::x86_sse_comilt_ss:
7679 case Intrinsic::x86_sse2_comilt_sd:
7683 case Intrinsic::x86_sse_comile_ss:
7684 case Intrinsic::x86_sse2_comile_sd:
7688 case Intrinsic::x86_sse_comigt_ss:
7689 case Intrinsic::x86_sse2_comigt_sd:
7693 case Intrinsic::x86_sse_comige_ss:
7694 case Intrinsic::x86_sse2_comige_sd:
7698 case Intrinsic::x86_sse_comineq_ss:
7699 case Intrinsic::x86_sse2_comineq_sd:
7703 case Intrinsic::x86_sse_ucomieq_ss:
7704 case Intrinsic::x86_sse2_ucomieq_sd:
7705 Opc = X86ISD::UCOMI;
7708 case Intrinsic::x86_sse_ucomilt_ss:
7709 case Intrinsic::x86_sse2_ucomilt_sd:
7710 Opc = X86ISD::UCOMI;
7713 case Intrinsic::x86_sse_ucomile_ss:
7714 case Intrinsic::x86_sse2_ucomile_sd:
7715 Opc = X86ISD::UCOMI;
7718 case Intrinsic::x86_sse_ucomigt_ss:
7719 case Intrinsic::x86_sse2_ucomigt_sd:
7720 Opc = X86ISD::UCOMI;
7723 case Intrinsic::x86_sse_ucomige_ss:
7724 case Intrinsic::x86_sse2_ucomige_sd:
7725 Opc = X86ISD::UCOMI;
7728 case Intrinsic::x86_sse_ucomineq_ss:
7729 case Intrinsic::x86_sse2_ucomineq_sd:
7730 Opc = X86ISD::UCOMI;
7735 SDValue LHS = Op.getOperand(1);
7736 SDValue RHS = Op.getOperand(2);
7737 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7738 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7739 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7740 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7741 DAG.getConstant(X86CC, MVT::i8), Cond);
7742 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7744 // ptest and testp intrinsics. The intrinsic these come from are designed to
7745 // return an integer value, not just an instruction so lower it to the ptest
7746 // or testp pattern and a setcc for the result.
7747 case Intrinsic::x86_sse41_ptestz:
7748 case Intrinsic::x86_sse41_ptestc:
7749 case Intrinsic::x86_sse41_ptestnzc:
7750 case Intrinsic::x86_avx_ptestz_256:
7751 case Intrinsic::x86_avx_ptestc_256:
7752 case Intrinsic::x86_avx_ptestnzc_256:
7753 case Intrinsic::x86_avx_vtestz_ps:
7754 case Intrinsic::x86_avx_vtestc_ps:
7755 case Intrinsic::x86_avx_vtestnzc_ps:
7756 case Intrinsic::x86_avx_vtestz_pd:
7757 case Intrinsic::x86_avx_vtestc_pd:
7758 case Intrinsic::x86_avx_vtestnzc_pd:
7759 case Intrinsic::x86_avx_vtestz_ps_256:
7760 case Intrinsic::x86_avx_vtestc_ps_256:
7761 case Intrinsic::x86_avx_vtestnzc_ps_256:
7762 case Intrinsic::x86_avx_vtestz_pd_256:
7763 case Intrinsic::x86_avx_vtestc_pd_256:
7764 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7765 bool IsTestPacked = false;
7768 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7769 case Intrinsic::x86_avx_vtestz_ps:
7770 case Intrinsic::x86_avx_vtestz_pd:
7771 case Intrinsic::x86_avx_vtestz_ps_256:
7772 case Intrinsic::x86_avx_vtestz_pd_256:
7773 IsTestPacked = true; // Fallthrough
7774 case Intrinsic::x86_sse41_ptestz:
7775 case Intrinsic::x86_avx_ptestz_256:
7777 X86CC = X86::COND_E;
7779 case Intrinsic::x86_avx_vtestc_ps:
7780 case Intrinsic::x86_avx_vtestc_pd:
7781 case Intrinsic::x86_avx_vtestc_ps_256:
7782 case Intrinsic::x86_avx_vtestc_pd_256:
7783 IsTestPacked = true; // Fallthrough
7784 case Intrinsic::x86_sse41_ptestc:
7785 case Intrinsic::x86_avx_ptestc_256:
7787 X86CC = X86::COND_B;
7789 case Intrinsic::x86_avx_vtestnzc_ps:
7790 case Intrinsic::x86_avx_vtestnzc_pd:
7791 case Intrinsic::x86_avx_vtestnzc_ps_256:
7792 case Intrinsic::x86_avx_vtestnzc_pd_256:
7793 IsTestPacked = true; // Fallthrough
7794 case Intrinsic::x86_sse41_ptestnzc:
7795 case Intrinsic::x86_avx_ptestnzc_256:
7797 X86CC = X86::COND_A;
7801 SDValue LHS = Op.getOperand(1);
7802 SDValue RHS = Op.getOperand(2);
7803 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7804 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7805 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7806 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7807 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7810 // Fix vector shift instructions where the last operand is a non-immediate
7812 case Intrinsic::x86_sse2_pslli_w:
7813 case Intrinsic::x86_sse2_pslli_d:
7814 case Intrinsic::x86_sse2_pslli_q:
7815 case Intrinsic::x86_sse2_psrli_w:
7816 case Intrinsic::x86_sse2_psrli_d:
7817 case Intrinsic::x86_sse2_psrli_q:
7818 case Intrinsic::x86_sse2_psrai_w:
7819 case Intrinsic::x86_sse2_psrai_d:
7820 case Intrinsic::x86_mmx_pslli_w:
7821 case Intrinsic::x86_mmx_pslli_d:
7822 case Intrinsic::x86_mmx_pslli_q:
7823 case Intrinsic::x86_mmx_psrli_w:
7824 case Intrinsic::x86_mmx_psrli_d:
7825 case Intrinsic::x86_mmx_psrli_q:
7826 case Intrinsic::x86_mmx_psrai_w:
7827 case Intrinsic::x86_mmx_psrai_d: {
7828 SDValue ShAmt = Op.getOperand(2);
7829 if (isa<ConstantSDNode>(ShAmt))
7832 unsigned NewIntNo = 0;
7833 EVT ShAmtVT = MVT::v4i32;
7835 case Intrinsic::x86_sse2_pslli_w:
7836 NewIntNo = Intrinsic::x86_sse2_psll_w;
7838 case Intrinsic::x86_sse2_pslli_d:
7839 NewIntNo = Intrinsic::x86_sse2_psll_d;
7841 case Intrinsic::x86_sse2_pslli_q:
7842 NewIntNo = Intrinsic::x86_sse2_psll_q;
7844 case Intrinsic::x86_sse2_psrli_w:
7845 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7847 case Intrinsic::x86_sse2_psrli_d:
7848 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7850 case Intrinsic::x86_sse2_psrli_q:
7851 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7853 case Intrinsic::x86_sse2_psrai_w:
7854 NewIntNo = Intrinsic::x86_sse2_psra_w;
7856 case Intrinsic::x86_sse2_psrai_d:
7857 NewIntNo = Intrinsic::x86_sse2_psra_d;
7860 ShAmtVT = MVT::v2i32;
7862 case Intrinsic::x86_mmx_pslli_w:
7863 NewIntNo = Intrinsic::x86_mmx_psll_w;
7865 case Intrinsic::x86_mmx_pslli_d:
7866 NewIntNo = Intrinsic::x86_mmx_psll_d;
7868 case Intrinsic::x86_mmx_pslli_q:
7869 NewIntNo = Intrinsic::x86_mmx_psll_q;
7871 case Intrinsic::x86_mmx_psrli_w:
7872 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7874 case Intrinsic::x86_mmx_psrli_d:
7875 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7877 case Intrinsic::x86_mmx_psrli_q:
7878 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7880 case Intrinsic::x86_mmx_psrai_w:
7881 NewIntNo = Intrinsic::x86_mmx_psra_w;
7883 case Intrinsic::x86_mmx_psrai_d:
7884 NewIntNo = Intrinsic::x86_mmx_psra_d;
7886 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7892 // The vector shift intrinsics with scalars uses 32b shift amounts but
7893 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7897 ShOps[1] = DAG.getConstant(0, MVT::i32);
7898 if (ShAmtVT == MVT::v4i32) {
7899 ShOps[2] = DAG.getUNDEF(MVT::i32);
7900 ShOps[3] = DAG.getUNDEF(MVT::i32);
7901 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7903 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7904 // FIXME this must be lowered to get rid of the invalid type.
7907 EVT VT = Op.getValueType();
7908 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7909 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7910 DAG.getConstant(NewIntNo, MVT::i32),
7911 Op.getOperand(1), ShAmt);
7916 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7917 SelectionDAG &DAG) const {
7918 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7919 MFI->setReturnAddressIsTaken(true);
7921 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7922 DebugLoc dl = Op.getDebugLoc();
7925 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7927 DAG.getConstant(TD->getPointerSize(),
7928 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7929 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7930 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7932 MachinePointerInfo(), false, false, 0);
7935 // Just load the return address.
7936 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7937 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7938 RetAddrFI, MachinePointerInfo(), false, false, 0);
7941 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7942 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7943 MFI->setFrameAddressIsTaken(true);
7945 EVT VT = Op.getValueType();
7946 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7947 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7948 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7949 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7951 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7952 MachinePointerInfo(),
7957 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7958 SelectionDAG &DAG) const {
7959 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7962 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7963 MachineFunction &MF = DAG.getMachineFunction();
7964 SDValue Chain = Op.getOperand(0);
7965 SDValue Offset = Op.getOperand(1);
7966 SDValue Handler = Op.getOperand(2);
7967 DebugLoc dl = Op.getDebugLoc();
7969 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7970 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7972 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7974 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7975 DAG.getIntPtrConstant(TD->getPointerSize()));
7976 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7977 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
7979 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7980 MF.getRegInfo().addLiveOut(StoreAddrReg);
7982 return DAG.getNode(X86ISD::EH_RETURN, dl,
7984 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7987 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7988 SelectionDAG &DAG) const {
7989 SDValue Root = Op.getOperand(0);
7990 SDValue Trmp = Op.getOperand(1); // trampoline
7991 SDValue FPtr = Op.getOperand(2); // nested function
7992 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7993 DebugLoc dl = Op.getDebugLoc();
7995 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7997 if (Subtarget->is64Bit()) {
7998 SDValue OutChains[6];
8000 // Large code-model.
8001 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8002 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8004 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8005 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8007 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8009 // Load the pointer to the nested function into R11.
8010 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8011 SDValue Addr = Trmp;
8012 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8013 Addr, MachinePointerInfo(TrmpAddr),
8016 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8017 DAG.getConstant(2, MVT::i64));
8018 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8019 MachinePointerInfo(TrmpAddr, 2),
8022 // Load the 'nest' parameter value into R10.
8023 // R10 is specified in X86CallingConv.td
8024 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8025 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8026 DAG.getConstant(10, MVT::i64));
8027 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8028 Addr, MachinePointerInfo(TrmpAddr, 10),
8031 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8032 DAG.getConstant(12, MVT::i64));
8033 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8034 MachinePointerInfo(TrmpAddr, 12),
8037 // Jump to the nested function.
8038 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8039 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8040 DAG.getConstant(20, MVT::i64));
8041 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8042 Addr, MachinePointerInfo(TrmpAddr, 20),
8045 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8046 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8047 DAG.getConstant(22, MVT::i64));
8048 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8049 MachinePointerInfo(TrmpAddr, 22),
8053 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8054 return DAG.getMergeValues(Ops, 2, dl);
8056 const Function *Func =
8057 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8058 CallingConv::ID CC = Func->getCallingConv();
8063 llvm_unreachable("Unsupported calling convention");
8064 case CallingConv::C:
8065 case CallingConv::X86_StdCall: {
8066 // Pass 'nest' parameter in ECX.
8067 // Must be kept in sync with X86CallingConv.td
8070 // Check that ECX wasn't needed by an 'inreg' parameter.
8071 const FunctionType *FTy = Func->getFunctionType();
8072 const AttrListPtr &Attrs = Func->getAttributes();
8074 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8075 unsigned InRegCount = 0;
8078 for (FunctionType::param_iterator I = FTy->param_begin(),
8079 E = FTy->param_end(); I != E; ++I, ++Idx)
8080 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8081 // FIXME: should only count parameters that are lowered to integers.
8082 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8084 if (InRegCount > 2) {
8085 report_fatal_error("Nest register in use - reduce number of inreg"
8091 case CallingConv::X86_FastCall:
8092 case CallingConv::X86_ThisCall:
8093 case CallingConv::Fast:
8094 // Pass 'nest' parameter in EAX.
8095 // Must be kept in sync with X86CallingConv.td
8100 SDValue OutChains[4];
8103 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8104 DAG.getConstant(10, MVT::i32));
8105 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8107 // This is storing the opcode for MOV32ri.
8108 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8109 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8110 OutChains[0] = DAG.getStore(Root, dl,
8111 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8112 Trmp, MachinePointerInfo(TrmpAddr),
8115 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8116 DAG.getConstant(1, MVT::i32));
8117 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8118 MachinePointerInfo(TrmpAddr, 1),
8121 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8122 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8123 DAG.getConstant(5, MVT::i32));
8124 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8125 MachinePointerInfo(TrmpAddr, 5),
8128 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8129 DAG.getConstant(6, MVT::i32));
8130 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8131 MachinePointerInfo(TrmpAddr, 6),
8135 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8136 return DAG.getMergeValues(Ops, 2, dl);
8140 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8141 SelectionDAG &DAG) const {
8143 The rounding mode is in bits 11:10 of FPSR, and has the following
8150 FLT_ROUNDS, on the other hand, expects the following:
8157 To perform the conversion, we do:
8158 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8161 MachineFunction &MF = DAG.getMachineFunction();
8162 const TargetMachine &TM = MF.getTarget();
8163 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8164 unsigned StackAlignment = TFI.getStackAlignment();
8165 EVT VT = Op.getValueType();
8166 DebugLoc DL = Op.getDebugLoc();
8168 // Save FP Control Word to stack slot
8169 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8170 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8173 MachineMemOperand *MMO =
8174 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8175 MachineMemOperand::MOStore, 2, 2);
8177 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8178 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8179 DAG.getVTList(MVT::Other),
8180 Ops, 2, MVT::i16, MMO);
8182 // Load FP Control Word from stack slot
8183 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8184 MachinePointerInfo(), false, false, 0);
8186 // Transform as necessary
8188 DAG.getNode(ISD::SRL, DL, MVT::i16,
8189 DAG.getNode(ISD::AND, DL, MVT::i16,
8190 CWD, DAG.getConstant(0x800, MVT::i16)),
8191 DAG.getConstant(11, MVT::i8));
8193 DAG.getNode(ISD::SRL, DL, MVT::i16,
8194 DAG.getNode(ISD::AND, DL, MVT::i16,
8195 CWD, DAG.getConstant(0x400, MVT::i16)),
8196 DAG.getConstant(9, MVT::i8));
8199 DAG.getNode(ISD::AND, DL, MVT::i16,
8200 DAG.getNode(ISD::ADD, DL, MVT::i16,
8201 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8202 DAG.getConstant(1, MVT::i16)),
8203 DAG.getConstant(3, MVT::i16));
8206 return DAG.getNode((VT.getSizeInBits() < 16 ?
8207 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8210 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8211 EVT VT = Op.getValueType();
8213 unsigned NumBits = VT.getSizeInBits();
8214 DebugLoc dl = Op.getDebugLoc();
8216 Op = Op.getOperand(0);
8217 if (VT == MVT::i8) {
8218 // Zero extend to i32 since there is not an i8 bsr.
8220 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8223 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8224 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8225 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8227 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8230 DAG.getConstant(NumBits+NumBits-1, OpVT),
8231 DAG.getConstant(X86::COND_E, MVT::i8),
8234 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8236 // Finally xor with NumBits-1.
8237 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8240 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8244 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8245 EVT VT = Op.getValueType();
8247 unsigned NumBits = VT.getSizeInBits();
8248 DebugLoc dl = Op.getDebugLoc();
8250 Op = Op.getOperand(0);
8251 if (VT == MVT::i8) {
8253 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8256 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8257 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8258 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8260 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8263 DAG.getConstant(NumBits, OpVT),
8264 DAG.getConstant(X86::COND_E, MVT::i8),
8267 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8270 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8274 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8275 EVT VT = Op.getValueType();
8276 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8277 DebugLoc dl = Op.getDebugLoc();
8279 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8280 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8281 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8282 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8283 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8285 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8286 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8287 // return AloBlo + AloBhi + AhiBlo;
8289 SDValue A = Op.getOperand(0);
8290 SDValue B = Op.getOperand(1);
8292 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8293 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8294 A, DAG.getConstant(32, MVT::i32));
8295 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8296 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8297 B, DAG.getConstant(32, MVT::i32));
8298 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8299 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8301 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8302 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8304 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8305 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8307 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8308 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8309 AloBhi, DAG.getConstant(32, MVT::i32));
8310 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8311 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8312 AhiBlo, DAG.getConstant(32, MVT::i32));
8313 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8314 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8318 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8319 EVT VT = Op.getValueType();
8320 DebugLoc dl = Op.getDebugLoc();
8321 SDValue R = Op.getOperand(0);
8323 LLVMContext *Context = DAG.getContext();
8325 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8327 if (VT == MVT::v4i32) {
8328 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8329 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8330 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8332 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8334 std::vector<Constant*> CV(4, CI);
8335 Constant *C = ConstantVector::get(CV);
8336 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8337 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8338 MachinePointerInfo::getConstantPool(),
8341 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8342 Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8343 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8344 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8346 if (VT == MVT::v16i8) {
8348 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8349 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8350 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8352 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8353 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8355 std::vector<Constant*> CVM1(16, CM1);
8356 std::vector<Constant*> CVM2(16, CM2);
8357 Constant *C = ConstantVector::get(CVM1);
8358 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8359 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8360 MachinePointerInfo::getConstantPool(),
8363 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8364 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8365 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8366 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8367 DAG.getConstant(4, MVT::i32));
8368 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8369 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8372 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8374 C = ConstantVector::get(CVM2);
8375 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8376 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8377 MachinePointerInfo::getConstantPool(),
8380 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8381 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8382 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8383 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8384 DAG.getConstant(2, MVT::i32));
8385 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8386 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8389 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8391 // return pblendv(r, r+r, a);
8392 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8393 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8394 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8400 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8401 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8402 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8403 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8404 // has only one use.
8405 SDNode *N = Op.getNode();
8406 SDValue LHS = N->getOperand(0);
8407 SDValue RHS = N->getOperand(1);
8408 unsigned BaseOp = 0;
8410 DebugLoc dl = Op.getDebugLoc();
8412 switch (Op.getOpcode()) {
8413 default: llvm_unreachable("Unknown ovf instruction!");
8415 // A subtract of one will be selected as a INC. Note that INC doesn't
8416 // set CF, so we can't do this for UADDO.
8417 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8418 if (C->getAPIntValue() == 1) {
8419 BaseOp = X86ISD::INC;
8423 BaseOp = X86ISD::ADD;
8427 BaseOp = X86ISD::ADD;
8431 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8432 // set CF, so we can't do this for USUBO.
8433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8434 if (C->getAPIntValue() == 1) {
8435 BaseOp = X86ISD::DEC;
8439 BaseOp = X86ISD::SUB;
8443 BaseOp = X86ISD::SUB;
8447 BaseOp = X86ISD::SMUL;
8451 BaseOp = X86ISD::UMUL;
8456 // Also sets EFLAGS.
8457 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8458 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8461 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8462 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8464 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8468 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8469 DebugLoc dl = Op.getDebugLoc();
8471 if (!Subtarget->hasSSE2()) {
8472 SDValue Chain = Op.getOperand(0);
8473 SDValue Zero = DAG.getConstant(0,
8474 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8476 DAG.getRegister(X86::ESP, MVT::i32), // Base
8477 DAG.getTargetConstant(1, MVT::i8), // Scale
8478 DAG.getRegister(0, MVT::i32), // Index
8479 DAG.getTargetConstant(0, MVT::i32), // Disp
8480 DAG.getRegister(0, MVT::i32), // Segment.
8485 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8486 array_lengthof(Ops));
8487 return SDValue(Res, 0);
8490 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8492 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8494 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8495 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8496 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8497 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8499 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8500 if (!Op1 && !Op2 && !Op3 && Op4)
8501 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8503 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8504 if (Op1 && !Op2 && !Op3 && !Op4)
8505 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8507 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8509 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8512 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8513 EVT T = Op.getValueType();
8514 DebugLoc DL = Op.getDebugLoc();
8517 switch(T.getSimpleVT().SimpleTy) {
8519 assert(false && "Invalid value type!");
8520 case MVT::i8: Reg = X86::AL; size = 1; break;
8521 case MVT::i16: Reg = X86::AX; size = 2; break;
8522 case MVT::i32: Reg = X86::EAX; size = 4; break;
8524 assert(Subtarget->is64Bit() && "Node not type legal!");
8525 Reg = X86::RAX; size = 8;
8528 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8529 Op.getOperand(2), SDValue());
8530 SDValue Ops[] = { cpIn.getValue(0),
8533 DAG.getTargetConstant(size, MVT::i8),
8535 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8536 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8537 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8540 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8544 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8545 SelectionDAG &DAG) const {
8546 assert(Subtarget->is64Bit() && "Result not type legalized?");
8547 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8548 SDValue TheChain = Op.getOperand(0);
8549 DebugLoc dl = Op.getDebugLoc();
8550 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8551 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8552 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8554 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8555 DAG.getConstant(32, MVT::i8));
8557 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8560 return DAG.getMergeValues(Ops, 2, dl);
8563 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8564 SelectionDAG &DAG) const {
8565 EVT SrcVT = Op.getOperand(0).getValueType();
8566 EVT DstVT = Op.getValueType();
8567 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8568 Subtarget->hasMMX() && !DisableMMX) &&
8569 "Unexpected custom BIT_CONVERT");
8570 assert((DstVT == MVT::i64 ||
8571 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8572 "Unexpected custom BIT_CONVERT");
8573 // i64 <=> MMX conversions are Legal.
8574 if (SrcVT==MVT::i64 && DstVT.isVector())
8576 if (DstVT==MVT::i64 && SrcVT.isVector())
8578 // MMX <=> MMX conversions are Legal.
8579 if (SrcVT.isVector() && DstVT.isVector())
8581 // All other conversions need to be expanded.
8584 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8585 SDNode *Node = Op.getNode();
8586 DebugLoc dl = Node->getDebugLoc();
8587 EVT T = Node->getValueType(0);
8588 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8589 DAG.getConstant(0, T), Node->getOperand(2));
8590 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8591 cast<AtomicSDNode>(Node)->getMemoryVT(),
8592 Node->getOperand(0),
8593 Node->getOperand(1), negOp,
8594 cast<AtomicSDNode>(Node)->getSrcValue(),
8595 cast<AtomicSDNode>(Node)->getAlignment());
8598 /// LowerOperation - Provide custom lowering hooks for some operations.
8600 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8601 switch (Op.getOpcode()) {
8602 default: llvm_unreachable("Should not custom lower this!");
8603 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8604 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8605 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8606 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8607 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8608 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8609 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8610 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8611 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8612 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8613 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8614 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8615 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8616 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8617 case ISD::SHL_PARTS:
8618 case ISD::SRA_PARTS:
8619 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8620 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8621 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8622 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8623 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8624 case ISD::FABS: return LowerFABS(Op, DAG);
8625 case ISD::FNEG: return LowerFNEG(Op, DAG);
8626 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8627 case ISD::SETCC: return LowerSETCC(Op, DAG);
8628 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8629 case ISD::SELECT: return LowerSELECT(Op, DAG);
8630 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8631 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8632 case ISD::VASTART: return LowerVASTART(Op, DAG);
8633 case ISD::VAARG: return LowerVAARG(Op, DAG);
8634 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8635 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8636 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8637 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8638 case ISD::FRAME_TO_ARGS_OFFSET:
8639 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8640 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8641 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8642 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8643 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8644 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8645 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8646 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8647 case ISD::SHL: return LowerSHL(Op, DAG);
8653 case ISD::UMULO: return LowerXALUO(Op, DAG);
8654 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8655 case ISD::BIT_CONVERT: return LowerBIT_CONVERT(Op, DAG);
8659 void X86TargetLowering::
8660 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8661 SelectionDAG &DAG, unsigned NewOp) const {
8662 EVT T = Node->getValueType(0);
8663 DebugLoc dl = Node->getDebugLoc();
8664 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8666 SDValue Chain = Node->getOperand(0);
8667 SDValue In1 = Node->getOperand(1);
8668 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8669 Node->getOperand(2), DAG.getIntPtrConstant(0));
8670 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8671 Node->getOperand(2), DAG.getIntPtrConstant(1));
8672 SDValue Ops[] = { Chain, In1, In2L, In2H };
8673 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8675 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8676 cast<MemSDNode>(Node)->getMemOperand());
8677 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8678 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8679 Results.push_back(Result.getValue(2));
8682 /// ReplaceNodeResults - Replace a node with an illegal result type
8683 /// with a new node built out of custom code.
8684 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8685 SmallVectorImpl<SDValue>&Results,
8686 SelectionDAG &DAG) const {
8687 DebugLoc dl = N->getDebugLoc();
8688 switch (N->getOpcode()) {
8690 assert(false && "Do not know how to custom type legalize this operation!");
8692 case ISD::FP_TO_SINT: {
8693 std::pair<SDValue,SDValue> Vals =
8694 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8695 SDValue FIST = Vals.first, StackSlot = Vals.second;
8696 if (FIST.getNode() != 0) {
8697 EVT VT = N->getValueType(0);
8698 // Return a load from the stack slot.
8699 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8700 MachinePointerInfo(), false, false, 0));
8704 case ISD::READCYCLECOUNTER: {
8705 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8706 SDValue TheChain = N->getOperand(0);
8707 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8708 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8710 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8712 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8713 SDValue Ops[] = { eax, edx };
8714 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8715 Results.push_back(edx.getValue(1));
8718 case ISD::ATOMIC_CMP_SWAP: {
8719 EVT T = N->getValueType(0);
8720 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8721 SDValue cpInL, cpInH;
8722 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8723 DAG.getConstant(0, MVT::i32));
8724 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8725 DAG.getConstant(1, MVT::i32));
8726 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8727 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8729 SDValue swapInL, swapInH;
8730 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8731 DAG.getConstant(0, MVT::i32));
8732 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8733 DAG.getConstant(1, MVT::i32));
8734 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8736 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8737 swapInL.getValue(1));
8738 SDValue Ops[] = { swapInH.getValue(0),
8740 swapInH.getValue(1) };
8741 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8742 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8743 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8745 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8746 MVT::i32, Result.getValue(1));
8747 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8748 MVT::i32, cpOutL.getValue(2));
8749 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8750 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8751 Results.push_back(cpOutH.getValue(1));
8754 case ISD::ATOMIC_LOAD_ADD:
8755 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8757 case ISD::ATOMIC_LOAD_AND:
8758 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8760 case ISD::ATOMIC_LOAD_NAND:
8761 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8763 case ISD::ATOMIC_LOAD_OR:
8764 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8766 case ISD::ATOMIC_LOAD_SUB:
8767 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8769 case ISD::ATOMIC_LOAD_XOR:
8770 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8772 case ISD::ATOMIC_SWAP:
8773 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8778 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8780 default: return NULL;
8781 case X86ISD::BSF: return "X86ISD::BSF";
8782 case X86ISD::BSR: return "X86ISD::BSR";
8783 case X86ISD::SHLD: return "X86ISD::SHLD";
8784 case X86ISD::SHRD: return "X86ISD::SHRD";
8785 case X86ISD::FAND: return "X86ISD::FAND";
8786 case X86ISD::FOR: return "X86ISD::FOR";
8787 case X86ISD::FXOR: return "X86ISD::FXOR";
8788 case X86ISD::FSRL: return "X86ISD::FSRL";
8789 case X86ISD::FILD: return "X86ISD::FILD";
8790 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8791 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8792 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8793 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8794 case X86ISD::FLD: return "X86ISD::FLD";
8795 case X86ISD::FST: return "X86ISD::FST";
8796 case X86ISD::CALL: return "X86ISD::CALL";
8797 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8798 case X86ISD::BT: return "X86ISD::BT";
8799 case X86ISD::CMP: return "X86ISD::CMP";
8800 case X86ISD::COMI: return "X86ISD::COMI";
8801 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8802 case X86ISD::SETCC: return "X86ISD::SETCC";
8803 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8804 case X86ISD::CMOV: return "X86ISD::CMOV";
8805 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8806 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8807 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8808 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8809 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8810 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8811 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8812 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8813 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8814 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8815 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8816 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8817 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8818 case X86ISD::FMAX: return "X86ISD::FMAX";
8819 case X86ISD::FMIN: return "X86ISD::FMIN";
8820 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8821 case X86ISD::FRCP: return "X86ISD::FRCP";
8822 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8823 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8824 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8825 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8826 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8827 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8828 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8829 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8830 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8831 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8832 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8833 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8834 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8835 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8836 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8837 case X86ISD::VSHL: return "X86ISD::VSHL";
8838 case X86ISD::VSRL: return "X86ISD::VSRL";
8839 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8840 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8841 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8842 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8843 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8844 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8845 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8846 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8847 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8848 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8849 case X86ISD::ADD: return "X86ISD::ADD";
8850 case X86ISD::SUB: return "X86ISD::SUB";
8851 case X86ISD::SMUL: return "X86ISD::SMUL";
8852 case X86ISD::UMUL: return "X86ISD::UMUL";
8853 case X86ISD::INC: return "X86ISD::INC";
8854 case X86ISD::DEC: return "X86ISD::DEC";
8855 case X86ISD::OR: return "X86ISD::OR";
8856 case X86ISD::XOR: return "X86ISD::XOR";
8857 case X86ISD::AND: return "X86ISD::AND";
8858 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8859 case X86ISD::PTEST: return "X86ISD::PTEST";
8860 case X86ISD::TESTP: return "X86ISD::TESTP";
8861 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8862 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8863 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8864 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8865 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8866 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8867 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8868 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8869 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8870 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8871 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8872 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8873 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8874 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8875 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8876 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8877 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8878 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8879 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8880 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8881 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8882 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8883 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8884 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8885 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8886 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8887 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8888 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8889 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8890 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8891 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8892 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8893 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8894 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8895 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
8896 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
8900 // isLegalAddressingMode - Return true if the addressing mode represented
8901 // by AM is legal for this target, for a load/store of the specified type.
8902 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8903 const Type *Ty) const {
8904 // X86 supports extremely general addressing modes.
8905 CodeModel::Model M = getTargetMachine().getCodeModel();
8906 Reloc::Model R = getTargetMachine().getRelocationModel();
8908 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8909 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8914 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8916 // If a reference to this global requires an extra load, we can't fold it.
8917 if (isGlobalStubReference(GVFlags))
8920 // If BaseGV requires a register for the PIC base, we cannot also have a
8921 // BaseReg specified.
8922 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8925 // If lower 4G is not available, then we must use rip-relative addressing.
8926 if ((M != CodeModel::Small || R != Reloc::Static) &&
8927 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8937 // These scales always work.
8942 // These scales are formed with basereg+scalereg. Only accept if there is
8947 default: // Other stuff never works.
8955 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8956 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8958 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8959 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8960 if (NumBits1 <= NumBits2)
8965 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8966 if (!VT1.isInteger() || !VT2.isInteger())
8968 unsigned NumBits1 = VT1.getSizeInBits();
8969 unsigned NumBits2 = VT2.getSizeInBits();
8970 if (NumBits1 <= NumBits2)
8975 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8976 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8977 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8980 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8981 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8982 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8985 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8986 // i16 instructions are longer (0x66 prefix) and potentially slower.
8987 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8990 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8991 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8992 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8993 /// are assumed to be legal.
8995 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8997 // Very little shuffling can be done for 64-bit vectors right now.
8998 if (VT.getSizeInBits() == 64)
8999 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9001 // FIXME: pshufb, blends, shifts.
9002 return (VT.getVectorNumElements() == 2 ||
9003 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9004 isMOVLMask(M, VT) ||
9005 isSHUFPMask(M, VT) ||
9006 isPSHUFDMask(M, VT) ||
9007 isPSHUFHWMask(M, VT) ||
9008 isPSHUFLWMask(M, VT) ||
9009 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9010 isUNPCKLMask(M, VT) ||
9011 isUNPCKHMask(M, VT) ||
9012 isUNPCKL_v_undef_Mask(M, VT) ||
9013 isUNPCKH_v_undef_Mask(M, VT));
9017 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9019 unsigned NumElts = VT.getVectorNumElements();
9020 // FIXME: This collection of masks seems suspect.
9023 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9024 return (isMOVLMask(Mask, VT) ||
9025 isCommutedMOVLMask(Mask, VT, true) ||
9026 isSHUFPMask(Mask, VT) ||
9027 isCommutedSHUFPMask(Mask, VT));
9032 //===----------------------------------------------------------------------===//
9033 // X86 Scheduler Hooks
9034 //===----------------------------------------------------------------------===//
9036 // private utility function
9038 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9039 MachineBasicBlock *MBB,
9046 TargetRegisterClass *RC,
9047 bool invSrc) const {
9048 // For the atomic bitwise operator, we generate
9051 // ld t1 = [bitinstr.addr]
9052 // op t2 = t1, [bitinstr.val]
9054 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9056 // fallthrough -->nextMBB
9057 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9058 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9059 MachineFunction::iterator MBBIter = MBB;
9062 /// First build the CFG
9063 MachineFunction *F = MBB->getParent();
9064 MachineBasicBlock *thisMBB = MBB;
9065 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9066 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9067 F->insert(MBBIter, newMBB);
9068 F->insert(MBBIter, nextMBB);
9070 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9071 nextMBB->splice(nextMBB->begin(), thisMBB,
9072 llvm::next(MachineBasicBlock::iterator(bInstr)),
9074 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9076 // Update thisMBB to fall through to newMBB
9077 thisMBB->addSuccessor(newMBB);
9079 // newMBB jumps to itself and fall through to nextMBB
9080 newMBB->addSuccessor(nextMBB);
9081 newMBB->addSuccessor(newMBB);
9083 // Insert instructions into newMBB based on incoming instruction
9084 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9085 "unexpected number of operands");
9086 DebugLoc dl = bInstr->getDebugLoc();
9087 MachineOperand& destOper = bInstr->getOperand(0);
9088 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9089 int numArgs = bInstr->getNumOperands() - 1;
9090 for (int i=0; i < numArgs; ++i)
9091 argOpers[i] = &bInstr->getOperand(i+1);
9093 // x86 address has 4 operands: base, index, scale, and displacement
9094 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9095 int valArgIndx = lastAddrIndx + 1;
9097 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9098 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9099 for (int i=0; i <= lastAddrIndx; ++i)
9100 (*MIB).addOperand(*argOpers[i]);
9102 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9104 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9109 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9110 assert((argOpers[valArgIndx]->isReg() ||
9111 argOpers[valArgIndx]->isImm()) &&
9113 if (argOpers[valArgIndx]->isReg())
9114 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9116 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9118 (*MIB).addOperand(*argOpers[valArgIndx]);
9120 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9123 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9124 for (int i=0; i <= lastAddrIndx; ++i)
9125 (*MIB).addOperand(*argOpers[i]);
9127 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9128 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9129 bInstr->memoperands_end());
9131 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9135 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9137 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9141 // private utility function: 64 bit atomics on 32 bit host.
9143 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9144 MachineBasicBlock *MBB,
9149 bool invSrc) const {
9150 // For the atomic bitwise operator, we generate
9151 // thisMBB (instructions are in pairs, except cmpxchg8b)
9152 // ld t1,t2 = [bitinstr.addr]
9154 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9155 // op t5, t6 <- out1, out2, [bitinstr.val]
9156 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9157 // mov ECX, EBX <- t5, t6
9158 // mov EAX, EDX <- t1, t2
9159 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9160 // mov t3, t4 <- EAX, EDX
9162 // result in out1, out2
9163 // fallthrough -->nextMBB
9165 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9166 const unsigned LoadOpc = X86::MOV32rm;
9167 const unsigned NotOpc = X86::NOT32r;
9168 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9169 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9170 MachineFunction::iterator MBBIter = MBB;
9173 /// First build the CFG
9174 MachineFunction *F = MBB->getParent();
9175 MachineBasicBlock *thisMBB = MBB;
9176 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9177 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9178 F->insert(MBBIter, newMBB);
9179 F->insert(MBBIter, nextMBB);
9181 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9182 nextMBB->splice(nextMBB->begin(), thisMBB,
9183 llvm::next(MachineBasicBlock::iterator(bInstr)),
9185 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9187 // Update thisMBB to fall through to newMBB
9188 thisMBB->addSuccessor(newMBB);
9190 // newMBB jumps to itself and fall through to nextMBB
9191 newMBB->addSuccessor(nextMBB);
9192 newMBB->addSuccessor(newMBB);
9194 DebugLoc dl = bInstr->getDebugLoc();
9195 // Insert instructions into newMBB based on incoming instruction
9196 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9197 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9198 "unexpected number of operands");
9199 MachineOperand& dest1Oper = bInstr->getOperand(0);
9200 MachineOperand& dest2Oper = bInstr->getOperand(1);
9201 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9202 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9203 argOpers[i] = &bInstr->getOperand(i+2);
9205 // We use some of the operands multiple times, so conservatively just
9206 // clear any kill flags that might be present.
9207 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9208 argOpers[i]->setIsKill(false);
9211 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9212 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9214 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9215 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9216 for (int i=0; i <= lastAddrIndx; ++i)
9217 (*MIB).addOperand(*argOpers[i]);
9218 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9219 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9220 // add 4 to displacement.
9221 for (int i=0; i <= lastAddrIndx-2; ++i)
9222 (*MIB).addOperand(*argOpers[i]);
9223 MachineOperand newOp3 = *(argOpers[3]);
9225 newOp3.setImm(newOp3.getImm()+4);
9227 newOp3.setOffset(newOp3.getOffset()+4);
9228 (*MIB).addOperand(newOp3);
9229 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9231 // t3/4 are defined later, at the bottom of the loop
9232 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9233 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9234 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9235 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9236 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9237 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9239 // The subsequent operations should be using the destination registers of
9240 //the PHI instructions.
9242 t1 = F->getRegInfo().createVirtualRegister(RC);
9243 t2 = F->getRegInfo().createVirtualRegister(RC);
9244 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9245 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9247 t1 = dest1Oper.getReg();
9248 t2 = dest2Oper.getReg();
9251 int valArgIndx = lastAddrIndx + 1;
9252 assert((argOpers[valArgIndx]->isReg() ||
9253 argOpers[valArgIndx]->isImm()) &&
9255 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9256 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9257 if (argOpers[valArgIndx]->isReg())
9258 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9260 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9261 if (regOpcL != X86::MOV32rr)
9263 (*MIB).addOperand(*argOpers[valArgIndx]);
9264 assert(argOpers[valArgIndx + 1]->isReg() ==
9265 argOpers[valArgIndx]->isReg());
9266 assert(argOpers[valArgIndx + 1]->isImm() ==
9267 argOpers[valArgIndx]->isImm());
9268 if (argOpers[valArgIndx + 1]->isReg())
9269 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9271 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9272 if (regOpcH != X86::MOV32rr)
9274 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9276 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9278 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9281 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9283 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9286 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9287 for (int i=0; i <= lastAddrIndx; ++i)
9288 (*MIB).addOperand(*argOpers[i]);
9290 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9291 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9292 bInstr->memoperands_end());
9294 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9295 MIB.addReg(X86::EAX);
9296 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9297 MIB.addReg(X86::EDX);
9300 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9302 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9306 // private utility function
9308 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9309 MachineBasicBlock *MBB,
9310 unsigned cmovOpc) const {
9311 // For the atomic min/max operator, we generate
9314 // ld t1 = [min/max.addr]
9315 // mov t2 = [min/max.val]
9317 // cmov[cond] t2 = t1
9319 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9321 // fallthrough -->nextMBB
9323 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9324 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9325 MachineFunction::iterator MBBIter = MBB;
9328 /// First build the CFG
9329 MachineFunction *F = MBB->getParent();
9330 MachineBasicBlock *thisMBB = MBB;
9331 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9332 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9333 F->insert(MBBIter, newMBB);
9334 F->insert(MBBIter, nextMBB);
9336 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9337 nextMBB->splice(nextMBB->begin(), thisMBB,
9338 llvm::next(MachineBasicBlock::iterator(mInstr)),
9340 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9342 // Update thisMBB to fall through to newMBB
9343 thisMBB->addSuccessor(newMBB);
9345 // newMBB jumps to newMBB and fall through to nextMBB
9346 newMBB->addSuccessor(nextMBB);
9347 newMBB->addSuccessor(newMBB);
9349 DebugLoc dl = mInstr->getDebugLoc();
9350 // Insert instructions into newMBB based on incoming instruction
9351 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9352 "unexpected number of operands");
9353 MachineOperand& destOper = mInstr->getOperand(0);
9354 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9355 int numArgs = mInstr->getNumOperands() - 1;
9356 for (int i=0; i < numArgs; ++i)
9357 argOpers[i] = &mInstr->getOperand(i+1);
9359 // x86 address has 4 operands: base, index, scale, and displacement
9360 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9361 int valArgIndx = lastAddrIndx + 1;
9363 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9364 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9365 for (int i=0; i <= lastAddrIndx; ++i)
9366 (*MIB).addOperand(*argOpers[i]);
9368 // We only support register and immediate values
9369 assert((argOpers[valArgIndx]->isReg() ||
9370 argOpers[valArgIndx]->isImm()) &&
9373 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9374 if (argOpers[valArgIndx]->isReg())
9375 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9377 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9378 (*MIB).addOperand(*argOpers[valArgIndx]);
9380 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9383 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9388 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9389 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9393 // Cmp and exchange if none has modified the memory location
9394 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9395 for (int i=0; i <= lastAddrIndx; ++i)
9396 (*MIB).addOperand(*argOpers[i]);
9398 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9399 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9400 mInstr->memoperands_end());
9402 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9403 MIB.addReg(X86::EAX);
9406 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9408 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9412 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9413 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9416 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9417 unsigned numArgs, bool memArg) const {
9419 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9420 "Target must have SSE4.2 or AVX features enabled");
9422 DebugLoc dl = MI->getDebugLoc();
9423 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9427 if (!Subtarget->hasAVX()) {
9429 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9431 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9434 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9436 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9439 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9441 for (unsigned i = 0; i < numArgs; ++i) {
9442 MachineOperand &Op = MI->getOperand(i+1);
9444 if (!(Op.isReg() && Op.isImplicit()))
9448 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9451 MI->eraseFromParent();
9457 X86TargetLowering::EmitVAARG64WithCustomInserter(
9459 MachineBasicBlock *MBB) const {
9460 // Emit va_arg instruction on X86-64.
9462 // Operands to this pseudo-instruction:
9463 // 0 ) Output : destination address (reg)
9464 // 1-5) Input : va_list address (addr, i64mem)
9465 // 6 ) ArgSize : Size (in bytes) of vararg type
9466 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9467 // 8 ) Align : Alignment of type
9468 // 9 ) EFLAGS (implicit-def)
9470 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9471 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9473 unsigned DestReg = MI->getOperand(0).getReg();
9474 MachineOperand &Base = MI->getOperand(1);
9475 MachineOperand &Scale = MI->getOperand(2);
9476 MachineOperand &Index = MI->getOperand(3);
9477 MachineOperand &Disp = MI->getOperand(4);
9478 MachineOperand &Segment = MI->getOperand(5);
9479 unsigned ArgSize = MI->getOperand(6).getImm();
9480 unsigned ArgMode = MI->getOperand(7).getImm();
9481 unsigned Align = MI->getOperand(8).getImm();
9484 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9485 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9486 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9488 // Machine Information
9489 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9490 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9491 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9492 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9493 DebugLoc DL = MI->getDebugLoc();
9498 // i64 overflow_area (address)
9499 // i64 reg_save_area (address)
9501 // sizeof(va_list) = 24
9502 // alignment(va_list) = 8
9504 unsigned TotalNumIntRegs = 6;
9505 unsigned TotalNumXMMRegs = 8;
9506 bool UseGPOffset = (ArgMode == 1);
9507 bool UseFPOffset = (ArgMode == 2);
9508 unsigned MaxOffset = TotalNumIntRegs * 8 +
9509 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9511 /* Align ArgSize to a multiple of 8 */
9512 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9513 bool NeedsAlign = (Align > 8);
9515 MachineBasicBlock *thisMBB = MBB;
9516 MachineBasicBlock *overflowMBB;
9517 MachineBasicBlock *offsetMBB;
9518 MachineBasicBlock *endMBB;
9520 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
9521 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
9522 unsigned OffsetReg = 0;
9524 if (!UseGPOffset && !UseFPOffset) {
9525 // If we only pull from the overflow region, we don't create a branch.
9526 // We don't need to alter control flow.
9527 OffsetDestReg = 0; // unused
9528 OverflowDestReg = DestReg;
9531 overflowMBB = thisMBB;
9534 // First emit code to check if gp_offset (or fp_offset) is below the bound.
9535 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9536 // If not, pull from overflow_area. (branch to overflowMBB)
9541 // offsetMBB overflowMBB
9546 // Registers for the PHI in endMBB
9547 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9548 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9550 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9551 MachineFunction *MF = MBB->getParent();
9552 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9553 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9554 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9556 MachineFunction::iterator MBBIter = MBB;
9559 // Insert the new basic blocks
9560 MF->insert(MBBIter, offsetMBB);
9561 MF->insert(MBBIter, overflowMBB);
9562 MF->insert(MBBIter, endMBB);
9564 // Transfer the remainder of MBB and its successor edges to endMBB.
9565 endMBB->splice(endMBB->begin(), thisMBB,
9566 llvm::next(MachineBasicBlock::iterator(MI)),
9568 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9570 // Make offsetMBB and overflowMBB successors of thisMBB
9571 thisMBB->addSuccessor(offsetMBB);
9572 thisMBB->addSuccessor(overflowMBB);
9574 // endMBB is a successor of both offsetMBB and overflowMBB
9575 offsetMBB->addSuccessor(endMBB);
9576 overflowMBB->addSuccessor(endMBB);
9578 // Load the offset value into a register
9579 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9580 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9584 .addDisp(Disp, UseFPOffset ? 4 : 0)
9585 .addOperand(Segment)
9586 .setMemRefs(MMOBegin, MMOEnd);
9588 // Check if there is enough room left to pull this argument.
9589 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9591 .addImm(MaxOffset + 8 - ArgSizeA8);
9593 // Branch to "overflowMBB" if offset >= max
9594 // Fall through to "offsetMBB" otherwise
9595 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9596 .addMBB(overflowMBB);
9599 // In offsetMBB, emit code to use the reg_save_area.
9601 assert(OffsetReg != 0);
9603 // Read the reg_save_area address.
9604 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9605 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9610 .addOperand(Segment)
9611 .setMemRefs(MMOBegin, MMOEnd);
9613 // Zero-extend the offset
9614 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9615 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9618 .addImm(X86::sub_32bit);
9620 // Add the offset to the reg_save_area to get the final address.
9621 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9622 .addReg(OffsetReg64)
9623 .addReg(RegSaveReg);
9625 // Compute the offset for the next argument
9626 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9627 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9629 .addImm(UseFPOffset ? 16 : 8);
9631 // Store it back into the va_list.
9632 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9636 .addDisp(Disp, UseFPOffset ? 4 : 0)
9637 .addOperand(Segment)
9638 .addReg(NextOffsetReg)
9639 .setMemRefs(MMOBegin, MMOEnd);
9642 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9647 // Emit code to use overflow area
9650 // Load the overflow_area address into a register.
9651 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9652 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9657 .addOperand(Segment)
9658 .setMemRefs(MMOBegin, MMOEnd);
9660 // If we need to align it, do so. Otherwise, just copy the address
9661 // to OverflowDestReg.
9663 // Align the overflow address
9664 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9665 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9667 // aligned_addr = (addr + (align-1)) & ~(align-1)
9668 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9669 .addReg(OverflowAddrReg)
9672 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9674 .addImm(~(uint64_t)(Align-1));
9676 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9677 .addReg(OverflowAddrReg);
9680 // Compute the next overflow address after this argument.
9681 // (the overflow address should be kept 8-byte aligned)
9682 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9683 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9684 .addReg(OverflowDestReg)
9687 // Store the new overflow address.
9688 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9693 .addOperand(Segment)
9694 .addReg(NextAddrReg)
9695 .setMemRefs(MMOBegin, MMOEnd);
9697 // If we branched, emit the PHI to the front of endMBB.
9699 BuildMI(*endMBB, endMBB->begin(), DL,
9700 TII->get(X86::PHI), DestReg)
9701 .addReg(OffsetDestReg).addMBB(offsetMBB)
9702 .addReg(OverflowDestReg).addMBB(overflowMBB);
9705 // Erase the pseudo instruction
9706 MI->eraseFromParent();
9712 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9714 MachineBasicBlock *MBB) const {
9715 // Emit code to save XMM registers to the stack. The ABI says that the
9716 // number of registers to save is given in %al, so it's theoretically
9717 // possible to do an indirect jump trick to avoid saving all of them,
9718 // however this code takes a simpler approach and just executes all
9719 // of the stores if %al is non-zero. It's less code, and it's probably
9720 // easier on the hardware branch predictor, and stores aren't all that
9721 // expensive anyway.
9723 // Create the new basic blocks. One block contains all the XMM stores,
9724 // and one block is the final destination regardless of whether any
9725 // stores were performed.
9726 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9727 MachineFunction *F = MBB->getParent();
9728 MachineFunction::iterator MBBIter = MBB;
9730 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9731 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9732 F->insert(MBBIter, XMMSaveMBB);
9733 F->insert(MBBIter, EndMBB);
9735 // Transfer the remainder of MBB and its successor edges to EndMBB.
9736 EndMBB->splice(EndMBB->begin(), MBB,
9737 llvm::next(MachineBasicBlock::iterator(MI)),
9739 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9741 // The original block will now fall through to the XMM save block.
9742 MBB->addSuccessor(XMMSaveMBB);
9743 // The XMMSaveMBB will fall through to the end block.
9744 XMMSaveMBB->addSuccessor(EndMBB);
9746 // Now add the instructions.
9747 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9748 DebugLoc DL = MI->getDebugLoc();
9750 unsigned CountReg = MI->getOperand(0).getReg();
9751 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9752 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9754 if (!Subtarget->isTargetWin64()) {
9755 // If %al is 0, branch around the XMM save block.
9756 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9757 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9758 MBB->addSuccessor(EndMBB);
9761 // In the XMM save block, save all the XMM argument registers.
9762 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9763 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9764 MachineMemOperand *MMO =
9765 F->getMachineMemOperand(
9766 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9767 MachineMemOperand::MOStore,
9768 /*Size=*/16, /*Align=*/16);
9769 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9770 .addFrameIndex(RegSaveFrameIndex)
9771 .addImm(/*Scale=*/1)
9772 .addReg(/*IndexReg=*/0)
9773 .addImm(/*Disp=*/Offset)
9774 .addReg(/*Segment=*/0)
9775 .addReg(MI->getOperand(i).getReg())
9776 .addMemOperand(MMO);
9779 MI->eraseFromParent(); // The pseudo instruction is gone now.
9785 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9786 MachineBasicBlock *BB) const {
9787 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9788 DebugLoc DL = MI->getDebugLoc();
9790 // To "insert" a SELECT_CC instruction, we actually have to insert the
9791 // diamond control-flow pattern. The incoming instruction knows the
9792 // destination vreg to set, the condition code register to branch on, the
9793 // true/false values to select between, and a branch opcode to use.
9794 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9795 MachineFunction::iterator It = BB;
9801 // cmpTY ccX, r1, r2
9803 // fallthrough --> copy0MBB
9804 MachineBasicBlock *thisMBB = BB;
9805 MachineFunction *F = BB->getParent();
9806 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9807 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9808 F->insert(It, copy0MBB);
9809 F->insert(It, sinkMBB);
9811 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9812 // live into the sink and copy blocks.
9813 const MachineFunction *MF = BB->getParent();
9814 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9815 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9817 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9818 const MachineOperand &MO = MI->getOperand(I);
9819 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9820 unsigned Reg = MO.getReg();
9821 if (Reg != X86::EFLAGS) continue;
9822 copy0MBB->addLiveIn(Reg);
9823 sinkMBB->addLiveIn(Reg);
9826 // Transfer the remainder of BB and its successor edges to sinkMBB.
9827 sinkMBB->splice(sinkMBB->begin(), BB,
9828 llvm::next(MachineBasicBlock::iterator(MI)),
9830 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9832 // Add the true and fallthrough blocks as its successors.
9833 BB->addSuccessor(copy0MBB);
9834 BB->addSuccessor(sinkMBB);
9836 // Create the conditional branch instruction.
9838 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9839 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9842 // %FalseValue = ...
9843 // # fallthrough to sinkMBB
9844 copy0MBB->addSuccessor(sinkMBB);
9847 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9849 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9850 TII->get(X86::PHI), MI->getOperand(0).getReg())
9851 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9852 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9854 MI->eraseFromParent(); // The pseudo instruction is gone now.
9859 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9860 MachineBasicBlock *BB) const {
9861 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9862 DebugLoc DL = MI->getDebugLoc();
9864 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9865 // non-trivial part is impdef of ESP.
9866 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9869 const char *StackProbeSymbol =
9870 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9872 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9873 .addExternalSymbol(StackProbeSymbol)
9874 .addReg(X86::EAX, RegState::Implicit)
9875 .addReg(X86::ESP, RegState::Implicit)
9876 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9877 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9878 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9880 MI->eraseFromParent(); // The pseudo instruction is gone now.
9885 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9886 MachineBasicBlock *BB) const {
9887 // This is pretty easy. We're taking the value that we received from
9888 // our load from the relocation, sticking it in either RDI (x86-64)
9889 // or EAX and doing an indirect call. The return value will then
9890 // be in the normal return register.
9891 const X86InstrInfo *TII
9892 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9893 DebugLoc DL = MI->getDebugLoc();
9894 MachineFunction *F = BB->getParent();
9896 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9897 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9899 if (Subtarget->is64Bit()) {
9900 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9901 TII->get(X86::MOV64rm), X86::RDI)
9903 .addImm(0).addReg(0)
9904 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9905 MI->getOperand(3).getTargetFlags())
9907 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9908 addDirectMem(MIB, X86::RDI);
9909 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9910 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9911 TII->get(X86::MOV32rm), X86::EAX)
9913 .addImm(0).addReg(0)
9914 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9915 MI->getOperand(3).getTargetFlags())
9917 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9918 addDirectMem(MIB, X86::EAX);
9920 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9921 TII->get(X86::MOV32rm), X86::EAX)
9922 .addReg(TII->getGlobalBaseReg(F))
9923 .addImm(0).addReg(0)
9924 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9925 MI->getOperand(3).getTargetFlags())
9927 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9928 addDirectMem(MIB, X86::EAX);
9931 MI->eraseFromParent(); // The pseudo instruction is gone now.
9936 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9937 MachineBasicBlock *BB) const {
9938 switch (MI->getOpcode()) {
9939 default: assert(false && "Unexpected instr type to insert");
9940 case X86::WIN_ALLOCA:
9941 return EmitLoweredWinAlloca(MI, BB);
9942 case X86::TLSCall_32:
9943 case X86::TLSCall_64:
9944 return EmitLoweredTLSCall(MI, BB);
9946 case X86::CMOV_FR32:
9947 case X86::CMOV_FR64:
9948 case X86::CMOV_V4F32:
9949 case X86::CMOV_V2F64:
9950 case X86::CMOV_V2I64:
9951 case X86::CMOV_GR16:
9952 case X86::CMOV_GR32:
9953 case X86::CMOV_RFP32:
9954 case X86::CMOV_RFP64:
9955 case X86::CMOV_RFP80:
9956 return EmitLoweredSelect(MI, BB);
9958 case X86::FP32_TO_INT16_IN_MEM:
9959 case X86::FP32_TO_INT32_IN_MEM:
9960 case X86::FP32_TO_INT64_IN_MEM:
9961 case X86::FP64_TO_INT16_IN_MEM:
9962 case X86::FP64_TO_INT32_IN_MEM:
9963 case X86::FP64_TO_INT64_IN_MEM:
9964 case X86::FP80_TO_INT16_IN_MEM:
9965 case X86::FP80_TO_INT32_IN_MEM:
9966 case X86::FP80_TO_INT64_IN_MEM: {
9967 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9968 DebugLoc DL = MI->getDebugLoc();
9970 // Change the floating point control register to use "round towards zero"
9971 // mode when truncating to an integer value.
9972 MachineFunction *F = BB->getParent();
9973 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9974 addFrameReference(BuildMI(*BB, MI, DL,
9975 TII->get(X86::FNSTCW16m)), CWFrameIdx);
9977 // Load the old value of the high byte of the control word...
9979 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9980 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9983 // Set the high part to be round to zero...
9984 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9987 // Reload the modified control word now...
9988 addFrameReference(BuildMI(*BB, MI, DL,
9989 TII->get(X86::FLDCW16m)), CWFrameIdx);
9991 // Restore the memory image of control word to original value
9992 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9995 // Get the X86 opcode to use.
9997 switch (MI->getOpcode()) {
9998 default: llvm_unreachable("illegal opcode!");
9999 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10000 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10001 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10002 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10003 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10004 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10005 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10006 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10007 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10011 MachineOperand &Op = MI->getOperand(0);
10013 AM.BaseType = X86AddressMode::RegBase;
10014 AM.Base.Reg = Op.getReg();
10016 AM.BaseType = X86AddressMode::FrameIndexBase;
10017 AM.Base.FrameIndex = Op.getIndex();
10019 Op = MI->getOperand(1);
10021 AM.Scale = Op.getImm();
10022 Op = MI->getOperand(2);
10024 AM.IndexReg = Op.getImm();
10025 Op = MI->getOperand(3);
10026 if (Op.isGlobal()) {
10027 AM.GV = Op.getGlobal();
10029 AM.Disp = Op.getImm();
10031 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10032 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10034 // Reload the original control word now.
10035 addFrameReference(BuildMI(*BB, MI, DL,
10036 TII->get(X86::FLDCW16m)), CWFrameIdx);
10038 MI->eraseFromParent(); // The pseudo instruction is gone now.
10041 // String/text processing lowering.
10042 case X86::PCMPISTRM128REG:
10043 case X86::VPCMPISTRM128REG:
10044 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10045 case X86::PCMPISTRM128MEM:
10046 case X86::VPCMPISTRM128MEM:
10047 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10048 case X86::PCMPESTRM128REG:
10049 case X86::VPCMPESTRM128REG:
10050 return EmitPCMP(MI, BB, 5, false /* in mem */);
10051 case X86::PCMPESTRM128MEM:
10052 case X86::VPCMPESTRM128MEM:
10053 return EmitPCMP(MI, BB, 5, true /* in mem */);
10055 // Atomic Lowering.
10056 case X86::ATOMAND32:
10057 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10058 X86::AND32ri, X86::MOV32rm,
10060 X86::NOT32r, X86::EAX,
10061 X86::GR32RegisterClass);
10062 case X86::ATOMOR32:
10063 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10064 X86::OR32ri, X86::MOV32rm,
10066 X86::NOT32r, X86::EAX,
10067 X86::GR32RegisterClass);
10068 case X86::ATOMXOR32:
10069 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10070 X86::XOR32ri, X86::MOV32rm,
10072 X86::NOT32r, X86::EAX,
10073 X86::GR32RegisterClass);
10074 case X86::ATOMNAND32:
10075 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10076 X86::AND32ri, X86::MOV32rm,
10078 X86::NOT32r, X86::EAX,
10079 X86::GR32RegisterClass, true);
10080 case X86::ATOMMIN32:
10081 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10082 case X86::ATOMMAX32:
10083 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10084 case X86::ATOMUMIN32:
10085 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10086 case X86::ATOMUMAX32:
10087 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10089 case X86::ATOMAND16:
10090 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10091 X86::AND16ri, X86::MOV16rm,
10093 X86::NOT16r, X86::AX,
10094 X86::GR16RegisterClass);
10095 case X86::ATOMOR16:
10096 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10097 X86::OR16ri, X86::MOV16rm,
10099 X86::NOT16r, X86::AX,
10100 X86::GR16RegisterClass);
10101 case X86::ATOMXOR16:
10102 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10103 X86::XOR16ri, X86::MOV16rm,
10105 X86::NOT16r, X86::AX,
10106 X86::GR16RegisterClass);
10107 case X86::ATOMNAND16:
10108 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10109 X86::AND16ri, X86::MOV16rm,
10111 X86::NOT16r, X86::AX,
10112 X86::GR16RegisterClass, true);
10113 case X86::ATOMMIN16:
10114 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10115 case X86::ATOMMAX16:
10116 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10117 case X86::ATOMUMIN16:
10118 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10119 case X86::ATOMUMAX16:
10120 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10122 case X86::ATOMAND8:
10123 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10124 X86::AND8ri, X86::MOV8rm,
10126 X86::NOT8r, X86::AL,
10127 X86::GR8RegisterClass);
10129 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10130 X86::OR8ri, X86::MOV8rm,
10132 X86::NOT8r, X86::AL,
10133 X86::GR8RegisterClass);
10134 case X86::ATOMXOR8:
10135 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10136 X86::XOR8ri, X86::MOV8rm,
10138 X86::NOT8r, X86::AL,
10139 X86::GR8RegisterClass);
10140 case X86::ATOMNAND8:
10141 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10142 X86::AND8ri, X86::MOV8rm,
10144 X86::NOT8r, X86::AL,
10145 X86::GR8RegisterClass, true);
10146 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10147 // This group is for 64-bit host.
10148 case X86::ATOMAND64:
10149 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10150 X86::AND64ri32, X86::MOV64rm,
10152 X86::NOT64r, X86::RAX,
10153 X86::GR64RegisterClass);
10154 case X86::ATOMOR64:
10155 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10156 X86::OR64ri32, X86::MOV64rm,
10158 X86::NOT64r, X86::RAX,
10159 X86::GR64RegisterClass);
10160 case X86::ATOMXOR64:
10161 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10162 X86::XOR64ri32, X86::MOV64rm,
10164 X86::NOT64r, X86::RAX,
10165 X86::GR64RegisterClass);
10166 case X86::ATOMNAND64:
10167 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10168 X86::AND64ri32, X86::MOV64rm,
10170 X86::NOT64r, X86::RAX,
10171 X86::GR64RegisterClass, true);
10172 case X86::ATOMMIN64:
10173 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10174 case X86::ATOMMAX64:
10175 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10176 case X86::ATOMUMIN64:
10177 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10178 case X86::ATOMUMAX64:
10179 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10181 // This group does 64-bit operations on a 32-bit host.
10182 case X86::ATOMAND6432:
10183 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10184 X86::AND32rr, X86::AND32rr,
10185 X86::AND32ri, X86::AND32ri,
10187 case X86::ATOMOR6432:
10188 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10189 X86::OR32rr, X86::OR32rr,
10190 X86::OR32ri, X86::OR32ri,
10192 case X86::ATOMXOR6432:
10193 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10194 X86::XOR32rr, X86::XOR32rr,
10195 X86::XOR32ri, X86::XOR32ri,
10197 case X86::ATOMNAND6432:
10198 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10199 X86::AND32rr, X86::AND32rr,
10200 X86::AND32ri, X86::AND32ri,
10202 case X86::ATOMADD6432:
10203 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10204 X86::ADD32rr, X86::ADC32rr,
10205 X86::ADD32ri, X86::ADC32ri,
10207 case X86::ATOMSUB6432:
10208 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10209 X86::SUB32rr, X86::SBB32rr,
10210 X86::SUB32ri, X86::SBB32ri,
10212 case X86::ATOMSWAP6432:
10213 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10214 X86::MOV32rr, X86::MOV32rr,
10215 X86::MOV32ri, X86::MOV32ri,
10217 case X86::VASTART_SAVE_XMM_REGS:
10218 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10220 case X86::VAARG_64:
10221 return EmitVAARG64WithCustomInserter(MI, BB);
10225 //===----------------------------------------------------------------------===//
10226 // X86 Optimization Hooks
10227 //===----------------------------------------------------------------------===//
10229 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10233 const SelectionDAG &DAG,
10234 unsigned Depth) const {
10235 unsigned Opc = Op.getOpcode();
10236 assert((Opc >= ISD::BUILTIN_OP_END ||
10237 Opc == ISD::INTRINSIC_WO_CHAIN ||
10238 Opc == ISD::INTRINSIC_W_CHAIN ||
10239 Opc == ISD::INTRINSIC_VOID) &&
10240 "Should use MaskedValueIsZero if you don't know whether Op"
10241 " is a target node!");
10243 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10255 // These nodes' second result is a boolean.
10256 if (Op.getResNo() == 0)
10259 case X86ISD::SETCC:
10260 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10261 Mask.getBitWidth() - 1);
10266 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10267 unsigned Depth) const {
10268 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10269 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10270 return Op.getValueType().getScalarType().getSizeInBits();
10276 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10277 /// node is a GlobalAddress + offset.
10278 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10279 const GlobalValue* &GA,
10280 int64_t &Offset) const {
10281 if (N->getOpcode() == X86ISD::Wrapper) {
10282 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10283 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10284 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10288 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10291 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10292 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10293 /// if the load addresses are consecutive, non-overlapping, and in the right
10295 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10296 const TargetLowering &TLI) {
10297 DebugLoc dl = N->getDebugLoc();
10298 EVT VT = N->getValueType(0);
10300 if (VT.getSizeInBits() != 128)
10303 SmallVector<SDValue, 16> Elts;
10304 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10305 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10307 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10310 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10311 /// generation and convert it from being a bunch of shuffles and extracts
10312 /// to a simple store and scalar loads to extract the elements.
10313 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10314 const TargetLowering &TLI) {
10315 SDValue InputVector = N->getOperand(0);
10317 // Only operate on vectors of 4 elements, where the alternative shuffling
10318 // gets to be more expensive.
10319 if (InputVector.getValueType() != MVT::v4i32)
10322 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10323 // single use which is a sign-extend or zero-extend, and all elements are
10325 SmallVector<SDNode *, 4> Uses;
10326 unsigned ExtractedElements = 0;
10327 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10328 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10329 if (UI.getUse().getResNo() != InputVector.getResNo())
10332 SDNode *Extract = *UI;
10333 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10336 if (Extract->getValueType(0) != MVT::i32)
10338 if (!Extract->hasOneUse())
10340 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10341 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10343 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10346 // Record which element was extracted.
10347 ExtractedElements |=
10348 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10350 Uses.push_back(Extract);
10353 // If not all the elements were used, this may not be worthwhile.
10354 if (ExtractedElements != 15)
10357 // Ok, we've now decided to do the transformation.
10358 DebugLoc dl = InputVector.getDebugLoc();
10360 // Store the value to a temporary stack slot.
10361 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10362 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10363 MachinePointerInfo(), false, false, 0);
10365 // Replace each use (extract) with a load of the appropriate element.
10366 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10367 UE = Uses.end(); UI != UE; ++UI) {
10368 SDNode *Extract = *UI;
10370 // Compute the element's address.
10371 SDValue Idx = Extract->getOperand(1);
10373 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10374 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10375 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10377 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10378 StackPtr, OffsetVal);
10380 // Load the scalar.
10381 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10382 ScalarAddr, MachinePointerInfo(),
10385 // Replace the exact with the load.
10386 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10389 // The replacement was made in place; don't return anything.
10393 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10394 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10395 const X86Subtarget *Subtarget) {
10396 DebugLoc DL = N->getDebugLoc();
10397 SDValue Cond = N->getOperand(0);
10398 // Get the LHS/RHS of the select.
10399 SDValue LHS = N->getOperand(1);
10400 SDValue RHS = N->getOperand(2);
10402 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10403 // instructions match the semantics of the common C idiom x<y?x:y but not
10404 // x<=y?x:y, because of how they handle negative zero (which can be
10405 // ignored in unsafe-math mode).
10406 if (Subtarget->hasSSE2() &&
10407 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10408 Cond.getOpcode() == ISD::SETCC) {
10409 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10411 unsigned Opcode = 0;
10412 // Check for x CC y ? x : y.
10413 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10414 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10418 // Converting this to a min would handle NaNs incorrectly, and swapping
10419 // the operands would cause it to handle comparisons between positive
10420 // and negative zero incorrectly.
10421 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10422 if (!UnsafeFPMath &&
10423 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10425 std::swap(LHS, RHS);
10427 Opcode = X86ISD::FMIN;
10430 // Converting this to a min would handle comparisons between positive
10431 // and negative zero incorrectly.
10432 if (!UnsafeFPMath &&
10433 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10435 Opcode = X86ISD::FMIN;
10438 // Converting this to a min would handle both negative zeros and NaNs
10439 // incorrectly, but we can swap the operands to fix both.
10440 std::swap(LHS, RHS);
10444 Opcode = X86ISD::FMIN;
10448 // Converting this to a max would handle comparisons between positive
10449 // and negative zero incorrectly.
10450 if (!UnsafeFPMath &&
10451 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10453 Opcode = X86ISD::FMAX;
10456 // Converting this to a max would handle NaNs incorrectly, and swapping
10457 // the operands would cause it to handle comparisons between positive
10458 // and negative zero incorrectly.
10459 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10460 if (!UnsafeFPMath &&
10461 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10463 std::swap(LHS, RHS);
10465 Opcode = X86ISD::FMAX;
10468 // Converting this to a max would handle both negative zeros and NaNs
10469 // incorrectly, but we can swap the operands to fix both.
10470 std::swap(LHS, RHS);
10474 Opcode = X86ISD::FMAX;
10477 // Check for x CC y ? y : x -- a min/max with reversed arms.
10478 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10479 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10483 // Converting this to a min would handle comparisons between positive
10484 // and negative zero incorrectly, and swapping the operands would
10485 // cause it to handle NaNs incorrectly.
10486 if (!UnsafeFPMath &&
10487 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10488 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10490 std::swap(LHS, RHS);
10492 Opcode = X86ISD::FMIN;
10495 // Converting this to a min would handle NaNs incorrectly.
10496 if (!UnsafeFPMath &&
10497 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10499 Opcode = X86ISD::FMIN;
10502 // Converting this to a min would handle both negative zeros and NaNs
10503 // incorrectly, but we can swap the operands to fix both.
10504 std::swap(LHS, RHS);
10508 Opcode = X86ISD::FMIN;
10512 // Converting this to a max would handle NaNs incorrectly.
10513 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10515 Opcode = X86ISD::FMAX;
10518 // Converting this to a max would handle comparisons between positive
10519 // and negative zero incorrectly, and swapping the operands would
10520 // cause it to handle NaNs incorrectly.
10521 if (!UnsafeFPMath &&
10522 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10523 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10525 std::swap(LHS, RHS);
10527 Opcode = X86ISD::FMAX;
10530 // Converting this to a max would handle both negative zeros and NaNs
10531 // incorrectly, but we can swap the operands to fix both.
10532 std::swap(LHS, RHS);
10536 Opcode = X86ISD::FMAX;
10542 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10545 // If this is a select between two integer constants, try to do some
10547 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10548 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10549 // Don't do this for crazy integer types.
10550 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10551 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10552 // so that TrueC (the true value) is larger than FalseC.
10553 bool NeedsCondInvert = false;
10555 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10556 // Efficiently invertible.
10557 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10558 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10559 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10560 NeedsCondInvert = true;
10561 std::swap(TrueC, FalseC);
10564 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10565 if (FalseC->getAPIntValue() == 0 &&
10566 TrueC->getAPIntValue().isPowerOf2()) {
10567 if (NeedsCondInvert) // Invert the condition if needed.
10568 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10569 DAG.getConstant(1, Cond.getValueType()));
10571 // Zero extend the condition if needed.
10572 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10574 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10575 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10576 DAG.getConstant(ShAmt, MVT::i8));
10579 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10580 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10581 if (NeedsCondInvert) // Invert the condition if needed.
10582 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10583 DAG.getConstant(1, Cond.getValueType()));
10585 // Zero extend the condition if needed.
10586 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10587 FalseC->getValueType(0), Cond);
10588 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10589 SDValue(FalseC, 0));
10592 // Optimize cases that will turn into an LEA instruction. This requires
10593 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10594 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10595 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10596 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10598 bool isFastMultiplier = false;
10600 switch ((unsigned char)Diff) {
10602 case 1: // result = add base, cond
10603 case 2: // result = lea base( , cond*2)
10604 case 3: // result = lea base(cond, cond*2)
10605 case 4: // result = lea base( , cond*4)
10606 case 5: // result = lea base(cond, cond*4)
10607 case 8: // result = lea base( , cond*8)
10608 case 9: // result = lea base(cond, cond*8)
10609 isFastMultiplier = true;
10614 if (isFastMultiplier) {
10615 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10616 if (NeedsCondInvert) // Invert the condition if needed.
10617 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10618 DAG.getConstant(1, Cond.getValueType()));
10620 // Zero extend the condition if needed.
10621 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10623 // Scale the condition by the difference.
10625 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10626 DAG.getConstant(Diff, Cond.getValueType()));
10628 // Add the base if non-zero.
10629 if (FalseC->getAPIntValue() != 0)
10630 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10631 SDValue(FalseC, 0));
10641 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10642 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10643 TargetLowering::DAGCombinerInfo &DCI) {
10644 DebugLoc DL = N->getDebugLoc();
10646 // If the flag operand isn't dead, don't touch this CMOV.
10647 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10650 // If this is a select between two integer constants, try to do some
10651 // optimizations. Note that the operands are ordered the opposite of SELECT
10653 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10654 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10655 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10656 // larger than FalseC (the false value).
10657 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10659 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10660 CC = X86::GetOppositeBranchCondition(CC);
10661 std::swap(TrueC, FalseC);
10664 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10665 // This is efficient for any integer data type (including i8/i16) and
10667 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10668 SDValue Cond = N->getOperand(3);
10669 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10670 DAG.getConstant(CC, MVT::i8), Cond);
10672 // Zero extend the condition if needed.
10673 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10675 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10676 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10677 DAG.getConstant(ShAmt, MVT::i8));
10678 if (N->getNumValues() == 2) // Dead flag value?
10679 return DCI.CombineTo(N, Cond, SDValue());
10683 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10684 // for any integer data type, including i8/i16.
10685 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10686 SDValue Cond = N->getOperand(3);
10687 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10688 DAG.getConstant(CC, MVT::i8), Cond);
10690 // Zero extend the condition if needed.
10691 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10692 FalseC->getValueType(0), Cond);
10693 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10694 SDValue(FalseC, 0));
10696 if (N->getNumValues() == 2) // Dead flag value?
10697 return DCI.CombineTo(N, Cond, SDValue());
10701 // Optimize cases that will turn into an LEA instruction. This requires
10702 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10703 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10704 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10705 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10707 bool isFastMultiplier = false;
10709 switch ((unsigned char)Diff) {
10711 case 1: // result = add base, cond
10712 case 2: // result = lea base( , cond*2)
10713 case 3: // result = lea base(cond, cond*2)
10714 case 4: // result = lea base( , cond*4)
10715 case 5: // result = lea base(cond, cond*4)
10716 case 8: // result = lea base( , cond*8)
10717 case 9: // result = lea base(cond, cond*8)
10718 isFastMultiplier = true;
10723 if (isFastMultiplier) {
10724 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10725 SDValue Cond = N->getOperand(3);
10726 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10727 DAG.getConstant(CC, MVT::i8), Cond);
10728 // Zero extend the condition if needed.
10729 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10731 // Scale the condition by the difference.
10733 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10734 DAG.getConstant(Diff, Cond.getValueType()));
10736 // Add the base if non-zero.
10737 if (FalseC->getAPIntValue() != 0)
10738 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10739 SDValue(FalseC, 0));
10740 if (N->getNumValues() == 2) // Dead flag value?
10741 return DCI.CombineTo(N, Cond, SDValue());
10751 /// PerformMulCombine - Optimize a single multiply with constant into two
10752 /// in order to implement it with two cheaper instructions, e.g.
10753 /// LEA + SHL, LEA + LEA.
10754 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10755 TargetLowering::DAGCombinerInfo &DCI) {
10756 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10759 EVT VT = N->getValueType(0);
10760 if (VT != MVT::i64)
10763 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10766 uint64_t MulAmt = C->getZExtValue();
10767 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10770 uint64_t MulAmt1 = 0;
10771 uint64_t MulAmt2 = 0;
10772 if ((MulAmt % 9) == 0) {
10774 MulAmt2 = MulAmt / 9;
10775 } else if ((MulAmt % 5) == 0) {
10777 MulAmt2 = MulAmt / 5;
10778 } else if ((MulAmt % 3) == 0) {
10780 MulAmt2 = MulAmt / 3;
10783 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10784 DebugLoc DL = N->getDebugLoc();
10786 if (isPowerOf2_64(MulAmt2) &&
10787 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10788 // If second multiplifer is pow2, issue it first. We want the multiply by
10789 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10791 std::swap(MulAmt1, MulAmt2);
10794 if (isPowerOf2_64(MulAmt1))
10795 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10796 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10798 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10799 DAG.getConstant(MulAmt1, VT));
10801 if (isPowerOf2_64(MulAmt2))
10802 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10803 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10805 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10806 DAG.getConstant(MulAmt2, VT));
10808 // Do not add new nodes to DAG combiner worklist.
10809 DCI.CombineTo(N, NewMul, false);
10814 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10815 SDValue N0 = N->getOperand(0);
10816 SDValue N1 = N->getOperand(1);
10817 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10818 EVT VT = N0.getValueType();
10820 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10821 // since the result of setcc_c is all zero's or all ones.
10822 if (N1C && N0.getOpcode() == ISD::AND &&
10823 N0.getOperand(1).getOpcode() == ISD::Constant) {
10824 SDValue N00 = N0.getOperand(0);
10825 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10826 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10827 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10828 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10829 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10830 APInt ShAmt = N1C->getAPIntValue();
10831 Mask = Mask.shl(ShAmt);
10833 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10834 N00, DAG.getConstant(Mask, VT));
10841 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10843 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10844 const X86Subtarget *Subtarget) {
10845 EVT VT = N->getValueType(0);
10846 if (!VT.isVector() && VT.isInteger() &&
10847 N->getOpcode() == ISD::SHL)
10848 return PerformSHLCombine(N, DAG);
10850 // On X86 with SSE2 support, we can transform this to a vector shift if
10851 // all elements are shifted by the same amount. We can't do this in legalize
10852 // because the a constant vector is typically transformed to a constant pool
10853 // so we have no knowledge of the shift amount.
10854 if (!Subtarget->hasSSE2())
10857 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10860 SDValue ShAmtOp = N->getOperand(1);
10861 EVT EltVT = VT.getVectorElementType();
10862 DebugLoc DL = N->getDebugLoc();
10863 SDValue BaseShAmt = SDValue();
10864 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10865 unsigned NumElts = VT.getVectorNumElements();
10867 for (; i != NumElts; ++i) {
10868 SDValue Arg = ShAmtOp.getOperand(i);
10869 if (Arg.getOpcode() == ISD::UNDEF) continue;
10873 for (; i != NumElts; ++i) {
10874 SDValue Arg = ShAmtOp.getOperand(i);
10875 if (Arg.getOpcode() == ISD::UNDEF) continue;
10876 if (Arg != BaseShAmt) {
10880 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10881 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10882 SDValue InVec = ShAmtOp.getOperand(0);
10883 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10884 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10886 for (; i != NumElts; ++i) {
10887 SDValue Arg = InVec.getOperand(i);
10888 if (Arg.getOpcode() == ISD::UNDEF) continue;
10892 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10894 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10895 if (C->getZExtValue() == SplatIdx)
10896 BaseShAmt = InVec.getOperand(1);
10899 if (BaseShAmt.getNode() == 0)
10900 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10901 DAG.getIntPtrConstant(0));
10905 // The shift amount is an i32.
10906 if (EltVT.bitsGT(MVT::i32))
10907 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10908 else if (EltVT.bitsLT(MVT::i32))
10909 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10911 // The shift amount is identical so we can do a vector shift.
10912 SDValue ValOp = N->getOperand(0);
10913 switch (N->getOpcode()) {
10915 llvm_unreachable("Unknown shift opcode!");
10918 if (VT == MVT::v2i64)
10919 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10920 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10922 if (VT == MVT::v4i32)
10923 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10924 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10926 if (VT == MVT::v8i16)
10927 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10928 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10932 if (VT == MVT::v4i32)
10933 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10934 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10936 if (VT == MVT::v8i16)
10937 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10938 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10942 if (VT == MVT::v2i64)
10943 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10944 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10946 if (VT == MVT::v4i32)
10947 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10948 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10950 if (VT == MVT::v8i16)
10951 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10952 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10959 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10960 TargetLowering::DAGCombinerInfo &DCI,
10961 const X86Subtarget *Subtarget) {
10962 if (DCI.isBeforeLegalizeOps())
10965 EVT VT = N->getValueType(0);
10966 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10969 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10970 SDValue N0 = N->getOperand(0);
10971 SDValue N1 = N->getOperand(1);
10972 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10974 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10976 if (!N0.hasOneUse() || !N1.hasOneUse())
10979 SDValue ShAmt0 = N0.getOperand(1);
10980 if (ShAmt0.getValueType() != MVT::i8)
10982 SDValue ShAmt1 = N1.getOperand(1);
10983 if (ShAmt1.getValueType() != MVT::i8)
10985 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10986 ShAmt0 = ShAmt0.getOperand(0);
10987 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10988 ShAmt1 = ShAmt1.getOperand(0);
10990 DebugLoc DL = N->getDebugLoc();
10991 unsigned Opc = X86ISD::SHLD;
10992 SDValue Op0 = N0.getOperand(0);
10993 SDValue Op1 = N1.getOperand(0);
10994 if (ShAmt0.getOpcode() == ISD::SUB) {
10995 Opc = X86ISD::SHRD;
10996 std::swap(Op0, Op1);
10997 std::swap(ShAmt0, ShAmt1);
11000 unsigned Bits = VT.getSizeInBits();
11001 if (ShAmt1.getOpcode() == ISD::SUB) {
11002 SDValue Sum = ShAmt1.getOperand(0);
11003 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11004 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11005 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11006 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11007 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11008 return DAG.getNode(Opc, DL, VT,
11010 DAG.getNode(ISD::TRUNCATE, DL,
11013 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11014 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11016 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11017 return DAG.getNode(Opc, DL, VT,
11018 N0.getOperand(0), N1.getOperand(0),
11019 DAG.getNode(ISD::TRUNCATE, DL,
11026 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11027 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11028 const X86Subtarget *Subtarget) {
11029 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11030 // the FP state in cases where an emms may be missing.
11031 // A preferable solution to the general problem is to figure out the right
11032 // places to insert EMMS. This qualifies as a quick hack.
11034 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11035 StoreSDNode *St = cast<StoreSDNode>(N);
11036 EVT VT = St->getValue().getValueType();
11037 if (VT.getSizeInBits() != 64)
11040 const Function *F = DAG.getMachineFunction().getFunction();
11041 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11042 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11043 && Subtarget->hasSSE2();
11044 if ((VT.isVector() ||
11045 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11046 isa<LoadSDNode>(St->getValue()) &&
11047 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11048 St->getChain().hasOneUse() && !St->isVolatile()) {
11049 SDNode* LdVal = St->getValue().getNode();
11050 LoadSDNode *Ld = 0;
11051 int TokenFactorIndex = -1;
11052 SmallVector<SDValue, 8> Ops;
11053 SDNode* ChainVal = St->getChain().getNode();
11054 // Must be a store of a load. We currently handle two cases: the load
11055 // is a direct child, and it's under an intervening TokenFactor. It is
11056 // possible to dig deeper under nested TokenFactors.
11057 if (ChainVal == LdVal)
11058 Ld = cast<LoadSDNode>(St->getChain());
11059 else if (St->getValue().hasOneUse() &&
11060 ChainVal->getOpcode() == ISD::TokenFactor) {
11061 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11062 if (ChainVal->getOperand(i).getNode() == LdVal) {
11063 TokenFactorIndex = i;
11064 Ld = cast<LoadSDNode>(St->getValue());
11066 Ops.push_back(ChainVal->getOperand(i));
11070 if (!Ld || !ISD::isNormalLoad(Ld))
11073 // If this is not the MMX case, i.e. we are just turning i64 load/store
11074 // into f64 load/store, avoid the transformation if there are multiple
11075 // uses of the loaded value.
11076 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11079 DebugLoc LdDL = Ld->getDebugLoc();
11080 DebugLoc StDL = N->getDebugLoc();
11081 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11082 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11084 if (Subtarget->is64Bit() || F64IsLegal) {
11085 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11086 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11087 Ld->getPointerInfo(), Ld->isVolatile(),
11088 Ld->isNonTemporal(), Ld->getAlignment());
11089 SDValue NewChain = NewLd.getValue(1);
11090 if (TokenFactorIndex != -1) {
11091 Ops.push_back(NewChain);
11092 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11095 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11096 St->getPointerInfo(),
11097 St->isVolatile(), St->isNonTemporal(),
11098 St->getAlignment());
11101 // Otherwise, lower to two pairs of 32-bit loads / stores.
11102 SDValue LoAddr = Ld->getBasePtr();
11103 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11104 DAG.getConstant(4, MVT::i32));
11106 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11107 Ld->getPointerInfo(),
11108 Ld->isVolatile(), Ld->isNonTemporal(),
11109 Ld->getAlignment());
11110 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11111 Ld->getPointerInfo().getWithOffset(4),
11112 Ld->isVolatile(), Ld->isNonTemporal(),
11113 MinAlign(Ld->getAlignment(), 4));
11115 SDValue NewChain = LoLd.getValue(1);
11116 if (TokenFactorIndex != -1) {
11117 Ops.push_back(LoLd);
11118 Ops.push_back(HiLd);
11119 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11123 LoAddr = St->getBasePtr();
11124 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11125 DAG.getConstant(4, MVT::i32));
11127 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11128 St->getPointerInfo(),
11129 St->isVolatile(), St->isNonTemporal(),
11130 St->getAlignment());
11131 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11132 St->getPointerInfo().getWithOffset(4),
11134 St->isNonTemporal(),
11135 MinAlign(St->getAlignment(), 4));
11136 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11141 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11142 /// X86ISD::FXOR nodes.
11143 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11144 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11145 // F[X]OR(0.0, x) -> x
11146 // F[X]OR(x, 0.0) -> x
11147 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11148 if (C->getValueAPF().isPosZero())
11149 return N->getOperand(1);
11150 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11151 if (C->getValueAPF().isPosZero())
11152 return N->getOperand(0);
11156 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11157 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11158 // FAND(0.0, x) -> 0.0
11159 // FAND(x, 0.0) -> 0.0
11160 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11161 if (C->getValueAPF().isPosZero())
11162 return N->getOperand(0);
11163 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11164 if (C->getValueAPF().isPosZero())
11165 return N->getOperand(1);
11169 static SDValue PerformBTCombine(SDNode *N,
11171 TargetLowering::DAGCombinerInfo &DCI) {
11172 // BT ignores high bits in the bit index operand.
11173 SDValue Op1 = N->getOperand(1);
11174 if (Op1.hasOneUse()) {
11175 unsigned BitWidth = Op1.getValueSizeInBits();
11176 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11177 APInt KnownZero, KnownOne;
11178 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11179 !DCI.isBeforeLegalizeOps());
11180 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11181 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11182 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11183 DCI.CommitTargetLoweringOpt(TLO);
11188 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11189 SDValue Op = N->getOperand(0);
11190 if (Op.getOpcode() == ISD::BIT_CONVERT)
11191 Op = Op.getOperand(0);
11192 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11193 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11194 VT.getVectorElementType().getSizeInBits() ==
11195 OpVT.getVectorElementType().getSizeInBits()) {
11196 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
11201 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11202 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11203 // (and (i32 x86isd::setcc_carry), 1)
11204 // This eliminates the zext. This transformation is necessary because
11205 // ISD::SETCC is always legalized to i8.
11206 DebugLoc dl = N->getDebugLoc();
11207 SDValue N0 = N->getOperand(0);
11208 EVT VT = N->getValueType(0);
11209 if (N0.getOpcode() == ISD::AND &&
11211 N0.getOperand(0).hasOneUse()) {
11212 SDValue N00 = N0.getOperand(0);
11213 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11215 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11216 if (!C || C->getZExtValue() != 1)
11218 return DAG.getNode(ISD::AND, dl, VT,
11219 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11220 N00.getOperand(0), N00.getOperand(1)),
11221 DAG.getConstant(1, VT));
11227 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11228 DAGCombinerInfo &DCI) const {
11229 SelectionDAG &DAG = DCI.DAG;
11230 switch (N->getOpcode()) {
11232 case ISD::EXTRACT_VECTOR_ELT:
11233 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11234 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11235 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11236 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11239 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11240 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11241 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11243 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11244 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11245 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11246 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11247 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11248 case X86ISD::SHUFPS: // Handle all target specific shuffles
11249 case X86ISD::SHUFPD:
11250 case X86ISD::PALIGN:
11251 case X86ISD::PUNPCKHBW:
11252 case X86ISD::PUNPCKHWD:
11253 case X86ISD::PUNPCKHDQ:
11254 case X86ISD::PUNPCKHQDQ:
11255 case X86ISD::UNPCKHPS:
11256 case X86ISD::UNPCKHPD:
11257 case X86ISD::PUNPCKLBW:
11258 case X86ISD::PUNPCKLWD:
11259 case X86ISD::PUNPCKLDQ:
11260 case X86ISD::PUNPCKLQDQ:
11261 case X86ISD::UNPCKLPS:
11262 case X86ISD::UNPCKLPD:
11263 case X86ISD::MOVHLPS:
11264 case X86ISD::MOVLHPS:
11265 case X86ISD::PSHUFD:
11266 case X86ISD::PSHUFHW:
11267 case X86ISD::PSHUFLW:
11268 case X86ISD::MOVSS:
11269 case X86ISD::MOVSD:
11270 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11276 /// isTypeDesirableForOp - Return true if the target has native support for
11277 /// the specified value type and it is 'desirable' to use the type for the
11278 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11279 /// instruction encodings are longer and some i16 instructions are slow.
11280 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11281 if (!isTypeLegal(VT))
11283 if (VT != MVT::i16)
11290 case ISD::SIGN_EXTEND:
11291 case ISD::ZERO_EXTEND:
11292 case ISD::ANY_EXTEND:
11305 /// IsDesirableToPromoteOp - This method query the target whether it is
11306 /// beneficial for dag combiner to promote the specified node. If true, it
11307 /// should return the desired promotion type by reference.
11308 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11309 EVT VT = Op.getValueType();
11310 if (VT != MVT::i16)
11313 bool Promote = false;
11314 bool Commute = false;
11315 switch (Op.getOpcode()) {
11318 LoadSDNode *LD = cast<LoadSDNode>(Op);
11319 // If the non-extending load has a single use and it's not live out, then it
11320 // might be folded.
11321 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11322 Op.hasOneUse()*/) {
11323 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11324 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11325 // The only case where we'd want to promote LOAD (rather then it being
11326 // promoted as an operand is when it's only use is liveout.
11327 if (UI->getOpcode() != ISD::CopyToReg)
11334 case ISD::SIGN_EXTEND:
11335 case ISD::ZERO_EXTEND:
11336 case ISD::ANY_EXTEND:
11341 SDValue N0 = Op.getOperand(0);
11342 // Look out for (store (shl (load), x)).
11343 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11356 SDValue N0 = Op.getOperand(0);
11357 SDValue N1 = Op.getOperand(1);
11358 if (!Commute && MayFoldLoad(N1))
11360 // Avoid disabling potential load folding opportunities.
11361 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11363 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11373 //===----------------------------------------------------------------------===//
11374 // X86 Inline Assembly Support
11375 //===----------------------------------------------------------------------===//
11377 static bool LowerToBSwap(CallInst *CI) {
11378 // FIXME: this should verify that we are targetting a 486 or better. If not,
11379 // we will turn this bswap into something that will be lowered to logical ops
11380 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11381 // so don't worry about this.
11383 // Verify this is a simple bswap.
11384 if (CI->getNumArgOperands() != 1 ||
11385 CI->getType() != CI->getArgOperand(0)->getType() ||
11386 !CI->getType()->isIntegerTy())
11389 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11390 if (!Ty || Ty->getBitWidth() % 16 != 0)
11393 // Okay, we can do this xform, do so now.
11394 const Type *Tys[] = { Ty };
11395 Module *M = CI->getParent()->getParent()->getParent();
11396 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11398 Value *Op = CI->getArgOperand(0);
11399 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11401 CI->replaceAllUsesWith(Op);
11402 CI->eraseFromParent();
11406 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11407 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11408 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11410 std::string AsmStr = IA->getAsmString();
11412 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11413 SmallVector<StringRef, 4> AsmPieces;
11414 SplitString(AsmStr, AsmPieces, ";\n");
11416 switch (AsmPieces.size()) {
11417 default: return false;
11419 AsmStr = AsmPieces[0];
11421 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11424 if (AsmPieces.size() == 2 &&
11425 (AsmPieces[0] == "bswap" ||
11426 AsmPieces[0] == "bswapq" ||
11427 AsmPieces[0] == "bswapl") &&
11428 (AsmPieces[1] == "$0" ||
11429 AsmPieces[1] == "${0:q}")) {
11430 // No need to check constraints, nothing other than the equivalent of
11431 // "=r,0" would be valid here.
11432 return LowerToBSwap(CI);
11434 // rorw $$8, ${0:w} --> llvm.bswap.i16
11435 if (CI->getType()->isIntegerTy(16) &&
11436 AsmPieces.size() == 3 &&
11437 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11438 AsmPieces[1] == "$$8," &&
11439 AsmPieces[2] == "${0:w}" &&
11440 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11442 const std::string &Constraints = IA->getConstraintString();
11443 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11444 std::sort(AsmPieces.begin(), AsmPieces.end());
11445 if (AsmPieces.size() == 4 &&
11446 AsmPieces[0] == "~{cc}" &&
11447 AsmPieces[1] == "~{dirflag}" &&
11448 AsmPieces[2] == "~{flags}" &&
11449 AsmPieces[3] == "~{fpsr}") {
11450 return LowerToBSwap(CI);
11455 if (CI->getType()->isIntegerTy(32) &&
11456 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11457 SmallVector<StringRef, 4> Words;
11458 SplitString(AsmPieces[0], Words, " \t,");
11459 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11460 Words[2] == "${0:w}") {
11462 SplitString(AsmPieces[1], Words, " \t,");
11463 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11464 Words[2] == "$0") {
11466 SplitString(AsmPieces[2], Words, " \t,");
11467 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11468 Words[2] == "${0:w}") {
11470 const std::string &Constraints = IA->getConstraintString();
11471 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11472 std::sort(AsmPieces.begin(), AsmPieces.end());
11473 if (AsmPieces.size() == 4 &&
11474 AsmPieces[0] == "~{cc}" &&
11475 AsmPieces[1] == "~{dirflag}" &&
11476 AsmPieces[2] == "~{flags}" &&
11477 AsmPieces[3] == "~{fpsr}") {
11478 return LowerToBSwap(CI);
11484 if (CI->getType()->isIntegerTy(64) &&
11485 Constraints.size() >= 2 &&
11486 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11487 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11488 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11489 SmallVector<StringRef, 4> Words;
11490 SplitString(AsmPieces[0], Words, " \t");
11491 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11493 SplitString(AsmPieces[1], Words, " \t");
11494 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11496 SplitString(AsmPieces[2], Words, " \t,");
11497 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11498 Words[2] == "%edx") {
11499 return LowerToBSwap(CI);
11511 /// getConstraintType - Given a constraint letter, return the type of
11512 /// constraint it is for this target.
11513 X86TargetLowering::ConstraintType
11514 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11515 if (Constraint.size() == 1) {
11516 switch (Constraint[0]) {
11526 return C_RegisterClass;
11550 return TargetLowering::getConstraintType(Constraint);
11553 /// Examine constraint type and operand type and determine a weight value.
11554 /// This object must already have been set up with the operand type
11555 /// and the current alternative constraint selected.
11556 TargetLowering::ConstraintWeight
11557 X86TargetLowering::getSingleConstraintMatchWeight(
11558 AsmOperandInfo &info, const char *constraint) const {
11559 ConstraintWeight weight = CW_Invalid;
11560 Value *CallOperandVal = info.CallOperandVal;
11561 // If we don't have a value, we can't do a match,
11562 // but allow it at the lowest weight.
11563 if (CallOperandVal == NULL)
11565 const Type *type = CallOperandVal->getType();
11566 // Look at the constraint type.
11567 switch (*constraint) {
11569 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11580 if (CallOperandVal->getType()->isIntegerTy())
11581 weight = CW_SpecificReg;
11586 if (type->isFloatingPointTy())
11587 weight = CW_SpecificReg;
11590 if (type->isX86_MMXTy() && !DisableMMX && Subtarget->hasMMX())
11591 weight = CW_SpecificReg;
11595 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1())
11596 weight = CW_Register;
11599 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11600 if (C->getZExtValue() <= 31)
11601 weight = CW_Constant;
11605 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11606 if (C->getZExtValue() <= 63)
11607 weight = CW_Constant;
11611 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11612 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11613 weight = CW_Constant;
11617 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11618 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11619 weight = CW_Constant;
11623 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11624 if (C->getZExtValue() <= 3)
11625 weight = CW_Constant;
11629 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11630 if (C->getZExtValue() <= 0xff)
11631 weight = CW_Constant;
11636 if (dyn_cast<ConstantFP>(CallOperandVal)) {
11637 weight = CW_Constant;
11641 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11642 if ((C->getSExtValue() >= -0x80000000LL) &&
11643 (C->getSExtValue() <= 0x7fffffffLL))
11644 weight = CW_Constant;
11648 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11649 if (C->getZExtValue() <= 0xffffffff)
11650 weight = CW_Constant;
11657 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11658 /// with another that has more specific requirements based on the type of the
11659 /// corresponding operand.
11660 const char *X86TargetLowering::
11661 LowerXConstraint(EVT ConstraintVT) const {
11662 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11663 // 'f' like normal targets.
11664 if (ConstraintVT.isFloatingPoint()) {
11665 if (Subtarget->hasSSE2())
11667 if (Subtarget->hasSSE1())
11671 return TargetLowering::LowerXConstraint(ConstraintVT);
11674 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11675 /// vector. If it is invalid, don't add anything to Ops.
11676 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11678 std::vector<SDValue>&Ops,
11679 SelectionDAG &DAG) const {
11680 SDValue Result(0, 0);
11682 switch (Constraint) {
11685 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11686 if (C->getZExtValue() <= 31) {
11687 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11693 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11694 if (C->getZExtValue() <= 63) {
11695 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11701 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11702 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11703 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11709 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11710 if (C->getZExtValue() <= 255) {
11711 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11717 // 32-bit signed value
11718 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11719 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11720 C->getSExtValue())) {
11721 // Widen to 64 bits here to get it sign extended.
11722 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11725 // FIXME gcc accepts some relocatable values here too, but only in certain
11726 // memory models; it's complicated.
11731 // 32-bit unsigned value
11732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11733 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11734 C->getZExtValue())) {
11735 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11739 // FIXME gcc accepts some relocatable values here too, but only in certain
11740 // memory models; it's complicated.
11744 // Literal immediates are always ok.
11745 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11746 // Widen to 64 bits here to get it sign extended.
11747 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11751 // In any sort of PIC mode addresses need to be computed at runtime by
11752 // adding in a register or some sort of table lookup. These can't
11753 // be used as immediates.
11754 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11757 // If we are in non-pic codegen mode, we allow the address of a global (with
11758 // an optional displacement) to be used with 'i'.
11759 GlobalAddressSDNode *GA = 0;
11760 int64_t Offset = 0;
11762 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11764 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11765 Offset += GA->getOffset();
11767 } else if (Op.getOpcode() == ISD::ADD) {
11768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11769 Offset += C->getZExtValue();
11770 Op = Op.getOperand(0);
11773 } else if (Op.getOpcode() == ISD::SUB) {
11774 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11775 Offset += -C->getZExtValue();
11776 Op = Op.getOperand(0);
11781 // Otherwise, this isn't something we can handle, reject it.
11785 const GlobalValue *GV = GA->getGlobal();
11786 // If we require an extra load to get this address, as in PIC mode, we
11787 // can't accept it.
11788 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11789 getTargetMachine())))
11792 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11793 GA->getValueType(0), Offset);
11798 if (Result.getNode()) {
11799 Ops.push_back(Result);
11802 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11805 std::vector<unsigned> X86TargetLowering::
11806 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11808 if (Constraint.size() == 1) {
11809 // FIXME: not handling fp-stack yet!
11810 switch (Constraint[0]) { // GCC X86 Constraint Letters
11811 default: break; // Unknown constraint letter
11812 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11813 if (Subtarget->is64Bit()) {
11814 if (VT == MVT::i32)
11815 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11816 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11817 X86::R10D,X86::R11D,X86::R12D,
11818 X86::R13D,X86::R14D,X86::R15D,
11819 X86::EBP, X86::ESP, 0);
11820 else if (VT == MVT::i16)
11821 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
11822 X86::SI, X86::DI, X86::R8W,X86::R9W,
11823 X86::R10W,X86::R11W,X86::R12W,
11824 X86::R13W,X86::R14W,X86::R15W,
11825 X86::BP, X86::SP, 0);
11826 else if (VT == MVT::i8)
11827 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
11828 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11829 X86::R10B,X86::R11B,X86::R12B,
11830 X86::R13B,X86::R14B,X86::R15B,
11831 X86::BPL, X86::SPL, 0);
11833 else if (VT == MVT::i64)
11834 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11835 X86::RSI, X86::RDI, X86::R8, X86::R9,
11836 X86::R10, X86::R11, X86::R12,
11837 X86::R13, X86::R14, X86::R15,
11838 X86::RBP, X86::RSP, 0);
11842 // 32-bit fallthrough
11843 case 'Q': // Q_REGS
11844 if (VT == MVT::i32)
11845 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11846 else if (VT == MVT::i16)
11847 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11848 else if (VT == MVT::i8)
11849 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11850 else if (VT == MVT::i64)
11851 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11856 return std::vector<unsigned>();
11859 std::pair<unsigned, const TargetRegisterClass*>
11860 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11862 // First, see if this is a constraint that directly corresponds to an LLVM
11864 if (Constraint.size() == 1) {
11865 // GCC Constraint Letters
11866 switch (Constraint[0]) {
11868 case 'r': // GENERAL_REGS
11869 case 'l': // INDEX_REGS
11871 return std::make_pair(0U, X86::GR8RegisterClass);
11872 if (VT == MVT::i16)
11873 return std::make_pair(0U, X86::GR16RegisterClass);
11874 if (VT == MVT::i32 || !Subtarget->is64Bit())
11875 return std::make_pair(0U, X86::GR32RegisterClass);
11876 return std::make_pair(0U, X86::GR64RegisterClass);
11877 case 'R': // LEGACY_REGS
11879 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11880 if (VT == MVT::i16)
11881 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11882 if (VT == MVT::i32 || !Subtarget->is64Bit())
11883 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11884 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11885 case 'f': // FP Stack registers.
11886 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11887 // value to the correct fpstack register class.
11888 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11889 return std::make_pair(0U, X86::RFP32RegisterClass);
11890 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11891 return std::make_pair(0U, X86::RFP64RegisterClass);
11892 return std::make_pair(0U, X86::RFP80RegisterClass);
11893 case 'y': // MMX_REGS if MMX allowed.
11894 if (!Subtarget->hasMMX()) break;
11895 return std::make_pair(0U, X86::VR64RegisterClass);
11896 case 'Y': // SSE_REGS if SSE2 allowed
11897 if (!Subtarget->hasSSE2()) break;
11899 case 'x': // SSE_REGS if SSE1 allowed
11900 if (!Subtarget->hasSSE1()) break;
11902 switch (VT.getSimpleVT().SimpleTy) {
11904 // Scalar SSE types.
11907 return std::make_pair(0U, X86::FR32RegisterClass);
11910 return std::make_pair(0U, X86::FR64RegisterClass);
11918 return std::make_pair(0U, X86::VR128RegisterClass);
11924 // Use the default implementation in TargetLowering to convert the register
11925 // constraint into a member of a register class.
11926 std::pair<unsigned, const TargetRegisterClass*> Res;
11927 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11929 // Not found as a standard register?
11930 if (Res.second == 0) {
11931 // Map st(0) -> st(7) -> ST0
11932 if (Constraint.size() == 7 && Constraint[0] == '{' &&
11933 tolower(Constraint[1]) == 's' &&
11934 tolower(Constraint[2]) == 't' &&
11935 Constraint[3] == '(' &&
11936 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11937 Constraint[5] == ')' &&
11938 Constraint[6] == '}') {
11940 Res.first = X86::ST0+Constraint[4]-'0';
11941 Res.second = X86::RFP80RegisterClass;
11945 // GCC allows "st(0)" to be called just plain "st".
11946 if (StringRef("{st}").equals_lower(Constraint)) {
11947 Res.first = X86::ST0;
11948 Res.second = X86::RFP80RegisterClass;
11953 if (StringRef("{flags}").equals_lower(Constraint)) {
11954 Res.first = X86::EFLAGS;
11955 Res.second = X86::CCRRegisterClass;
11959 // 'A' means EAX + EDX.
11960 if (Constraint == "A") {
11961 Res.first = X86::EAX;
11962 Res.second = X86::GR32_ADRegisterClass;
11968 // Otherwise, check to see if this is a register class of the wrong value
11969 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11970 // turn into {ax},{dx}.
11971 if (Res.second->hasType(VT))
11972 return Res; // Correct type already, nothing to do.
11974 // All of the single-register GCC register classes map their values onto
11975 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
11976 // really want an 8-bit or 32-bit register, map to the appropriate register
11977 // class and return the appropriate register.
11978 if (Res.second == X86::GR16RegisterClass) {
11979 if (VT == MVT::i8) {
11980 unsigned DestReg = 0;
11981 switch (Res.first) {
11983 case X86::AX: DestReg = X86::AL; break;
11984 case X86::DX: DestReg = X86::DL; break;
11985 case X86::CX: DestReg = X86::CL; break;
11986 case X86::BX: DestReg = X86::BL; break;
11989 Res.first = DestReg;
11990 Res.second = X86::GR8RegisterClass;
11992 } else if (VT == MVT::i32) {
11993 unsigned DestReg = 0;
11994 switch (Res.first) {
11996 case X86::AX: DestReg = X86::EAX; break;
11997 case X86::DX: DestReg = X86::EDX; break;
11998 case X86::CX: DestReg = X86::ECX; break;
11999 case X86::BX: DestReg = X86::EBX; break;
12000 case X86::SI: DestReg = X86::ESI; break;
12001 case X86::DI: DestReg = X86::EDI; break;
12002 case X86::BP: DestReg = X86::EBP; break;
12003 case X86::SP: DestReg = X86::ESP; break;
12006 Res.first = DestReg;
12007 Res.second = X86::GR32RegisterClass;
12009 } else if (VT == MVT::i64) {
12010 unsigned DestReg = 0;
12011 switch (Res.first) {
12013 case X86::AX: DestReg = X86::RAX; break;
12014 case X86::DX: DestReg = X86::RDX; break;
12015 case X86::CX: DestReg = X86::RCX; break;
12016 case X86::BX: DestReg = X86::RBX; break;
12017 case X86::SI: DestReg = X86::RSI; break;
12018 case X86::DI: DestReg = X86::RDI; break;
12019 case X86::BP: DestReg = X86::RBP; break;
12020 case X86::SP: DestReg = X86::RSP; break;
12023 Res.first = DestReg;
12024 Res.second = X86::GR64RegisterClass;
12027 } else if (Res.second == X86::FR32RegisterClass ||
12028 Res.second == X86::FR64RegisterClass ||
12029 Res.second == X86::VR128RegisterClass) {
12030 // Handle references to XMM physical registers that got mapped into the
12031 // wrong class. This can happen with constraints like {xmm0} where the
12032 // target independent register mapper will just pick the first match it can
12033 // find, ignoring the required type.
12034 if (VT == MVT::f32)
12035 Res.second = X86::FR32RegisterClass;
12036 else if (VT == MVT::f64)
12037 Res.second = X86::FR64RegisterClass;
12038 else if (X86::VR128RegisterClass->hasType(VT))
12039 Res.second = X86::VR128RegisterClass;