1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "X86TargetObjectFile.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/VectorExtras.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/raw_ostream.h"
48 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
50 // Disable16Bit - 16-bit operations typically have a larger encoding than
51 // corresponding 32-bit instructions, and 16-bit code is slow on some
52 // processors. This is an experimental flag to disable 16-bit operations
53 // (which forces them to be Legalized to 32-bit operations).
55 Disable16Bit("disable-16bit", cl::Hidden,
56 cl::desc("Disable use of 16-bit instructions"));
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
63 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
64 default: llvm_unreachable("unknown subtarget type");
65 case X86Subtarget::isDarwin:
66 if (TM.getSubtarget<X86Subtarget>().is64Bit())
67 return new X8664_MachoTargetObjectFile();
68 return new X8632_MachoTargetObjectFile();
69 case X86Subtarget::isELF:
70 return new TargetLoweringObjectFileELF();
71 case X86Subtarget::isMingw:
72 case X86Subtarget::isCygwin:
73 case X86Subtarget::isWindows:
74 return new TargetLoweringObjectFileCOFF();
79 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
80 : TargetLowering(TM, createTLOF(TM)) {
81 Subtarget = &TM.getSubtarget<X86Subtarget>();
82 X86ScalarSSEf64 = Subtarget->hasSSE2();
83 X86ScalarSSEf32 = Subtarget->hasSSE1();
84 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
86 RegInfo = TM.getRegisterInfo();
89 // Set up the TargetLowering object.
91 // X86 is weird, it always uses i8 for shift amounts and setcc results.
92 setShiftAmountType(MVT::i8);
93 setBooleanContents(ZeroOrOneBooleanContent);
94 setSchedulingPreference(SchedulingForRegPressure);
95 setStackPointerRegisterToSaveRestore(X86StackPtr);
97 if (Subtarget->isTargetDarwin()) {
98 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
99 setUseUnderscoreSetJmp(false);
100 setUseUnderscoreLongJmp(false);
101 } else if (Subtarget->isTargetMingw()) {
102 // MS runtime is weird: it exports _setjmp, but longjmp!
103 setUseUnderscoreSetJmp(true);
104 setUseUnderscoreLongJmp(false);
106 setUseUnderscoreSetJmp(true);
107 setUseUnderscoreLongJmp(true);
110 // Set up the register classes.
111 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
113 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
114 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
115 if (Subtarget->is64Bit())
116 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
118 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
120 // We don't accept any truncstore of integer registers.
121 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
123 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
130 // SETOEQ and SETUNE require checking two conditions.
131 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
138 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
140 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
141 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
142 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
144 if (Subtarget->is64Bit()) {
145 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
146 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
147 } else if (!UseSoftFloat) {
148 if (X86ScalarSSEf64) {
149 // We have an impenetrably clever algorithm for ui64->double only.
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
152 // We have an algorithm for SSE2, and we turn this into a 64-bit
153 // FILD for other targets.
154 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
157 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
159 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
160 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
163 // SSE has no i16 to fp conversion, only i32
164 if (X86ScalarSSEf32) {
165 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
166 // f32 and f64 cases are Legal, f80 case is not
167 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
169 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
174 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
177 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
178 // are Legal, f80 is custom lowered.
179 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
182 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
184 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
185 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
187 if (X86ScalarSSEf32) {
188 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
189 // f32 and f64 cases are Legal, f80 case is not
190 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
192 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
193 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
196 // Handle FP_TO_UINT by promoting the destination to a larger signed
198 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
199 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
200 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
202 if (Subtarget->is64Bit()) {
203 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
204 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
205 } else if (!UseSoftFloat) {
206 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
207 // Expand FP_TO_UINT into a select.
208 // FIXME: We would like to use a Custom expander here eventually to do
209 // the optimal thing for SSE vs. the default expansion in the legalizer.
210 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
212 // With SSE3 we can use fisttpll to convert to a signed i64; without
213 // SSE, we're stuck with a fistpll.
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
217 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
218 if (!X86ScalarSSEf64) {
219 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
220 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
223 // Scalar integer divide and remainder are lowered to use operations that
224 // produce two results, to match the available instructions. This exposes
225 // the two-result form to trivial CSE, which is able to combine x/y and x%y
226 // into a single instruction.
228 // Scalar integer multiply-high is also lowered to use two-result
229 // operations, to match the available instructions. However, plain multiply
230 // (low) operations are left as Legal, as there are single-result
231 // instructions for this in x86. Using the two-result multiply instructions
232 // when both high and low results are needed must be arranged by dagcombine.
233 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
234 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
235 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
236 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
237 setOperationAction(ISD::SREM , MVT::i8 , Expand);
238 setOperationAction(ISD::UREM , MVT::i8 , Expand);
239 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
240 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
241 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
242 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
243 setOperationAction(ISD::SREM , MVT::i16 , Expand);
244 setOperationAction(ISD::UREM , MVT::i16 , Expand);
245 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
246 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
247 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
248 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
249 setOperationAction(ISD::SREM , MVT::i32 , Expand);
250 setOperationAction(ISD::UREM , MVT::i32 , Expand);
251 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
252 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
253 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
254 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
255 setOperationAction(ISD::SREM , MVT::i64 , Expand);
256 setOperationAction(ISD::UREM , MVT::i64 , Expand);
258 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
259 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
260 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
261 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
262 if (Subtarget->is64Bit())
263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
267 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
268 setOperationAction(ISD::FREM , MVT::f32 , Expand);
269 setOperationAction(ISD::FREM , MVT::f64 , Expand);
270 setOperationAction(ISD::FREM , MVT::f80 , Expand);
271 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
273 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
274 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
275 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
276 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
278 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
279 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
281 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
282 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
284 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
285 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
293 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
294 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
296 // These should be promoted to a larger select which is supported.
297 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
298 // X86 wants to expand cmov itself.
299 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
301 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
303 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
304 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
305 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
306 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
307 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
308 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
310 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
312 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
313 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
314 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
315 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
316 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
317 if (Subtarget->is64Bit()) {
318 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
319 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
321 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
324 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
325 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
326 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
327 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
328 if (Subtarget->is64Bit())
329 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
330 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
331 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
332 if (Subtarget->is64Bit()) {
333 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
334 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
335 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
336 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
337 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
339 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
340 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
341 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
342 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
343 if (Subtarget->is64Bit()) {
344 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
345 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
346 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
349 if (Subtarget->hasSSE1())
350 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
352 if (!Subtarget->hasSSE2())
353 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
355 // Expand certain atomics
356 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
359 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
361 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
362 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
364 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
366 if (!Subtarget->is64Bit()) {
367 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
368 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
369 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
376 // FIXME - use subtarget debug flags
377 if (!Subtarget->isTargetDarwin() &&
378 !Subtarget->isTargetELF() &&
379 !Subtarget->isTargetCygMing()) {
380 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
383 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
384 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
385 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
386 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
387 if (Subtarget->is64Bit()) {
388 setExceptionPointerRegister(X86::RAX);
389 setExceptionSelectorRegister(X86::RDX);
391 setExceptionPointerRegister(X86::EAX);
392 setExceptionSelectorRegister(X86::EDX);
394 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
395 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
397 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
399 setOperationAction(ISD::TRAP, MVT::Other, Legal);
401 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
402 setOperationAction(ISD::VASTART , MVT::Other, Custom);
403 setOperationAction(ISD::VAEND , MVT::Other, Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::VAARG , MVT::Other, Custom);
406 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
408 setOperationAction(ISD::VAARG , MVT::Other, Expand);
409 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
412 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
413 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
414 if (Subtarget->is64Bit())
415 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
416 if (Subtarget->isTargetCygMing())
417 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
421 if (!UseSoftFloat && X86ScalarSSEf64) {
422 // f32 and f64 use SSE.
423 // Set up the FP register classes.
424 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
425 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
427 // Use ANDPD to simulate FABS.
428 setOperationAction(ISD::FABS , MVT::f64, Custom);
429 setOperationAction(ISD::FABS , MVT::f32, Custom);
431 // Use XORP to simulate FNEG.
432 setOperationAction(ISD::FNEG , MVT::f64, Custom);
433 setOperationAction(ISD::FNEG , MVT::f32, Custom);
435 // Use ANDPD and ORPD to simulate FCOPYSIGN.
436 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439 // We don't support sin/cos/fmod
440 setOperationAction(ISD::FSIN , MVT::f64, Expand);
441 setOperationAction(ISD::FCOS , MVT::f64, Expand);
442 setOperationAction(ISD::FSIN , MVT::f32, Expand);
443 setOperationAction(ISD::FCOS , MVT::f32, Expand);
445 // Expand FP immediates into loads from the stack, except for the special
447 addLegalFPImmediate(APFloat(+0.0)); // xorpd
448 addLegalFPImmediate(APFloat(+0.0f)); // xorps
449 } else if (!UseSoftFloat && X86ScalarSSEf32) {
450 // Use SSE for f32, x87 for f64.
451 // Set up the FP register classes.
452 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
453 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
455 // Use ANDPS to simulate FABS.
456 setOperationAction(ISD::FABS , MVT::f32, Custom);
458 // Use XORP to simulate FNEG.
459 setOperationAction(ISD::FNEG , MVT::f32, Custom);
461 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
463 // Use ANDPS and ORPS to simulate FCOPYSIGN.
464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
467 // We don't support sin/cos/fmod
468 setOperationAction(ISD::FSIN , MVT::f32, Expand);
469 setOperationAction(ISD::FCOS , MVT::f32, Expand);
471 // Special cases we handle for FP constants.
472 addLegalFPImmediate(APFloat(+0.0f)); // xorps
473 addLegalFPImmediate(APFloat(+0.0)); // FLD0
474 addLegalFPImmediate(APFloat(+1.0)); // FLD1
475 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
476 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
479 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
480 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
482 } else if (!UseSoftFloat) {
483 // f32 and f64 in x87.
484 // Set up the FP register classes.
485 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
486 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
488 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
489 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
490 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
491 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
494 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
495 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
497 addLegalFPImmediate(APFloat(+0.0)); // FLD0
498 addLegalFPImmediate(APFloat(+1.0)); // FLD1
499 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
500 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
501 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
502 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
503 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
504 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
507 // Long double always uses X87.
509 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
510 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
511 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
514 APFloat TmpFlt(+0.0);
515 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
517 addLegalFPImmediate(TmpFlt); // FLD0
519 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
520 APFloat TmpFlt2(+1.0);
521 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
523 addLegalFPImmediate(TmpFlt2); // FLD1
524 TmpFlt2.changeSign();
525 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
529 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
530 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
534 // Always use a library call for pow.
535 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
536 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
537 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
539 setOperationAction(ISD::FLOG, MVT::f80, Expand);
540 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
541 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
542 setOperationAction(ISD::FEXP, MVT::f80, Expand);
543 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
545 // First set operation action for all vector types to either promote
546 // (for widening) or expand (for scalarization). Then we will selectively
547 // turn on ones that can be effectively codegen'd.
548 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
549 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
550 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
565 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
566 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
599 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
603 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
604 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
605 setTruncStoreAction((MVT::SimpleValueType)VT,
606 (MVT::SimpleValueType)InnerVT, Expand);
607 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
608 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
609 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
612 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
613 // with -msoft-float, disable use of MMX as well.
614 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
615 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
616 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
617 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
618 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
619 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
621 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
622 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
623 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
624 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
626 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
627 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
628 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
629 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
631 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
632 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
634 setOperationAction(ISD::AND, MVT::v8i8, Promote);
635 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
636 setOperationAction(ISD::AND, MVT::v4i16, Promote);
637 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
638 setOperationAction(ISD::AND, MVT::v2i32, Promote);
639 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
640 setOperationAction(ISD::AND, MVT::v1i64, Legal);
642 setOperationAction(ISD::OR, MVT::v8i8, Promote);
643 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
644 setOperationAction(ISD::OR, MVT::v4i16, Promote);
645 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
646 setOperationAction(ISD::OR, MVT::v2i32, Promote);
647 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
648 setOperationAction(ISD::OR, MVT::v1i64, Legal);
650 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
651 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
652 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
653 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
654 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
655 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
656 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
658 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
659 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
660 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
661 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
662 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
663 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
664 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
665 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
666 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
668 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
669 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
670 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
671 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
672 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
675 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
676 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
677 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
679 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
680 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
681 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
682 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
684 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
686 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
687 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
688 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
689 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
690 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
691 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
692 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
695 if (!UseSoftFloat && Subtarget->hasSSE1()) {
696 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
698 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
699 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
700 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
701 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
702 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
703 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
704 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
705 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
706 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
707 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
708 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
709 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
712 if (!UseSoftFloat && Subtarget->hasSSE2()) {
713 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
715 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
716 // registers cannot be used even for integer operations.
717 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
718 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
719 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
720 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
722 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
723 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
724 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
725 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
726 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
727 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
728 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
729 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
730 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
731 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
732 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
733 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
734 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
735 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
736 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
737 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
739 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
740 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
741 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
742 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
744 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
745 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
746 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
747 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
748 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
750 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
751 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
752 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
753 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
754 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
756 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
757 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
758 EVT VT = (MVT::SimpleValueType)i;
759 // Do not attempt to custom lower non-power-of-2 vectors
760 if (!isPowerOf2_32(VT.getVectorNumElements()))
762 // Do not attempt to custom lower non-128-bit vectors
763 if (!VT.is128BitVector())
765 setOperationAction(ISD::BUILD_VECTOR,
766 VT.getSimpleVT().SimpleTy, Custom);
767 setOperationAction(ISD::VECTOR_SHUFFLE,
768 VT.getSimpleVT().SimpleTy, Custom);
769 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
770 VT.getSimpleVT().SimpleTy, Custom);
773 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
774 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
775 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
778 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
780 if (Subtarget->is64Bit()) {
781 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
782 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
785 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
786 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
787 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
790 // Do not attempt to promote non-128-bit vectors
791 if (!VT.is128BitVector()) {
794 setOperationAction(ISD::AND, SVT, Promote);
795 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
796 setOperationAction(ISD::OR, SVT, Promote);
797 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
798 setOperationAction(ISD::XOR, SVT, Promote);
799 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
800 setOperationAction(ISD::LOAD, SVT, Promote);
801 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
802 setOperationAction(ISD::SELECT, SVT, Promote);
803 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
806 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
808 // Custom lower v2i64 and v2f64 selects.
809 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
810 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
811 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
812 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
814 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
815 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
816 if (!DisableMMX && Subtarget->hasMMX()) {
817 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
818 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
822 if (Subtarget->hasSSE41()) {
823 // FIXME: Do we need to handle scalar-to-vector here?
824 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
826 // i8 and i16 vectors are custom , because the source register and source
827 // source memory operand types are not the same width. f32 vectors are
828 // custom since the immediate controlling the insert encodes additional
830 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
835 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
836 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
837 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
840 if (Subtarget->is64Bit()) {
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
842 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
846 if (Subtarget->hasSSE42()) {
847 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
850 if (!UseSoftFloat && Subtarget->hasAVX()) {
851 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
852 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
853 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
854 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
856 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
857 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
858 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
859 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
860 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
861 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
862 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
863 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
864 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
865 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
866 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
867 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
868 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
869 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
870 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
872 // Operations to consider commented out -v16i16 v32i8
873 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
874 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
875 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
876 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
877 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
878 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
879 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
880 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
881 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
882 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
883 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
884 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
885 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
886 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
888 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
889 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
890 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
891 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
893 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
894 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
895 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
899 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
900 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
901 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
902 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
903 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
904 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
907 // Not sure we want to do this since there are no 256-bit integer
910 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
911 // This includes 256-bit vectors
912 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
913 EVT VT = (MVT::SimpleValueType)i;
915 // Do not attempt to custom lower non-power-of-2 vectors
916 if (!isPowerOf2_32(VT.getVectorNumElements()))
919 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
920 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
924 if (Subtarget->is64Bit()) {
925 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
926 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
931 // Not sure we want to do this since there are no 256-bit integer
934 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
935 // Including 256-bit vectors
936 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
937 EVT VT = (MVT::SimpleValueType)i;
939 if (!VT.is256BitVector()) {
942 setOperationAction(ISD::AND, VT, Promote);
943 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
944 setOperationAction(ISD::OR, VT, Promote);
945 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
946 setOperationAction(ISD::XOR, VT, Promote);
947 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
948 setOperationAction(ISD::LOAD, VT, Promote);
949 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
950 setOperationAction(ISD::SELECT, VT, Promote);
951 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
954 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
958 // We want to custom lower some of our intrinsics.
959 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
961 // Add/Sub/Mul with overflow operations are custom lowered.
962 setOperationAction(ISD::SADDO, MVT::i32, Custom);
963 setOperationAction(ISD::SADDO, MVT::i64, Custom);
964 setOperationAction(ISD::UADDO, MVT::i32, Custom);
965 setOperationAction(ISD::UADDO, MVT::i64, Custom);
966 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
967 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
968 setOperationAction(ISD::USUBO, MVT::i32, Custom);
969 setOperationAction(ISD::USUBO, MVT::i64, Custom);
970 setOperationAction(ISD::SMULO, MVT::i32, Custom);
971 setOperationAction(ISD::SMULO, MVT::i64, Custom);
973 if (!Subtarget->is64Bit()) {
974 // These libcalls are not available in 32-bit.
975 setLibcallName(RTLIB::SHL_I128, 0);
976 setLibcallName(RTLIB::SRL_I128, 0);
977 setLibcallName(RTLIB::SRA_I128, 0);
980 // We have target-specific dag combine patterns for the following nodes:
981 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
982 setTargetDAGCombine(ISD::BUILD_VECTOR);
983 setTargetDAGCombine(ISD::SELECT);
984 setTargetDAGCombine(ISD::SHL);
985 setTargetDAGCombine(ISD::SRA);
986 setTargetDAGCombine(ISD::SRL);
987 setTargetDAGCombine(ISD::OR);
988 setTargetDAGCombine(ISD::STORE);
989 setTargetDAGCombine(ISD::MEMBARRIER);
990 setTargetDAGCombine(ISD::ZERO_EXTEND);
991 if (Subtarget->is64Bit())
992 setTargetDAGCombine(ISD::MUL);
994 computeRegisterProperties();
996 // Divide and reminder operations have no vector equivalent and can
997 // trap. Do a custom widening for these operations in which we never
998 // generate more divides/remainder than the original vector width.
999 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1000 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
1001 if (!isTypeLegal((MVT::SimpleValueType)VT)) {
1002 setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
1003 setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
1004 setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
1005 setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
1009 // FIXME: These should be based on subtarget info. Plus, the values should
1010 // be smaller when we are in optimizing for size mode.
1011 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1012 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1013 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1014 setPrefLoopAlignment(16);
1015 benefitFromCodePlacementOpt = true;
1019 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1024 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1025 /// the desired ByVal argument alignment.
1026 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1029 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1030 if (VTy->getBitWidth() == 128)
1032 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1033 unsigned EltAlign = 0;
1034 getMaxByValAlign(ATy->getElementType(), EltAlign);
1035 if (EltAlign > MaxAlign)
1036 MaxAlign = EltAlign;
1037 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1038 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1039 unsigned EltAlign = 0;
1040 getMaxByValAlign(STy->getElementType(i), EltAlign);
1041 if (EltAlign > MaxAlign)
1042 MaxAlign = EltAlign;
1050 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1051 /// function arguments in the caller parameter area. For X86, aggregates
1052 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1053 /// are at 4-byte boundaries.
1054 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1055 if (Subtarget->is64Bit()) {
1056 // Max of 8 and alignment of type.
1057 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1064 if (Subtarget->hasSSE1())
1065 getMaxByValAlign(Ty, Align);
1069 /// getOptimalMemOpType - Returns the target specific optimal type for load
1070 /// and store operations as a result of memset, memcpy, and memmove
1071 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1074 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1075 bool isSrcConst, bool isSrcStr,
1076 SelectionDAG &DAG) const {
1077 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1078 // linux. This is because the stack realignment code can't handle certain
1079 // cases like PR2962. This should be removed when PR2962 is fixed.
1080 const Function *F = DAG.getMachineFunction().getFunction();
1081 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1082 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1083 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1085 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1088 if (Subtarget->is64Bit() && Size >= 8)
1093 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1095 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1096 SelectionDAG &DAG) const {
1097 if (usesGlobalOffsetTable())
1098 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1099 if (!Subtarget->is64Bit())
1100 // This doesn't have DebugLoc associated with it, but is not really the
1101 // same as a Register.
1102 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1107 /// getFunctionAlignment - Return the Log2 alignment of this function.
1108 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1109 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1112 //===----------------------------------------------------------------------===//
1113 // Return Value Calling Convention Implementation
1114 //===----------------------------------------------------------------------===//
1116 #include "X86GenCallingConv.inc"
1119 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1120 const SmallVectorImpl<EVT> &OutTys,
1121 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1122 SelectionDAG &DAG) {
1123 SmallVector<CCValAssign, 16> RVLocs;
1124 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1125 RVLocs, *DAG.getContext());
1126 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1130 X86TargetLowering::LowerReturn(SDValue Chain,
1131 CallingConv::ID CallConv, bool isVarArg,
1132 const SmallVectorImpl<ISD::OutputArg> &Outs,
1133 DebugLoc dl, SelectionDAG &DAG) {
1135 SmallVector<CCValAssign, 16> RVLocs;
1136 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1137 RVLocs, *DAG.getContext());
1138 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1140 // If this is the first return lowered for this function, add the regs to the
1141 // liveout set for the function.
1142 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1143 for (unsigned i = 0; i != RVLocs.size(); ++i)
1144 if (RVLocs[i].isRegLoc())
1145 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1150 SmallVector<SDValue, 6> RetOps;
1151 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1152 // Operand #1 = Bytes To Pop
1153 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1155 // Copy the result values into the output registers.
1156 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1157 CCValAssign &VA = RVLocs[i];
1158 assert(VA.isRegLoc() && "Can only return in registers!");
1159 SDValue ValToCopy = Outs[i].Val;
1161 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1162 // the RET instruction and handled by the FP Stackifier.
1163 if (VA.getLocReg() == X86::ST0 ||
1164 VA.getLocReg() == X86::ST1) {
1165 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1166 // change the value to the FP stack register class.
1167 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1168 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1169 RetOps.push_back(ValToCopy);
1170 // Don't emit a copytoreg.
1174 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1175 // which is returned in RAX / RDX.
1176 if (Subtarget->is64Bit()) {
1177 EVT ValVT = ValToCopy.getValueType();
1178 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1179 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1180 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1181 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1185 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1186 Flag = Chain.getValue(1);
1189 // The x86-64 ABI for returning structs by value requires that we copy
1190 // the sret argument into %rax for the return. We saved the argument into
1191 // a virtual register in the entry block, so now we copy the value out
1193 if (Subtarget->is64Bit() &&
1194 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1195 MachineFunction &MF = DAG.getMachineFunction();
1196 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1197 unsigned Reg = FuncInfo->getSRetReturnReg();
1199 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1200 FuncInfo->setSRetReturnReg(Reg);
1202 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1204 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1205 Flag = Chain.getValue(1);
1207 // RAX now acts like a return value.
1208 MF.getRegInfo().addLiveOut(X86::RAX);
1211 RetOps[0] = Chain; // Update chain.
1213 // Add the flag if we have it.
1215 RetOps.push_back(Flag);
1217 return DAG.getNode(X86ISD::RET_FLAG, dl,
1218 MVT::Other, &RetOps[0], RetOps.size());
1221 /// LowerCallResult - Lower the result values of a call into the
1222 /// appropriate copies out of appropriate physical registers.
1225 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1226 CallingConv::ID CallConv, bool isVarArg,
1227 const SmallVectorImpl<ISD::InputArg> &Ins,
1228 DebugLoc dl, SelectionDAG &DAG,
1229 SmallVectorImpl<SDValue> &InVals) {
1231 // Assign locations to each value returned by this call.
1232 SmallVector<CCValAssign, 16> RVLocs;
1233 bool Is64Bit = Subtarget->is64Bit();
1234 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1235 RVLocs, *DAG.getContext());
1236 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1238 // Copy all of the result registers out of their specified physreg.
1239 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1240 CCValAssign &VA = RVLocs[i];
1241 EVT CopyVT = VA.getValVT();
1243 // If this is x86-64, and we disabled SSE, we can't return FP values
1244 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1245 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1246 llvm_report_error("SSE register return with SSE disabled");
1249 // If this is a call to a function that returns an fp value on the floating
1250 // point stack, but where we prefer to use the value in xmm registers, copy
1251 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1252 if ((VA.getLocReg() == X86::ST0 ||
1253 VA.getLocReg() == X86::ST1) &&
1254 isScalarFPTypeInSSEReg(VA.getValVT())) {
1259 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1260 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1261 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1262 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1263 MVT::v2i64, InFlag).getValue(1);
1264 Val = Chain.getValue(0);
1265 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1266 Val, DAG.getConstant(0, MVT::i64));
1268 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1269 MVT::i64, InFlag).getValue(1);
1270 Val = Chain.getValue(0);
1272 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1274 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1275 CopyVT, InFlag).getValue(1);
1276 Val = Chain.getValue(0);
1278 InFlag = Chain.getValue(2);
1280 if (CopyVT != VA.getValVT()) {
1281 // Round the F80 the right size, which also moves to the appropriate xmm
1283 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1284 // This truncation won't change the value.
1285 DAG.getIntPtrConstant(1));
1288 InVals.push_back(Val);
1295 //===----------------------------------------------------------------------===//
1296 // C & StdCall & Fast Calling Convention implementation
1297 //===----------------------------------------------------------------------===//
1298 // StdCall calling convention seems to be standard for many Windows' API
1299 // routines and around. It differs from C calling convention just a little:
1300 // callee should clean up the stack, not caller. Symbols should be also
1301 // decorated in some fancy way :) It doesn't support any vector arguments.
1302 // For info on fast calling convention see Fast Calling Convention (tail call)
1303 // implementation LowerX86_32FastCCCallTo.
1305 /// CallIsStructReturn - Determines whether a call uses struct return
1307 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1311 return Outs[0].Flags.isSRet();
1314 /// ArgsAreStructReturn - Determines whether a function uses struct
1315 /// return semantics.
1317 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1321 return Ins[0].Flags.isSRet();
1324 /// IsCalleePop - Determines whether the callee is required to pop its
1325 /// own arguments. Callee pop is necessary to support tail calls.
1326 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1330 switch (CallingConv) {
1333 case CallingConv::X86_StdCall:
1334 return !Subtarget->is64Bit();
1335 case CallingConv::X86_FastCall:
1336 return !Subtarget->is64Bit();
1337 case CallingConv::Fast:
1338 return PerformTailCallOpt;
1342 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1343 /// given CallingConvention value.
1344 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1345 if (Subtarget->is64Bit()) {
1346 if (Subtarget->isTargetWin64())
1347 return CC_X86_Win64_C;
1352 if (CC == CallingConv::X86_FastCall)
1353 return CC_X86_32_FastCall;
1354 else if (CC == CallingConv::Fast)
1355 return CC_X86_32_FastCC;
1360 /// NameDecorationForCallConv - Selects the appropriate decoration to
1361 /// apply to a MachineFunction containing a given calling convention.
1363 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1364 if (CallConv == CallingConv::X86_FastCall)
1366 else if (CallConv == CallingConv::X86_StdCall)
1372 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1373 /// by "Src" to address "Dst" with size and alignment information specified by
1374 /// the specific parameter attribute. The copy will be passed as a byval
1375 /// function parameter.
1377 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1378 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1380 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1381 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1382 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1386 X86TargetLowering::LowerMemArgument(SDValue Chain,
1387 CallingConv::ID CallConv,
1388 const SmallVectorImpl<ISD::InputArg> &Ins,
1389 DebugLoc dl, SelectionDAG &DAG,
1390 const CCValAssign &VA,
1391 MachineFrameInfo *MFI,
1394 // Create the nodes corresponding to a load from this parameter slot.
1395 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1396 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1397 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1400 // If value is passed by pointer we have address passed instead of the value
1402 if (VA.getLocInfo() == CCValAssign::Indirect)
1403 ValVT = VA.getLocVT();
1405 ValVT = VA.getValVT();
1407 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1408 // changed with more analysis.
1409 // In case of tail call optimization mark all arguments mutable. Since they
1410 // could be overwritten by lowering of arguments in case of a tail call.
1411 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1412 VA.getLocMemOffset(), isImmutable, false);
1413 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1414 if (Flags.isByVal())
1416 return DAG.getLoad(ValVT, dl, Chain, FIN,
1417 PseudoSourceValue::getFixedStack(FI), 0);
1421 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1422 CallingConv::ID CallConv,
1424 const SmallVectorImpl<ISD::InputArg> &Ins,
1427 SmallVectorImpl<SDValue> &InVals) {
1429 MachineFunction &MF = DAG.getMachineFunction();
1430 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1432 const Function* Fn = MF.getFunction();
1433 if (Fn->hasExternalLinkage() &&
1434 Subtarget->isTargetCygMing() &&
1435 Fn->getName() == "main")
1436 FuncInfo->setForceFramePointer(true);
1438 // Decorate the function name.
1439 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1441 MachineFrameInfo *MFI = MF.getFrameInfo();
1442 bool Is64Bit = Subtarget->is64Bit();
1443 bool IsWin64 = Subtarget->isTargetWin64();
1445 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1446 "Var args not supported with calling convention fastcc");
1448 // Assign locations to all of the incoming arguments.
1449 SmallVector<CCValAssign, 16> ArgLocs;
1450 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1451 ArgLocs, *DAG.getContext());
1452 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1454 unsigned LastVal = ~0U;
1456 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1457 CCValAssign &VA = ArgLocs[i];
1458 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1460 assert(VA.getValNo() != LastVal &&
1461 "Don't support value assigned to multiple locs yet");
1462 LastVal = VA.getValNo();
1464 if (VA.isRegLoc()) {
1465 EVT RegVT = VA.getLocVT();
1466 TargetRegisterClass *RC = NULL;
1467 if (RegVT == MVT::i32)
1468 RC = X86::GR32RegisterClass;
1469 else if (Is64Bit && RegVT == MVT::i64)
1470 RC = X86::GR64RegisterClass;
1471 else if (RegVT == MVT::f32)
1472 RC = X86::FR32RegisterClass;
1473 else if (RegVT == MVT::f64)
1474 RC = X86::FR64RegisterClass;
1475 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1476 RC = X86::VR128RegisterClass;
1477 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1478 RC = X86::VR64RegisterClass;
1480 llvm_unreachable("Unknown argument type!");
1482 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1483 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1485 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1486 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1488 if (VA.getLocInfo() == CCValAssign::SExt)
1489 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1490 DAG.getValueType(VA.getValVT()));
1491 else if (VA.getLocInfo() == CCValAssign::ZExt)
1492 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1493 DAG.getValueType(VA.getValVT()));
1494 else if (VA.getLocInfo() == CCValAssign::BCvt)
1495 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1497 if (VA.isExtInLoc()) {
1498 // Handle MMX values passed in XMM regs.
1499 if (RegVT.isVector()) {
1500 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1501 ArgValue, DAG.getConstant(0, MVT::i64));
1502 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1504 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1507 assert(VA.isMemLoc());
1508 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1511 // If value is passed via pointer - do a load.
1512 if (VA.getLocInfo() == CCValAssign::Indirect)
1513 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1515 InVals.push_back(ArgValue);
1518 // The x86-64 ABI for returning structs by value requires that we copy
1519 // the sret argument into %rax for the return. Save the argument into
1520 // a virtual register so that we can access it from the return points.
1521 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1522 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1523 unsigned Reg = FuncInfo->getSRetReturnReg();
1525 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1526 FuncInfo->setSRetReturnReg(Reg);
1528 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1529 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1532 unsigned StackSize = CCInfo.getNextStackOffset();
1533 // align stack specially for tail calls
1534 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1535 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1537 // If the function takes variable number of arguments, make a frame index for
1538 // the start of the first vararg value... for expansion of llvm.va_start.
1540 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1541 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1544 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1546 // FIXME: We should really autogenerate these arrays
1547 static const unsigned GPR64ArgRegsWin64[] = {
1548 X86::RCX, X86::RDX, X86::R8, X86::R9
1550 static const unsigned XMMArgRegsWin64[] = {
1551 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1553 static const unsigned GPR64ArgRegs64Bit[] = {
1554 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1556 static const unsigned XMMArgRegs64Bit[] = {
1557 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1558 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1560 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1563 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1564 GPR64ArgRegs = GPR64ArgRegsWin64;
1565 XMMArgRegs = XMMArgRegsWin64;
1567 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1568 GPR64ArgRegs = GPR64ArgRegs64Bit;
1569 XMMArgRegs = XMMArgRegs64Bit;
1571 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1573 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1576 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1577 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1578 "SSE register cannot be used when SSE is disabled!");
1579 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1580 "SSE register cannot be used when SSE is disabled!");
1581 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1582 // Kernel mode asks for SSE to be disabled, so don't push them
1584 TotalNumXMMRegs = 0;
1586 // For X86-64, if there are vararg parameters that are passed via
1587 // registers, then we must store them to their spots on the stack so they
1588 // may be loaded by deferencing the result of va_next.
1589 VarArgsGPOffset = NumIntRegs * 8;
1590 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1591 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1592 TotalNumXMMRegs * 16, 16,
1595 // Store the integer parameter registers.
1596 SmallVector<SDValue, 8> MemOps;
1597 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1598 unsigned Offset = VarArgsGPOffset;
1599 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1600 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1601 DAG.getIntPtrConstant(Offset));
1602 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1603 X86::GR64RegisterClass);
1604 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1606 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1607 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1609 MemOps.push_back(Store);
1613 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1614 // Now store the XMM (fp + vector) parameter registers.
1615 SmallVector<SDValue, 11> SaveXMMOps;
1616 SaveXMMOps.push_back(Chain);
1618 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1619 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1620 SaveXMMOps.push_back(ALVal);
1622 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1623 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1625 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1626 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1627 X86::VR128RegisterClass);
1628 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1629 SaveXMMOps.push_back(Val);
1631 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1633 &SaveXMMOps[0], SaveXMMOps.size()));
1636 if (!MemOps.empty())
1637 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1638 &MemOps[0], MemOps.size());
1642 // Some CCs need callee pop.
1643 if (IsCalleePop(isVarArg, CallConv)) {
1644 BytesToPopOnReturn = StackSize; // Callee pops everything.
1645 BytesCallerReserves = 0;
1647 BytesToPopOnReturn = 0; // Callee pops nothing.
1648 // If this is an sret function, the return should pop the hidden pointer.
1649 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1650 BytesToPopOnReturn = 4;
1651 BytesCallerReserves = StackSize;
1655 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1656 if (CallConv == CallingConv::X86_FastCall)
1657 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1660 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1666 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1667 SDValue StackPtr, SDValue Arg,
1668 DebugLoc dl, SelectionDAG &DAG,
1669 const CCValAssign &VA,
1670 ISD::ArgFlagsTy Flags) {
1671 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1672 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1673 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1674 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1675 if (Flags.isByVal()) {
1676 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1678 return DAG.getStore(Chain, dl, Arg, PtrOff,
1679 PseudoSourceValue::getStack(), LocMemOffset);
1682 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1683 /// optimization is performed and it is required.
1685 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1686 SDValue &OutRetAddr,
1692 if (!IsTailCall || FPDiff==0) return Chain;
1694 // Adjust the Return address stack slot.
1695 EVT VT = getPointerTy();
1696 OutRetAddr = getReturnAddressFrameIndex(DAG);
1698 // Load the "old" Return address.
1699 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1700 return SDValue(OutRetAddr.getNode(), 1);
1703 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1704 /// optimization is performed and it is required (FPDiff!=0).
1706 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1707 SDValue Chain, SDValue RetAddrFrIdx,
1708 bool Is64Bit, int FPDiff, DebugLoc dl) {
1709 // Store the return address to the appropriate stack slot.
1710 if (!FPDiff) return Chain;
1711 // Calculate the new stack slot for the return address.
1712 int SlotSize = Is64Bit ? 8 : 4;
1713 int NewReturnAddrFI =
1714 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize,
1716 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1717 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1718 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1719 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1724 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1725 CallingConv::ID CallConv, bool isVarArg,
1727 const SmallVectorImpl<ISD::OutputArg> &Outs,
1728 const SmallVectorImpl<ISD::InputArg> &Ins,
1729 DebugLoc dl, SelectionDAG &DAG,
1730 SmallVectorImpl<SDValue> &InVals) {
1732 MachineFunction &MF = DAG.getMachineFunction();
1733 bool Is64Bit = Subtarget->is64Bit();
1734 bool IsStructRet = CallIsStructReturn(Outs);
1736 assert((!isTailCall ||
1737 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1738 "IsEligibleForTailCallOptimization missed a case!");
1739 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1740 "Var args not supported with calling convention fastcc");
1742 // Analyze operands of the call, assigning locations to each operand.
1743 SmallVector<CCValAssign, 16> ArgLocs;
1744 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1745 ArgLocs, *DAG.getContext());
1746 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1748 // Get a count of how many bytes are to be pushed on the stack.
1749 unsigned NumBytes = CCInfo.getNextStackOffset();
1750 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1751 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1755 // Lower arguments at fp - stackoffset + fpdiff.
1756 unsigned NumBytesCallerPushed =
1757 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1758 FPDiff = NumBytesCallerPushed - NumBytes;
1760 // Set the delta of movement of the returnaddr stackslot.
1761 // But only set if delta is greater than previous delta.
1762 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1763 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1766 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1768 SDValue RetAddrFrIdx;
1769 // Load return adress for tail calls.
1770 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1773 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1774 SmallVector<SDValue, 8> MemOpChains;
1777 // Walk the register/memloc assignments, inserting copies/loads. In the case
1778 // of tail call optimization arguments are handle later.
1779 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1780 CCValAssign &VA = ArgLocs[i];
1781 EVT RegVT = VA.getLocVT();
1782 SDValue Arg = Outs[i].Val;
1783 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1784 bool isByVal = Flags.isByVal();
1786 // Promote the value if needed.
1787 switch (VA.getLocInfo()) {
1788 default: llvm_unreachable("Unknown loc info!");
1789 case CCValAssign::Full: break;
1790 case CCValAssign::SExt:
1791 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1793 case CCValAssign::ZExt:
1794 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1796 case CCValAssign::AExt:
1797 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1798 // Special case: passing MMX values in XMM registers.
1799 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1800 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1801 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1803 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1805 case CCValAssign::BCvt:
1806 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1808 case CCValAssign::Indirect: {
1809 // Store the argument.
1810 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1811 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1812 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1813 PseudoSourceValue::getFixedStack(FI), 0);
1819 if (VA.isRegLoc()) {
1820 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1822 if (!isTailCall || (isTailCall && isByVal)) {
1823 assert(VA.isMemLoc());
1824 if (StackPtr.getNode() == 0)
1825 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1827 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1828 dl, DAG, VA, Flags));
1833 if (!MemOpChains.empty())
1834 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1835 &MemOpChains[0], MemOpChains.size());
1837 // Build a sequence of copy-to-reg nodes chained together with token chain
1838 // and flag operands which copy the outgoing args into registers.
1840 // Tail call byval lowering might overwrite argument registers so in case of
1841 // tail call optimization the copies to registers are lowered later.
1843 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1844 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1845 RegsToPass[i].second, InFlag);
1846 InFlag = Chain.getValue(1);
1850 if (Subtarget->isPICStyleGOT()) {
1851 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1854 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1855 DAG.getNode(X86ISD::GlobalBaseReg,
1856 DebugLoc::getUnknownLoc(),
1859 InFlag = Chain.getValue(1);
1861 // If we are tail calling and generating PIC/GOT style code load the
1862 // address of the callee into ECX. The value in ecx is used as target of
1863 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1864 // for tail calls on PIC/GOT architectures. Normally we would just put the
1865 // address of GOT into ebx and then call target@PLT. But for tail calls
1866 // ebx would be restored (since ebx is callee saved) before jumping to the
1869 // Note: The actual moving to ECX is done further down.
1870 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1871 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1872 !G->getGlobal()->hasProtectedVisibility())
1873 Callee = LowerGlobalAddress(Callee, DAG);
1874 else if (isa<ExternalSymbolSDNode>(Callee))
1875 Callee = LowerExternalSymbol(Callee, DAG);
1879 if (Is64Bit && isVarArg) {
1880 // From AMD64 ABI document:
1881 // For calls that may call functions that use varargs or stdargs
1882 // (prototype-less calls or calls to functions containing ellipsis (...) in
1883 // the declaration) %al is used as hidden argument to specify the number
1884 // of SSE registers used. The contents of %al do not need to match exactly
1885 // the number of registers, but must be an ubound on the number of SSE
1886 // registers used and is in the range 0 - 8 inclusive.
1888 // FIXME: Verify this on Win64
1889 // Count the number of XMM registers allocated.
1890 static const unsigned XMMArgRegs[] = {
1891 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1892 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1894 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1895 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1896 && "SSE registers cannot be used when SSE is disabled");
1898 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1899 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1900 InFlag = Chain.getValue(1);
1904 // For tail calls lower the arguments to the 'real' stack slot.
1906 // Force all the incoming stack arguments to be loaded from the stack
1907 // before any new outgoing arguments are stored to the stack, because the
1908 // outgoing stack slots may alias the incoming argument stack slots, and
1909 // the alias isn't otherwise explicit. This is slightly more conservative
1910 // than necessary, because it means that each store effectively depends
1911 // on every argument instead of just those arguments it would clobber.
1912 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1914 SmallVector<SDValue, 8> MemOpChains2;
1917 // Do not flag preceeding copytoreg stuff together with the following stuff.
1919 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1920 CCValAssign &VA = ArgLocs[i];
1921 if (!VA.isRegLoc()) {
1922 assert(VA.isMemLoc());
1923 SDValue Arg = Outs[i].Val;
1924 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1925 // Create frame index.
1926 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1927 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1928 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1929 FIN = DAG.getFrameIndex(FI, getPointerTy());
1931 if (Flags.isByVal()) {
1932 // Copy relative to framepointer.
1933 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1934 if (StackPtr.getNode() == 0)
1935 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1937 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1939 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1943 // Store relative to framepointer.
1944 MemOpChains2.push_back(
1945 DAG.getStore(ArgChain, dl, Arg, FIN,
1946 PseudoSourceValue::getFixedStack(FI), 0));
1951 if (!MemOpChains2.empty())
1952 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1953 &MemOpChains2[0], MemOpChains2.size());
1955 // Copy arguments to their registers.
1956 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1957 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1958 RegsToPass[i].second, InFlag);
1959 InFlag = Chain.getValue(1);
1963 // Store the return address to the appropriate stack slot.
1964 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1968 bool WasGlobalOrExternal = false;
1969 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
1970 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
1971 // In the 64-bit large code model, we have to make all calls
1972 // through a register, since the call instruction's 32-bit
1973 // pc-relative offset may not be large enough to hold the whole
1975 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1976 WasGlobalOrExternal = true;
1977 // If the callee is a GlobalAddress node (quite common, every direct call
1978 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
1981 // We should use extra load for direct calls to dllimported functions in
1983 GlobalValue *GV = G->getGlobal();
1984 if (!GV->hasDLLImportLinkage()) {
1985 unsigned char OpFlags = 0;
1987 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1988 // external symbols most go through the PLT in PIC mode. If the symbol
1989 // has hidden or protected visibility, or if it is static or local, then
1990 // we don't need to use the PLT - we can directly call it.
1991 if (Subtarget->isTargetELF() &&
1992 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1993 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1994 OpFlags = X86II::MO_PLT;
1995 } else if (Subtarget->isPICStyleStubAny() &&
1996 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1997 Subtarget->getDarwinVers() < 9) {
1998 // PC-relative references to external symbols should go through $stub,
1999 // unless we're building with the leopard linker or later, which
2000 // automatically synthesizes these stubs.
2001 OpFlags = X86II::MO_DARWIN_STUB;
2004 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2005 G->getOffset(), OpFlags);
2007 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2008 WasGlobalOrExternal = true;
2009 unsigned char OpFlags = 0;
2011 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2012 // symbols should go through the PLT.
2013 if (Subtarget->isTargetELF() &&
2014 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2015 OpFlags = X86II::MO_PLT;
2016 } else if (Subtarget->isPICStyleStubAny() &&
2017 Subtarget->getDarwinVers() < 9) {
2018 // PC-relative references to external symbols should go through $stub,
2019 // unless we're building with the leopard linker or later, which
2020 // automatically synthesizes these stubs.
2021 OpFlags = X86II::MO_DARWIN_STUB;
2024 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2028 if (isTailCall && !WasGlobalOrExternal) {
2029 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2031 Chain = DAG.getCopyToReg(Chain, dl,
2032 DAG.getRegister(Opc, getPointerTy()),
2034 Callee = DAG.getRegister(Opc, getPointerTy());
2035 // Add register as live out.
2036 MF.getRegInfo().addLiveOut(Opc);
2039 // Returns a chain & a flag for retval copy to use.
2040 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2041 SmallVector<SDValue, 8> Ops;
2044 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2045 DAG.getIntPtrConstant(0, true), InFlag);
2046 InFlag = Chain.getValue(1);
2049 Ops.push_back(Chain);
2050 Ops.push_back(Callee);
2053 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2055 // Add argument registers to the end of the list so that they are known live
2057 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2058 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2059 RegsToPass[i].second.getValueType()));
2061 // Add an implicit use GOT pointer in EBX.
2062 if (!isTailCall && Subtarget->isPICStyleGOT())
2063 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2065 // Add an implicit use of AL for x86 vararg functions.
2066 if (Is64Bit && isVarArg)
2067 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2069 if (InFlag.getNode())
2070 Ops.push_back(InFlag);
2073 // If this is the first return lowered for this function, add the regs
2074 // to the liveout set for the function.
2075 if (MF.getRegInfo().liveout_empty()) {
2076 SmallVector<CCValAssign, 16> RVLocs;
2077 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2079 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2080 for (unsigned i = 0; i != RVLocs.size(); ++i)
2081 if (RVLocs[i].isRegLoc())
2082 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2085 assert(((Callee.getOpcode() == ISD::Register &&
2086 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2087 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2088 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2089 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2090 "Expecting a global address, external symbol, or scratch register");
2092 return DAG.getNode(X86ISD::TC_RETURN, dl,
2093 NodeTys, &Ops[0], Ops.size());
2096 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2097 InFlag = Chain.getValue(1);
2099 // Create the CALLSEQ_END node.
2100 unsigned NumBytesForCalleeToPush;
2101 if (IsCalleePop(isVarArg, CallConv))
2102 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2103 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2104 // If this is is a call to a struct-return function, the callee
2105 // pops the hidden struct pointer, so we have to push it back.
2106 // This is common for Darwin/X86, Linux & Mingw32 targets.
2107 NumBytesForCalleeToPush = 4;
2109 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2111 // Returns a flag for retval copy to use.
2112 Chain = DAG.getCALLSEQ_END(Chain,
2113 DAG.getIntPtrConstant(NumBytes, true),
2114 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2117 InFlag = Chain.getValue(1);
2119 // Handle result values, copying them out of physregs into vregs that we
2121 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2122 Ins, dl, DAG, InVals);
2126 //===----------------------------------------------------------------------===//
2127 // Fast Calling Convention (tail call) implementation
2128 //===----------------------------------------------------------------------===//
2130 // Like std call, callee cleans arguments, convention except that ECX is
2131 // reserved for storing the tail called function address. Only 2 registers are
2132 // free for argument passing (inreg). Tail call optimization is performed
2134 // * tailcallopt is enabled
2135 // * caller/callee are fastcc
2136 // On X86_64 architecture with GOT-style position independent code only local
2137 // (within module) calls are supported at the moment.
2138 // To keep the stack aligned according to platform abi the function
2139 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2140 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2141 // If a tail called function callee has more arguments than the caller the
2142 // caller needs to make sure that there is room to move the RETADDR to. This is
2143 // achieved by reserving an area the size of the argument delta right after the
2144 // original REtADDR, but before the saved framepointer or the spilled registers
2145 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2157 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2158 /// for a 16 byte align requirement.
2159 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2160 SelectionDAG& DAG) {
2161 MachineFunction &MF = DAG.getMachineFunction();
2162 const TargetMachine &TM = MF.getTarget();
2163 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2164 unsigned StackAlignment = TFI.getStackAlignment();
2165 uint64_t AlignMask = StackAlignment - 1;
2166 int64_t Offset = StackSize;
2167 uint64_t SlotSize = TD->getPointerSize();
2168 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2169 // Number smaller than 12 so just add the difference.
2170 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2172 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2173 Offset = ((~AlignMask) & Offset) + StackAlignment +
2174 (StackAlignment-SlotSize);
2179 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2180 /// for tail call optimization. Targets which want to do tail call
2181 /// optimization should implement this function.
2183 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2184 CallingConv::ID CalleeCC,
2186 const SmallVectorImpl<ISD::InputArg> &Ins,
2187 SelectionDAG& DAG) const {
2188 MachineFunction &MF = DAG.getMachineFunction();
2189 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2190 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2194 X86TargetLowering::createFastISel(MachineFunction &mf,
2195 MachineModuleInfo *mmo,
2197 DenseMap<const Value *, unsigned> &vm,
2198 DenseMap<const BasicBlock *,
2199 MachineBasicBlock *> &bm,
2200 DenseMap<const AllocaInst *, int> &am
2202 , SmallSet<Instruction*, 8> &cil
2205 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2213 //===----------------------------------------------------------------------===//
2214 // Other Lowering Hooks
2215 //===----------------------------------------------------------------------===//
2218 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2219 MachineFunction &MF = DAG.getMachineFunction();
2220 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2221 int ReturnAddrIndex = FuncInfo->getRAIndex();
2223 if (ReturnAddrIndex == 0) {
2224 // Set up a frame object for the return address.
2225 uint64_t SlotSize = TD->getPointerSize();
2226 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2228 FuncInfo->setRAIndex(ReturnAddrIndex);
2231 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2235 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2236 bool hasSymbolicDisplacement) {
2237 // Offset should fit into 32 bit immediate field.
2238 if (!isInt32(Offset))
2241 // If we don't have a symbolic displacement - we don't have any extra
2243 if (!hasSymbolicDisplacement)
2246 // FIXME: Some tweaks might be needed for medium code model.
2247 if (M != CodeModel::Small && M != CodeModel::Kernel)
2250 // For small code model we assume that latest object is 16MB before end of 31
2251 // bits boundary. We may also accept pretty large negative constants knowing
2252 // that all objects are in the positive half of address space.
2253 if (M == CodeModel::Small && Offset < 16*1024*1024)
2256 // For kernel code model we know that all object resist in the negative half
2257 // of 32bits address space. We may not accept negative offsets, since they may
2258 // be just off and we may accept pretty large positive ones.
2259 if (M == CodeModel::Kernel && Offset > 0)
2265 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2266 /// specific condition code, returning the condition code and the LHS/RHS of the
2267 /// comparison to make.
2268 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2269 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2271 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2272 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2273 // X > -1 -> X == 0, jump !sign.
2274 RHS = DAG.getConstant(0, RHS.getValueType());
2275 return X86::COND_NS;
2276 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2277 // X < 0 -> X == 0, jump on sign.
2279 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2281 RHS = DAG.getConstant(0, RHS.getValueType());
2282 return X86::COND_LE;
2286 switch (SetCCOpcode) {
2287 default: llvm_unreachable("Invalid integer condition!");
2288 case ISD::SETEQ: return X86::COND_E;
2289 case ISD::SETGT: return X86::COND_G;
2290 case ISD::SETGE: return X86::COND_GE;
2291 case ISD::SETLT: return X86::COND_L;
2292 case ISD::SETLE: return X86::COND_LE;
2293 case ISD::SETNE: return X86::COND_NE;
2294 case ISD::SETULT: return X86::COND_B;
2295 case ISD::SETUGT: return X86::COND_A;
2296 case ISD::SETULE: return X86::COND_BE;
2297 case ISD::SETUGE: return X86::COND_AE;
2301 // First determine if it is required or is profitable to flip the operands.
2303 // If LHS is a foldable load, but RHS is not, flip the condition.
2304 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2305 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2306 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2307 std::swap(LHS, RHS);
2310 switch (SetCCOpcode) {
2316 std::swap(LHS, RHS);
2320 // On a floating point condition, the flags are set as follows:
2322 // 0 | 0 | 0 | X > Y
2323 // 0 | 0 | 1 | X < Y
2324 // 1 | 0 | 0 | X == Y
2325 // 1 | 1 | 1 | unordered
2326 switch (SetCCOpcode) {
2327 default: llvm_unreachable("Condcode should be pre-legalized away");
2329 case ISD::SETEQ: return X86::COND_E;
2330 case ISD::SETOLT: // flipped
2332 case ISD::SETGT: return X86::COND_A;
2333 case ISD::SETOLE: // flipped
2335 case ISD::SETGE: return X86::COND_AE;
2336 case ISD::SETUGT: // flipped
2338 case ISD::SETLT: return X86::COND_B;
2339 case ISD::SETUGE: // flipped
2341 case ISD::SETLE: return X86::COND_BE;
2343 case ISD::SETNE: return X86::COND_NE;
2344 case ISD::SETUO: return X86::COND_P;
2345 case ISD::SETO: return X86::COND_NP;
2347 case ISD::SETUNE: return X86::COND_INVALID;
2351 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2352 /// code. Current x86 isa includes the following FP cmov instructions:
2353 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2354 static bool hasFPCMov(unsigned X86CC) {
2370 /// isFPImmLegal - Returns true if the target can instruction select the
2371 /// specified FP immediate natively. If false, the legalizer will
2372 /// materialize the FP immediate as a load from a constant pool.
2373 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2374 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2375 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2381 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2382 /// the specified range (L, H].
2383 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2384 return (Val < 0) || (Val >= Low && Val < Hi);
2387 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2388 /// specified value.
2389 static bool isUndefOrEqual(int Val, int CmpVal) {
2390 if (Val < 0 || Val == CmpVal)
2395 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2396 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2397 /// the second operand.
2398 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2399 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2400 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2401 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2402 return (Mask[0] < 2 && Mask[1] < 2);
2406 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2407 SmallVector<int, 8> M;
2409 return ::isPSHUFDMask(M, N->getValueType(0));
2412 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2413 /// is suitable for input to PSHUFHW.
2414 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2415 if (VT != MVT::v8i16)
2418 // Lower quadword copied in order or undef.
2419 for (int i = 0; i != 4; ++i)
2420 if (Mask[i] >= 0 && Mask[i] != i)
2423 // Upper quadword shuffled.
2424 for (int i = 4; i != 8; ++i)
2425 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2431 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2432 SmallVector<int, 8> M;
2434 return ::isPSHUFHWMask(M, N->getValueType(0));
2437 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2438 /// is suitable for input to PSHUFLW.
2439 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2440 if (VT != MVT::v8i16)
2443 // Upper quadword copied in order.
2444 for (int i = 4; i != 8; ++i)
2445 if (Mask[i] >= 0 && Mask[i] != i)
2448 // Lower quadword shuffled.
2449 for (int i = 0; i != 4; ++i)
2456 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2457 SmallVector<int, 8> M;
2459 return ::isPSHUFLWMask(M, N->getValueType(0));
2462 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2463 /// is suitable for input to PALIGNR.
2464 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2466 int i, e = VT.getVectorNumElements();
2468 // Do not handle v2i64 / v2f64 shuffles with palignr.
2469 if (e < 4 || !hasSSSE3)
2472 for (i = 0; i != e; ++i)
2476 // All undef, not a palignr.
2480 // Determine if it's ok to perform a palignr with only the LHS, since we
2481 // don't have access to the actual shuffle elements to see if RHS is undef.
2482 bool Unary = Mask[i] < (int)e;
2483 bool NeedsUnary = false;
2485 int s = Mask[i] - i;
2487 // Check the rest of the elements to see if they are consecutive.
2488 for (++i; i != e; ++i) {
2493 Unary = Unary && (m < (int)e);
2494 NeedsUnary = NeedsUnary || (m < s);
2496 if (NeedsUnary && !Unary)
2498 if (Unary && m != ((s+i) & (e-1)))
2500 if (!Unary && m != (s+i))
2506 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2507 SmallVector<int, 8> M;
2509 return ::isPALIGNRMask(M, N->getValueType(0), true);
2512 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2513 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2514 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2515 int NumElems = VT.getVectorNumElements();
2516 if (NumElems != 2 && NumElems != 4)
2519 int Half = NumElems / 2;
2520 for (int i = 0; i < Half; ++i)
2521 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2523 for (int i = Half; i < NumElems; ++i)
2524 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2530 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2531 SmallVector<int, 8> M;
2533 return ::isSHUFPMask(M, N->getValueType(0));
2536 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2537 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2538 /// half elements to come from vector 1 (which would equal the dest.) and
2539 /// the upper half to come from vector 2.
2540 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2541 int NumElems = VT.getVectorNumElements();
2543 if (NumElems != 2 && NumElems != 4)
2546 int Half = NumElems / 2;
2547 for (int i = 0; i < Half; ++i)
2548 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2550 for (int i = Half; i < NumElems; ++i)
2551 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2556 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2557 SmallVector<int, 8> M;
2559 return isCommutedSHUFPMask(M, N->getValueType(0));
2562 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2563 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2564 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2565 if (N->getValueType(0).getVectorNumElements() != 4)
2568 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2569 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2570 isUndefOrEqual(N->getMaskElt(1), 7) &&
2571 isUndefOrEqual(N->getMaskElt(2), 2) &&
2572 isUndefOrEqual(N->getMaskElt(3), 3);
2575 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2576 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2578 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2579 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2584 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2585 isUndefOrEqual(N->getMaskElt(1), 3) &&
2586 isUndefOrEqual(N->getMaskElt(2), 2) &&
2587 isUndefOrEqual(N->getMaskElt(3), 3);
2590 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2591 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2592 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2593 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2595 if (NumElems != 2 && NumElems != 4)
2598 for (unsigned i = 0; i < NumElems/2; ++i)
2599 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2602 for (unsigned i = NumElems/2; i < NumElems; ++i)
2603 if (!isUndefOrEqual(N->getMaskElt(i), i))
2609 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2610 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2611 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2612 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2614 if (NumElems != 2 && NumElems != 4)
2617 for (unsigned i = 0; i < NumElems/2; ++i)
2618 if (!isUndefOrEqual(N->getMaskElt(i), i))
2621 for (unsigned i = 0; i < NumElems/2; ++i)
2622 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2628 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2629 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2630 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2631 bool V2IsSplat = false) {
2632 int NumElts = VT.getVectorNumElements();
2633 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2636 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2638 int BitI1 = Mask[i+1];
2639 if (!isUndefOrEqual(BitI, j))
2642 if (!isUndefOrEqual(BitI1, NumElts))
2645 if (!isUndefOrEqual(BitI1, j + NumElts))
2652 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2653 SmallVector<int, 8> M;
2655 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2658 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2659 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2660 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2661 bool V2IsSplat = false) {
2662 int NumElts = VT.getVectorNumElements();
2663 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2666 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2668 int BitI1 = Mask[i+1];
2669 if (!isUndefOrEqual(BitI, j + NumElts/2))
2672 if (isUndefOrEqual(BitI1, NumElts))
2675 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2682 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2683 SmallVector<int, 8> M;
2685 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2688 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2689 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2691 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2692 int NumElems = VT.getVectorNumElements();
2693 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2696 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2698 int BitI1 = Mask[i+1];
2699 if (!isUndefOrEqual(BitI, j))
2701 if (!isUndefOrEqual(BitI1, j))
2707 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2708 SmallVector<int, 8> M;
2710 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2713 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2714 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2716 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2717 int NumElems = VT.getVectorNumElements();
2718 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2721 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2723 int BitI1 = Mask[i+1];
2724 if (!isUndefOrEqual(BitI, j))
2726 if (!isUndefOrEqual(BitI1, j))
2732 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2733 SmallVector<int, 8> M;
2735 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2738 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2739 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2740 /// MOVSD, and MOVD, i.e. setting the lowest element.
2741 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2742 if (VT.getVectorElementType().getSizeInBits() < 32)
2745 int NumElts = VT.getVectorNumElements();
2747 if (!isUndefOrEqual(Mask[0], NumElts))
2750 for (int i = 1; i < NumElts; ++i)
2751 if (!isUndefOrEqual(Mask[i], i))
2757 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2758 SmallVector<int, 8> M;
2760 return ::isMOVLMask(M, N->getValueType(0));
2763 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2764 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2765 /// element of vector 2 and the other elements to come from vector 1 in order.
2766 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2767 bool V2IsSplat = false, bool V2IsUndef = false) {
2768 int NumOps = VT.getVectorNumElements();
2769 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2772 if (!isUndefOrEqual(Mask[0], 0))
2775 for (int i = 1; i < NumOps; ++i)
2776 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2777 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2778 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2784 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2785 bool V2IsUndef = false) {
2786 SmallVector<int, 8> M;
2788 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2791 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2792 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2793 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2794 if (N->getValueType(0).getVectorNumElements() != 4)
2797 // Expect 1, 1, 3, 3
2798 for (unsigned i = 0; i < 2; ++i) {
2799 int Elt = N->getMaskElt(i);
2800 if (Elt >= 0 && Elt != 1)
2805 for (unsigned i = 2; i < 4; ++i) {
2806 int Elt = N->getMaskElt(i);
2807 if (Elt >= 0 && Elt != 3)
2812 // Don't use movshdup if it can be done with a shufps.
2813 // FIXME: verify that matching u, u, 3, 3 is what we want.
2817 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2818 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2819 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2820 if (N->getValueType(0).getVectorNumElements() != 4)
2823 // Expect 0, 0, 2, 2
2824 for (unsigned i = 0; i < 2; ++i)
2825 if (N->getMaskElt(i) > 0)
2829 for (unsigned i = 2; i < 4; ++i) {
2830 int Elt = N->getMaskElt(i);
2831 if (Elt >= 0 && Elt != 2)
2836 // Don't use movsldup if it can be done with a shufps.
2840 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2841 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2842 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2843 int e = N->getValueType(0).getVectorNumElements() / 2;
2845 for (int i = 0; i < e; ++i)
2846 if (!isUndefOrEqual(N->getMaskElt(i), i))
2848 for (int i = 0; i < e; ++i)
2849 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2854 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2855 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2856 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2857 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2858 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2860 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2862 for (int i = 0; i < NumOperands; ++i) {
2863 int Val = SVOp->getMaskElt(NumOperands-i-1);
2864 if (Val < 0) Val = 0;
2865 if (Val >= NumOperands) Val -= NumOperands;
2867 if (i != NumOperands - 1)
2873 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2874 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2875 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2876 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2878 // 8 nodes, but we only care about the last 4.
2879 for (unsigned i = 7; i >= 4; --i) {
2880 int Val = SVOp->getMaskElt(i);
2889 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2890 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2891 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2894 // 8 nodes, but we only care about the first 4.
2895 for (int i = 3; i >= 0; --i) {
2896 int Val = SVOp->getMaskElt(i);
2905 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2906 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2907 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2908 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2909 EVT VVT = N->getValueType(0);
2910 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2914 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2915 Val = SVOp->getMaskElt(i);
2919 return (Val - i) * EltSize;
2922 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2924 bool X86::isZeroNode(SDValue Elt) {
2925 return ((isa<ConstantSDNode>(Elt) &&
2926 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2927 (isa<ConstantFPSDNode>(Elt) &&
2928 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2931 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2932 /// their permute mask.
2933 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2934 SelectionDAG &DAG) {
2935 EVT VT = SVOp->getValueType(0);
2936 unsigned NumElems = VT.getVectorNumElements();
2937 SmallVector<int, 8> MaskVec;
2939 for (unsigned i = 0; i != NumElems; ++i) {
2940 int idx = SVOp->getMaskElt(i);
2942 MaskVec.push_back(idx);
2943 else if (idx < (int)NumElems)
2944 MaskVec.push_back(idx + NumElems);
2946 MaskVec.push_back(idx - NumElems);
2948 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2949 SVOp->getOperand(0), &MaskVec[0]);
2952 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2953 /// the two vector operands have swapped position.
2954 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2955 unsigned NumElems = VT.getVectorNumElements();
2956 for (unsigned i = 0; i != NumElems; ++i) {
2960 else if (idx < (int)NumElems)
2961 Mask[i] = idx + NumElems;
2963 Mask[i] = idx - NumElems;
2967 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2968 /// match movhlps. The lower half elements should come from upper half of
2969 /// V1 (and in order), and the upper half elements should come from the upper
2970 /// half of V2 (and in order).
2971 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2972 if (Op->getValueType(0).getVectorNumElements() != 4)
2974 for (unsigned i = 0, e = 2; i != e; ++i)
2975 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2977 for (unsigned i = 2; i != 4; ++i)
2978 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2983 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2984 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2986 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2987 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2989 N = N->getOperand(0).getNode();
2990 if (!ISD::isNON_EXTLoad(N))
2993 *LD = cast<LoadSDNode>(N);
2997 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2998 /// match movlp{s|d}. The lower half elements should come from lower half of
2999 /// V1 (and in order), and the upper half elements should come from the upper
3000 /// half of V2 (and in order). And since V1 will become the source of the
3001 /// MOVLP, it must be either a vector load or a scalar load to vector.
3002 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3003 ShuffleVectorSDNode *Op) {
3004 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3006 // Is V2 is a vector load, don't do this transformation. We will try to use
3007 // load folding shufps op.
3008 if (ISD::isNON_EXTLoad(V2))
3011 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3013 if (NumElems != 2 && NumElems != 4)
3015 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3016 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3018 for (unsigned i = NumElems/2; i != NumElems; ++i)
3019 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3024 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3026 static bool isSplatVector(SDNode *N) {
3027 if (N->getOpcode() != ISD::BUILD_VECTOR)
3030 SDValue SplatValue = N->getOperand(0);
3031 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3032 if (N->getOperand(i) != SplatValue)
3037 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3038 /// to an zero vector.
3039 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3040 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3041 SDValue V1 = N->getOperand(0);
3042 SDValue V2 = N->getOperand(1);
3043 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3044 for (unsigned i = 0; i != NumElems; ++i) {
3045 int Idx = N->getMaskElt(i);
3046 if (Idx >= (int)NumElems) {
3047 unsigned Opc = V2.getOpcode();
3048 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3050 if (Opc != ISD::BUILD_VECTOR ||
3051 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3053 } else if (Idx >= 0) {
3054 unsigned Opc = V1.getOpcode();
3055 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3057 if (Opc != ISD::BUILD_VECTOR ||
3058 !X86::isZeroNode(V1.getOperand(Idx)))
3065 /// getZeroVector - Returns a vector of specified type with all zero elements.
3067 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3069 assert(VT.isVector() && "Expected a vector type");
3071 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3072 // type. This ensures they get CSE'd.
3074 if (VT.getSizeInBits() == 64) { // MMX
3075 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3076 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3077 } else if (HasSSE2) { // SSE2
3078 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3079 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3081 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3082 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3084 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3087 /// getOnesVector - Returns a vector of specified type with all bits set.
3089 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3090 assert(VT.isVector() && "Expected a vector type");
3092 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3093 // type. This ensures they get CSE'd.
3094 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3096 if (VT.getSizeInBits() == 64) // MMX
3097 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3099 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3100 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3104 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3105 /// that point to V2 points to its first element.
3106 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3107 EVT VT = SVOp->getValueType(0);
3108 unsigned NumElems = VT.getVectorNumElements();
3110 bool Changed = false;
3111 SmallVector<int, 8> MaskVec;
3112 SVOp->getMask(MaskVec);
3114 for (unsigned i = 0; i != NumElems; ++i) {
3115 if (MaskVec[i] > (int)NumElems) {
3116 MaskVec[i] = NumElems;
3121 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3122 SVOp->getOperand(1), &MaskVec[0]);
3123 return SDValue(SVOp, 0);
3126 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3127 /// operation of specified width.
3128 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3130 unsigned NumElems = VT.getVectorNumElements();
3131 SmallVector<int, 8> Mask;
3132 Mask.push_back(NumElems);
3133 for (unsigned i = 1; i != NumElems; ++i)
3135 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3138 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3139 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3141 unsigned NumElems = VT.getVectorNumElements();
3142 SmallVector<int, 8> Mask;
3143 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3145 Mask.push_back(i + NumElems);
3147 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3150 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3151 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3153 unsigned NumElems = VT.getVectorNumElements();
3154 unsigned Half = NumElems/2;
3155 SmallVector<int, 8> Mask;
3156 for (unsigned i = 0; i != Half; ++i) {
3157 Mask.push_back(i + Half);
3158 Mask.push_back(i + NumElems + Half);
3160 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3163 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3164 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3166 if (SV->getValueType(0).getVectorNumElements() <= 4)
3167 return SDValue(SV, 0);
3169 EVT PVT = MVT::v4f32;
3170 EVT VT = SV->getValueType(0);
3171 DebugLoc dl = SV->getDebugLoc();
3172 SDValue V1 = SV->getOperand(0);
3173 int NumElems = VT.getVectorNumElements();
3174 int EltNo = SV->getSplatIndex();
3176 // unpack elements to the correct location
3177 while (NumElems > 4) {
3178 if (EltNo < NumElems/2) {
3179 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3181 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3182 EltNo -= NumElems/2;
3187 // Perform the splat.
3188 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3189 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3190 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3191 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3194 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3195 /// vector of zero or undef vector. This produces a shuffle where the low
3196 /// element of V2 is swizzled into the zero/undef vector, landing at element
3197 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3198 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3199 bool isZero, bool HasSSE2,
3200 SelectionDAG &DAG) {
3201 EVT VT = V2.getValueType();
3203 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3204 unsigned NumElems = VT.getVectorNumElements();
3205 SmallVector<int, 16> MaskVec;
3206 for (unsigned i = 0; i != NumElems; ++i)
3207 // If this is the insertion idx, put the low elt of V2 here.
3208 MaskVec.push_back(i == Idx ? NumElems : i);
3209 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3212 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3213 /// a shuffle that is zero.
3215 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3216 bool Low, SelectionDAG &DAG) {
3217 unsigned NumZeros = 0;
3218 for (int i = 0; i < NumElems; ++i) {
3219 unsigned Index = Low ? i : NumElems-i-1;
3220 int Idx = SVOp->getMaskElt(Index);
3225 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3226 if (Elt.getNode() && X86::isZeroNode(Elt))
3234 /// isVectorShift - Returns true if the shuffle can be implemented as a
3235 /// logical left or right shift of a vector.
3236 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3237 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3238 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3239 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3242 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3245 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3249 bool SeenV1 = false;
3250 bool SeenV2 = false;
3251 for (int i = NumZeros; i < NumElems; ++i) {
3252 int Val = isLeft ? (i - NumZeros) : i;
3253 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3265 if (SeenV1 && SeenV2)
3268 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3274 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3276 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3277 unsigned NumNonZero, unsigned NumZero,
3278 SelectionDAG &DAG, TargetLowering &TLI) {
3282 DebugLoc dl = Op.getDebugLoc();
3285 for (unsigned i = 0; i < 16; ++i) {
3286 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3287 if (ThisIsNonZero && First) {
3289 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3291 V = DAG.getUNDEF(MVT::v8i16);
3296 SDValue ThisElt(0, 0), LastElt(0, 0);
3297 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3298 if (LastIsNonZero) {
3299 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3300 MVT::i16, Op.getOperand(i-1));
3302 if (ThisIsNonZero) {
3303 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3304 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3305 ThisElt, DAG.getConstant(8, MVT::i8));
3307 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3311 if (ThisElt.getNode())
3312 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3313 DAG.getIntPtrConstant(i/2));
3317 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3320 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3322 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3323 unsigned NumNonZero, unsigned NumZero,
3324 SelectionDAG &DAG, TargetLowering &TLI) {
3328 DebugLoc dl = Op.getDebugLoc();
3331 for (unsigned i = 0; i < 8; ++i) {
3332 bool isNonZero = (NonZeros & (1 << i)) != 0;
3336 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3338 V = DAG.getUNDEF(MVT::v8i16);
3341 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3342 MVT::v8i16, V, Op.getOperand(i),
3343 DAG.getIntPtrConstant(i));
3350 /// getVShift - Return a vector logical shift node.
3352 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3353 unsigned NumBits, SelectionDAG &DAG,
3354 const TargetLowering &TLI, DebugLoc dl) {
3355 bool isMMX = VT.getSizeInBits() == 64;
3356 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3357 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3358 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3359 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3360 DAG.getNode(Opc, dl, ShVT, SrcOp,
3361 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3365 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3366 SelectionDAG &DAG) {
3368 // Check if the scalar load can be widened into a vector load. And if
3369 // the address is "base + cst" see if the cst can be "absorbed" into
3370 // the shuffle mask.
3371 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3372 SDValue Ptr = LD->getBasePtr();
3373 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3375 EVT PVT = LD->getValueType(0);
3376 if (PVT != MVT::i32 && PVT != MVT::f32)
3381 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3382 FI = FINode->getIndex();
3384 } else if (Ptr.getOpcode() == ISD::ADD &&
3385 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3386 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3387 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3388 Offset = Ptr.getConstantOperandVal(1);
3389 Ptr = Ptr.getOperand(0);
3394 SDValue Chain = LD->getChain();
3395 // Make sure the stack object alignment is at least 16.
3396 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3397 if (DAG.InferPtrAlignment(Ptr) < 16) {
3398 if (MFI->isFixedObjectIndex(FI)) {
3399 // Can't change the alignment. FIXME: It's possible to compute
3400 // the exact stack offset and reference FI + adjust offset instead.
3401 // If someone *really* cares about this. That's the way to implement it.
3404 MFI->setObjectAlignment(FI, 16);
3408 // (Offset % 16) must be multiple of 4. Then address is then
3409 // Ptr + (Offset & ~15).
3412 if ((Offset % 16) & 3)
3414 int64_t StartOffset = Offset & ~15;
3416 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3417 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3419 int EltNo = (Offset - StartOffset) >> 2;
3420 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3421 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3422 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3423 // Canonicalize it to a v4i32 shuffle.
3424 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3425 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3426 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3427 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3434 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3435 DebugLoc dl = Op.getDebugLoc();
3436 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3437 if (ISD::isBuildVectorAllZeros(Op.getNode())
3438 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3439 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3440 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3441 // eliminated on x86-32 hosts.
3442 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3445 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3446 return getOnesVector(Op.getValueType(), DAG, dl);
3447 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3450 EVT VT = Op.getValueType();
3451 EVT ExtVT = VT.getVectorElementType();
3452 unsigned EVTBits = ExtVT.getSizeInBits();
3454 unsigned NumElems = Op.getNumOperands();
3455 unsigned NumZero = 0;
3456 unsigned NumNonZero = 0;
3457 unsigned NonZeros = 0;
3458 bool IsAllConstants = true;
3459 SmallSet<SDValue, 8> Values;
3460 for (unsigned i = 0; i < NumElems; ++i) {
3461 SDValue Elt = Op.getOperand(i);
3462 if (Elt.getOpcode() == ISD::UNDEF)
3465 if (Elt.getOpcode() != ISD::Constant &&
3466 Elt.getOpcode() != ISD::ConstantFP)
3467 IsAllConstants = false;
3468 if (X86::isZeroNode(Elt))
3471 NonZeros |= (1 << i);
3476 if (NumNonZero == 0) {
3477 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3478 return DAG.getUNDEF(VT);
3481 // Special case for single non-zero, non-undef, element.
3482 if (NumNonZero == 1) {
3483 unsigned Idx = CountTrailingZeros_32(NonZeros);
3484 SDValue Item = Op.getOperand(Idx);
3486 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3487 // the value are obviously zero, truncate the value to i32 and do the
3488 // insertion that way. Only do this if the value is non-constant or if the
3489 // value is a constant being inserted into element 0. It is cheaper to do
3490 // a constant pool load than it is to do a movd + shuffle.
3491 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3492 (!IsAllConstants || Idx == 0)) {
3493 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3494 // Handle MMX and SSE both.
3495 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3496 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3498 // Truncate the value (which may itself be a constant) to i32, and
3499 // convert it to a vector with movd (S2V+shuffle to zero extend).
3500 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3501 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3502 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3503 Subtarget->hasSSE2(), DAG);
3505 // Now we have our 32-bit value zero extended in the low element of
3506 // a vector. If Idx != 0, swizzle it into place.
3508 SmallVector<int, 4> Mask;
3509 Mask.push_back(Idx);
3510 for (unsigned i = 1; i != VecElts; ++i)
3512 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3513 DAG.getUNDEF(Item.getValueType()),
3516 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3520 // If we have a constant or non-constant insertion into the low element of
3521 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3522 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3523 // depending on what the source datatype is.
3526 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3527 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3528 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3529 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3530 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3531 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3533 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3534 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3535 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3536 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3537 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3538 Subtarget->hasSSE2(), DAG);
3539 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3543 // Is it a vector logical left shift?
3544 if (NumElems == 2 && Idx == 1 &&
3545 X86::isZeroNode(Op.getOperand(0)) &&
3546 !X86::isZeroNode(Op.getOperand(1))) {
3547 unsigned NumBits = VT.getSizeInBits();
3548 return getVShift(true, VT,
3549 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3550 VT, Op.getOperand(1)),
3551 NumBits/2, DAG, *this, dl);
3554 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3557 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3558 // is a non-constant being inserted into an element other than the low one,
3559 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3560 // movd/movss) to move this into the low element, then shuffle it into
3562 if (EVTBits == 32) {
3563 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3565 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3566 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3567 Subtarget->hasSSE2(), DAG);
3568 SmallVector<int, 8> MaskVec;
3569 for (unsigned i = 0; i < NumElems; i++)
3570 MaskVec.push_back(i == Idx ? 0 : 1);
3571 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3575 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3576 if (Values.size() == 1) {
3577 if (EVTBits == 32) {
3578 // Instead of a shuffle like this:
3579 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3580 // Check if it's possible to issue this instead.
3581 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3582 unsigned Idx = CountTrailingZeros_32(NonZeros);
3583 SDValue Item = Op.getOperand(Idx);
3584 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3585 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3590 // A vector full of immediates; various special cases are already
3591 // handled, so this is best done with a single constant-pool load.
3595 // Let legalizer expand 2-wide build_vectors.
3596 if (EVTBits == 64) {
3597 if (NumNonZero == 1) {
3598 // One half is zero or undef.
3599 unsigned Idx = CountTrailingZeros_32(NonZeros);
3600 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3601 Op.getOperand(Idx));
3602 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3603 Subtarget->hasSSE2(), DAG);
3608 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3609 if (EVTBits == 8 && NumElems == 16) {
3610 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3612 if (V.getNode()) return V;
3615 if (EVTBits == 16 && NumElems == 8) {
3616 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3618 if (V.getNode()) return V;
3621 // If element VT is == 32 bits, turn it into a number of shuffles.
3622 SmallVector<SDValue, 8> V;
3624 if (NumElems == 4 && NumZero > 0) {
3625 for (unsigned i = 0; i < 4; ++i) {
3626 bool isZero = !(NonZeros & (1 << i));
3628 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3630 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3633 for (unsigned i = 0; i < 2; ++i) {
3634 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3637 V[i] = V[i*2]; // Must be a zero vector.
3640 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3643 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3646 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3651 SmallVector<int, 8> MaskVec;
3652 bool Reverse = (NonZeros & 0x3) == 2;
3653 for (unsigned i = 0; i < 2; ++i)
3654 MaskVec.push_back(Reverse ? 1-i : i);
3655 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3656 for (unsigned i = 0; i < 2; ++i)
3657 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3658 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3661 if (Values.size() > 2) {
3662 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3663 // values to be inserted is equal to the number of elements, in which case
3664 // use the unpack code below in the hopes of matching the consecutive elts
3665 // load merge pattern for shuffles.
3666 // FIXME: We could probably just check that here directly.
3667 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3668 getSubtarget()->hasSSE41()) {
3669 V[0] = DAG.getUNDEF(VT);
3670 for (unsigned i = 0; i < NumElems; ++i)
3671 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3672 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3673 Op.getOperand(i), DAG.getIntPtrConstant(i));
3676 // Expand into a number of unpckl*.
3678 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3679 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3680 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3681 for (unsigned i = 0; i < NumElems; ++i)
3682 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3684 while (NumElems != 0) {
3685 for (unsigned i = 0; i < NumElems; ++i)
3686 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3696 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3697 // We support concatenate two MMX registers and place them in a MMX
3698 // register. This is better than doing a stack convert.
3699 DebugLoc dl = Op.getDebugLoc();
3700 EVT ResVT = Op.getValueType();
3701 assert(Op.getNumOperands() == 2);
3702 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3703 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3705 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3706 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3707 InVec = Op.getOperand(1);
3708 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3709 unsigned NumElts = ResVT.getVectorNumElements();
3710 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3711 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3712 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3714 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3715 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3716 Mask[0] = 0; Mask[1] = 2;
3717 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3719 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3722 // v8i16 shuffles - Prefer shuffles in the following order:
3723 // 1. [all] pshuflw, pshufhw, optional move
3724 // 2. [ssse3] 1 x pshufb
3725 // 3. [ssse3] 2 x pshufb + 1 x por
3726 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3728 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3729 SelectionDAG &DAG, X86TargetLowering &TLI) {
3730 SDValue V1 = SVOp->getOperand(0);
3731 SDValue V2 = SVOp->getOperand(1);
3732 DebugLoc dl = SVOp->getDebugLoc();
3733 SmallVector<int, 8> MaskVals;
3735 // Determine if more than 1 of the words in each of the low and high quadwords
3736 // of the result come from the same quadword of one of the two inputs. Undef
3737 // mask values count as coming from any quadword, for better codegen.
3738 SmallVector<unsigned, 4> LoQuad(4);
3739 SmallVector<unsigned, 4> HiQuad(4);
3740 BitVector InputQuads(4);
3741 for (unsigned i = 0; i < 8; ++i) {
3742 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3743 int EltIdx = SVOp->getMaskElt(i);
3744 MaskVals.push_back(EltIdx);
3753 InputQuads.set(EltIdx / 4);
3756 int BestLoQuad = -1;
3757 unsigned MaxQuad = 1;
3758 for (unsigned i = 0; i < 4; ++i) {
3759 if (LoQuad[i] > MaxQuad) {
3761 MaxQuad = LoQuad[i];
3765 int BestHiQuad = -1;
3767 for (unsigned i = 0; i < 4; ++i) {
3768 if (HiQuad[i] > MaxQuad) {
3770 MaxQuad = HiQuad[i];
3774 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3775 // of the two input vectors, shuffle them into one input vector so only a
3776 // single pshufb instruction is necessary. If There are more than 2 input
3777 // quads, disable the next transformation since it does not help SSSE3.
3778 bool V1Used = InputQuads[0] || InputQuads[1];
3779 bool V2Used = InputQuads[2] || InputQuads[3];
3780 if (TLI.getSubtarget()->hasSSSE3()) {
3781 if (InputQuads.count() == 2 && V1Used && V2Used) {
3782 BestLoQuad = InputQuads.find_first();
3783 BestHiQuad = InputQuads.find_next(BestLoQuad);
3785 if (InputQuads.count() > 2) {
3791 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3792 // the shuffle mask. If a quad is scored as -1, that means that it contains
3793 // words from all 4 input quadwords.
3795 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3796 SmallVector<int, 8> MaskV;
3797 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3798 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3799 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3800 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3801 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3802 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3804 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3805 // source words for the shuffle, to aid later transformations.
3806 bool AllWordsInNewV = true;
3807 bool InOrder[2] = { true, true };
3808 for (unsigned i = 0; i != 8; ++i) {
3809 int idx = MaskVals[i];
3811 InOrder[i/4] = false;
3812 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3814 AllWordsInNewV = false;
3818 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3819 if (AllWordsInNewV) {
3820 for (int i = 0; i != 8; ++i) {
3821 int idx = MaskVals[i];
3824 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3825 if ((idx != i) && idx < 4)
3827 if ((idx != i) && idx > 3)
3836 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3837 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3838 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3839 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3840 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3844 // If we have SSSE3, and all words of the result are from 1 input vector,
3845 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3846 // is present, fall back to case 4.
3847 if (TLI.getSubtarget()->hasSSSE3()) {
3848 SmallVector<SDValue,16> pshufbMask;
3850 // If we have elements from both input vectors, set the high bit of the
3851 // shuffle mask element to zero out elements that come from V2 in the V1
3852 // mask, and elements that come from V1 in the V2 mask, so that the two
3853 // results can be OR'd together.
3854 bool TwoInputs = V1Used && V2Used;
3855 for (unsigned i = 0; i != 8; ++i) {
3856 int EltIdx = MaskVals[i] * 2;
3857 if (TwoInputs && (EltIdx >= 16)) {
3858 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3859 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3862 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3863 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3865 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3866 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3867 DAG.getNode(ISD::BUILD_VECTOR, dl,
3868 MVT::v16i8, &pshufbMask[0], 16));
3870 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3872 // Calculate the shuffle mask for the second input, shuffle it, and
3873 // OR it with the first shuffled input.
3875 for (unsigned i = 0; i != 8; ++i) {
3876 int EltIdx = MaskVals[i] * 2;
3878 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3879 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3882 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3883 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3885 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3886 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3887 DAG.getNode(ISD::BUILD_VECTOR, dl,
3888 MVT::v16i8, &pshufbMask[0], 16));
3889 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3890 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3893 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3894 // and update MaskVals with new element order.
3895 BitVector InOrder(8);
3896 if (BestLoQuad >= 0) {
3897 SmallVector<int, 8> MaskV;
3898 for (int i = 0; i != 4; ++i) {
3899 int idx = MaskVals[i];
3901 MaskV.push_back(-1);
3903 } else if ((idx / 4) == BestLoQuad) {
3904 MaskV.push_back(idx & 3);
3907 MaskV.push_back(-1);
3910 for (unsigned i = 4; i != 8; ++i)
3912 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3916 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3917 // and update MaskVals with the new element order.
3918 if (BestHiQuad >= 0) {
3919 SmallVector<int, 8> MaskV;
3920 for (unsigned i = 0; i != 4; ++i)
3922 for (unsigned i = 4; i != 8; ++i) {
3923 int idx = MaskVals[i];
3925 MaskV.push_back(-1);
3927 } else if ((idx / 4) == BestHiQuad) {
3928 MaskV.push_back((idx & 3) + 4);
3931 MaskV.push_back(-1);
3934 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3938 // In case BestHi & BestLo were both -1, which means each quadword has a word
3939 // from each of the four input quadwords, calculate the InOrder bitvector now
3940 // before falling through to the insert/extract cleanup.
3941 if (BestLoQuad == -1 && BestHiQuad == -1) {
3943 for (int i = 0; i != 8; ++i)
3944 if (MaskVals[i] < 0 || MaskVals[i] == i)
3948 // The other elements are put in the right place using pextrw and pinsrw.
3949 for (unsigned i = 0; i != 8; ++i) {
3952 int EltIdx = MaskVals[i];
3955 SDValue ExtOp = (EltIdx < 8)
3956 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3957 DAG.getIntPtrConstant(EltIdx))
3958 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3959 DAG.getIntPtrConstant(EltIdx - 8));
3960 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3961 DAG.getIntPtrConstant(i));
3966 // v16i8 shuffles - Prefer shuffles in the following order:
3967 // 1. [ssse3] 1 x pshufb
3968 // 2. [ssse3] 2 x pshufb + 1 x por
3969 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3971 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3972 SelectionDAG &DAG, X86TargetLowering &TLI) {
3973 SDValue V1 = SVOp->getOperand(0);
3974 SDValue V2 = SVOp->getOperand(1);
3975 DebugLoc dl = SVOp->getDebugLoc();
3976 SmallVector<int, 16> MaskVals;
3977 SVOp->getMask(MaskVals);
3979 // If we have SSSE3, case 1 is generated when all result bytes come from
3980 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3981 // present, fall back to case 3.
3982 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3985 for (unsigned i = 0; i < 16; ++i) {
3986 int EltIdx = MaskVals[i];
3995 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3996 if (TLI.getSubtarget()->hasSSSE3()) {
3997 SmallVector<SDValue,16> pshufbMask;
3999 // If all result elements are from one input vector, then only translate
4000 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4002 // Otherwise, we have elements from both input vectors, and must zero out
4003 // elements that come from V2 in the first mask, and V1 in the second mask
4004 // so that we can OR them together.
4005 bool TwoInputs = !(V1Only || V2Only);
4006 for (unsigned i = 0; i != 16; ++i) {
4007 int EltIdx = MaskVals[i];
4008 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4009 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4012 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4014 // If all the elements are from V2, assign it to V1 and return after
4015 // building the first pshufb.
4018 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4019 DAG.getNode(ISD::BUILD_VECTOR, dl,
4020 MVT::v16i8, &pshufbMask[0], 16));
4024 // Calculate the shuffle mask for the second input, shuffle it, and
4025 // OR it with the first shuffled input.
4027 for (unsigned i = 0; i != 16; ++i) {
4028 int EltIdx = MaskVals[i];
4030 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4033 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4035 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4036 DAG.getNode(ISD::BUILD_VECTOR, dl,
4037 MVT::v16i8, &pshufbMask[0], 16));
4038 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4041 // No SSSE3 - Calculate in place words and then fix all out of place words
4042 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4043 // the 16 different words that comprise the two doublequadword input vectors.
4044 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4045 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4046 SDValue NewV = V2Only ? V2 : V1;
4047 for (int i = 0; i != 8; ++i) {
4048 int Elt0 = MaskVals[i*2];
4049 int Elt1 = MaskVals[i*2+1];
4051 // This word of the result is all undef, skip it.
4052 if (Elt0 < 0 && Elt1 < 0)
4055 // This word of the result is already in the correct place, skip it.
4056 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4058 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4061 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4062 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4065 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4066 // using a single extract together, load it and store it.
4067 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4068 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4069 DAG.getIntPtrConstant(Elt1 / 2));
4070 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4071 DAG.getIntPtrConstant(i));
4075 // If Elt1 is defined, extract it from the appropriate source. If the
4076 // source byte is not also odd, shift the extracted word left 8 bits
4077 // otherwise clear the bottom 8 bits if we need to do an or.
4079 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4080 DAG.getIntPtrConstant(Elt1 / 2));
4081 if ((Elt1 & 1) == 0)
4082 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4083 DAG.getConstant(8, TLI.getShiftAmountTy()));
4085 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4086 DAG.getConstant(0xFF00, MVT::i16));
4088 // If Elt0 is defined, extract it from the appropriate source. If the
4089 // source byte is not also even, shift the extracted word right 8 bits. If
4090 // Elt1 was also defined, OR the extracted values together before
4091 // inserting them in the result.
4093 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4094 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4095 if ((Elt0 & 1) != 0)
4096 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4097 DAG.getConstant(8, TLI.getShiftAmountTy()));
4099 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4100 DAG.getConstant(0x00FF, MVT::i16));
4101 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4104 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4105 DAG.getIntPtrConstant(i));
4107 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4110 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4111 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4112 /// done when every pair / quad of shuffle mask elements point to elements in
4113 /// the right sequence. e.g.
4114 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4116 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4118 TargetLowering &TLI, DebugLoc dl) {
4119 EVT VT = SVOp->getValueType(0);
4120 SDValue V1 = SVOp->getOperand(0);
4121 SDValue V2 = SVOp->getOperand(1);
4122 unsigned NumElems = VT.getVectorNumElements();
4123 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4124 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4125 EVT MaskEltVT = MaskVT.getVectorElementType();
4127 switch (VT.getSimpleVT().SimpleTy) {
4128 default: assert(false && "Unexpected!");
4129 case MVT::v4f32: NewVT = MVT::v2f64; break;
4130 case MVT::v4i32: NewVT = MVT::v2i64; break;
4131 case MVT::v8i16: NewVT = MVT::v4i32; break;
4132 case MVT::v16i8: NewVT = MVT::v4i32; break;
4135 if (NewWidth == 2) {
4141 int Scale = NumElems / NewWidth;
4142 SmallVector<int, 8> MaskVec;
4143 for (unsigned i = 0; i < NumElems; i += Scale) {
4145 for (int j = 0; j < Scale; ++j) {
4146 int EltIdx = SVOp->getMaskElt(i+j);
4150 StartIdx = EltIdx - (EltIdx % Scale);
4151 if (EltIdx != StartIdx + j)
4155 MaskVec.push_back(-1);
4157 MaskVec.push_back(StartIdx / Scale);
4160 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4161 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4162 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4165 /// getVZextMovL - Return a zero-extending vector move low node.
4167 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4168 SDValue SrcOp, SelectionDAG &DAG,
4169 const X86Subtarget *Subtarget, DebugLoc dl) {
4170 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4171 LoadSDNode *LD = NULL;
4172 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4173 LD = dyn_cast<LoadSDNode>(SrcOp);
4175 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4177 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4178 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4179 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4180 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4181 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4183 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4184 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4185 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4186 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4194 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4195 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4196 DAG.getNode(ISD::BIT_CONVERT, dl,
4200 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4203 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4204 SDValue V1 = SVOp->getOperand(0);
4205 SDValue V2 = SVOp->getOperand(1);
4206 DebugLoc dl = SVOp->getDebugLoc();
4207 EVT VT = SVOp->getValueType(0);
4209 SmallVector<std::pair<int, int>, 8> Locs;
4211 SmallVector<int, 8> Mask1(4U, -1);
4212 SmallVector<int, 8> PermMask;
4213 SVOp->getMask(PermMask);
4217 for (unsigned i = 0; i != 4; ++i) {
4218 int Idx = PermMask[i];
4220 Locs[i] = std::make_pair(-1, -1);
4222 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4224 Locs[i] = std::make_pair(0, NumLo);
4228 Locs[i] = std::make_pair(1, NumHi);
4230 Mask1[2+NumHi] = Idx;
4236 if (NumLo <= 2 && NumHi <= 2) {
4237 // If no more than two elements come from either vector. This can be
4238 // implemented with two shuffles. First shuffle gather the elements.
4239 // The second shuffle, which takes the first shuffle as both of its
4240 // vector operands, put the elements into the right order.
4241 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4243 SmallVector<int, 8> Mask2(4U, -1);
4245 for (unsigned i = 0; i != 4; ++i) {
4246 if (Locs[i].first == -1)
4249 unsigned Idx = (i < 2) ? 0 : 4;
4250 Idx += Locs[i].first * 2 + Locs[i].second;
4255 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4256 } else if (NumLo == 3 || NumHi == 3) {
4257 // Otherwise, we must have three elements from one vector, call it X, and
4258 // one element from the other, call it Y. First, use a shufps to build an
4259 // intermediate vector with the one element from Y and the element from X
4260 // that will be in the same half in the final destination (the indexes don't
4261 // matter). Then, use a shufps to build the final vector, taking the half
4262 // containing the element from Y from the intermediate, and the other half
4265 // Normalize it so the 3 elements come from V1.
4266 CommuteVectorShuffleMask(PermMask, VT);
4270 // Find the element from V2.
4272 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4273 int Val = PermMask[HiIndex];
4280 Mask1[0] = PermMask[HiIndex];
4282 Mask1[2] = PermMask[HiIndex^1];
4284 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4287 Mask1[0] = PermMask[0];
4288 Mask1[1] = PermMask[1];
4289 Mask1[2] = HiIndex & 1 ? 6 : 4;
4290 Mask1[3] = HiIndex & 1 ? 4 : 6;
4291 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4293 Mask1[0] = HiIndex & 1 ? 2 : 0;
4294 Mask1[1] = HiIndex & 1 ? 0 : 2;
4295 Mask1[2] = PermMask[2];
4296 Mask1[3] = PermMask[3];
4301 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4305 // Break it into (shuffle shuffle_hi, shuffle_lo).
4307 SmallVector<int,8> LoMask(4U, -1);
4308 SmallVector<int,8> HiMask(4U, -1);
4310 SmallVector<int,8> *MaskPtr = &LoMask;
4311 unsigned MaskIdx = 0;
4314 for (unsigned i = 0; i != 4; ++i) {
4321 int Idx = PermMask[i];
4323 Locs[i] = std::make_pair(-1, -1);
4324 } else if (Idx < 4) {
4325 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4326 (*MaskPtr)[LoIdx] = Idx;
4329 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4330 (*MaskPtr)[HiIdx] = Idx;
4335 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4336 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4337 SmallVector<int, 8> MaskOps;
4338 for (unsigned i = 0; i != 4; ++i) {
4339 if (Locs[i].first == -1) {
4340 MaskOps.push_back(-1);
4342 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4343 MaskOps.push_back(Idx);
4346 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4350 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4351 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4352 SDValue V1 = Op.getOperand(0);
4353 SDValue V2 = Op.getOperand(1);
4354 EVT VT = Op.getValueType();
4355 DebugLoc dl = Op.getDebugLoc();
4356 unsigned NumElems = VT.getVectorNumElements();
4357 bool isMMX = VT.getSizeInBits() == 64;
4358 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4359 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4360 bool V1IsSplat = false;
4361 bool V2IsSplat = false;
4363 if (isZeroShuffle(SVOp))
4364 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4366 // Promote splats to v4f32.
4367 if (SVOp->isSplat()) {
4368 if (isMMX || NumElems < 4)
4370 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4373 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4375 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4376 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4377 if (NewOp.getNode())
4378 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4379 LowerVECTOR_SHUFFLE(NewOp, DAG));
4380 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4381 // FIXME: Figure out a cleaner way to do this.
4382 // Try to make use of movq to zero out the top part.
4383 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4384 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4385 if (NewOp.getNode()) {
4386 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4387 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4388 DAG, Subtarget, dl);
4390 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4391 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4392 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4393 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4394 DAG, Subtarget, dl);
4398 if (X86::isPSHUFDMask(SVOp))
4401 // Check if this can be converted into a logical shift.
4402 bool isLeft = false;
4405 bool isShift = getSubtarget()->hasSSE2() &&
4406 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4407 if (isShift && ShVal.hasOneUse()) {
4408 // If the shifted value has multiple uses, it may be cheaper to use
4409 // v_set0 + movlhps or movhlps, etc.
4410 EVT EltVT = VT.getVectorElementType();
4411 ShAmt *= EltVT.getSizeInBits();
4412 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4415 if (X86::isMOVLMask(SVOp)) {
4418 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4419 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4424 // FIXME: fold these into legal mask.
4425 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4426 X86::isMOVSLDUPMask(SVOp) ||
4427 X86::isMOVHLPSMask(SVOp) ||
4428 X86::isMOVLHPSMask(SVOp) ||
4429 X86::isMOVLPMask(SVOp)))
4432 if (ShouldXformToMOVHLPS(SVOp) ||
4433 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4434 return CommuteVectorShuffle(SVOp, DAG);
4437 // No better options. Use a vshl / vsrl.
4438 EVT EltVT = VT.getVectorElementType();
4439 ShAmt *= EltVT.getSizeInBits();
4440 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4443 bool Commuted = false;
4444 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4445 // 1,1,1,1 -> v8i16 though.
4446 V1IsSplat = isSplatVector(V1.getNode());
4447 V2IsSplat = isSplatVector(V2.getNode());
4449 // Canonicalize the splat or undef, if present, to be on the RHS.
4450 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4451 Op = CommuteVectorShuffle(SVOp, DAG);
4452 SVOp = cast<ShuffleVectorSDNode>(Op);
4453 V1 = SVOp->getOperand(0);
4454 V2 = SVOp->getOperand(1);
4455 std::swap(V1IsSplat, V2IsSplat);
4456 std::swap(V1IsUndef, V2IsUndef);
4460 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4461 // Shuffling low element of v1 into undef, just return v1.
4464 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4465 // the instruction selector will not match, so get a canonical MOVL with
4466 // swapped operands to undo the commute.
4467 return getMOVL(DAG, dl, VT, V2, V1);
4470 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4471 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4472 X86::isUNPCKLMask(SVOp) ||
4473 X86::isUNPCKHMask(SVOp))
4477 // Normalize mask so all entries that point to V2 points to its first
4478 // element then try to match unpck{h|l} again. If match, return a
4479 // new vector_shuffle with the corrected mask.
4480 SDValue NewMask = NormalizeMask(SVOp, DAG);
4481 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4482 if (NSVOp != SVOp) {
4483 if (X86::isUNPCKLMask(NSVOp, true)) {
4485 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4492 // Commute is back and try unpck* again.
4493 // FIXME: this seems wrong.
4494 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4495 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4496 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4497 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4498 X86::isUNPCKLMask(NewSVOp) ||
4499 X86::isUNPCKHMask(NewSVOp))
4503 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4505 // Normalize the node to match x86 shuffle ops if needed
4506 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4507 return CommuteVectorShuffle(SVOp, DAG);
4509 // Check for legal shuffle and return?
4510 SmallVector<int, 16> PermMask;
4511 SVOp->getMask(PermMask);
4512 if (isShuffleMaskLegal(PermMask, VT))
4515 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4516 if (VT == MVT::v8i16) {
4517 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4518 if (NewOp.getNode())
4522 if (VT == MVT::v16i8) {
4523 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4524 if (NewOp.getNode())
4528 // Handle all 4 wide cases with a number of shuffles except for MMX.
4529 if (NumElems == 4 && !isMMX)
4530 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4536 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4537 SelectionDAG &DAG) {
4538 EVT VT = Op.getValueType();
4539 DebugLoc dl = Op.getDebugLoc();
4540 if (VT.getSizeInBits() == 8) {
4541 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4542 Op.getOperand(0), Op.getOperand(1));
4543 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4544 DAG.getValueType(VT));
4545 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4546 } else if (VT.getSizeInBits() == 16) {
4547 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4548 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4550 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4551 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4552 DAG.getNode(ISD::BIT_CONVERT, dl,
4556 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4557 Op.getOperand(0), Op.getOperand(1));
4558 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4559 DAG.getValueType(VT));
4560 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4561 } else if (VT == MVT::f32) {
4562 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4563 // the result back to FR32 register. It's only worth matching if the
4564 // result has a single use which is a store or a bitcast to i32. And in
4565 // the case of a store, it's not worth it if the index is a constant 0,
4566 // because a MOVSSmr can be used instead, which is smaller and faster.
4567 if (!Op.hasOneUse())
4569 SDNode *User = *Op.getNode()->use_begin();
4570 if ((User->getOpcode() != ISD::STORE ||
4571 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4572 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4573 (User->getOpcode() != ISD::BIT_CONVERT ||
4574 User->getValueType(0) != MVT::i32))
4576 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4577 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4580 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4581 } else if (VT == MVT::i32) {
4582 // ExtractPS works with constant index.
4583 if (isa<ConstantSDNode>(Op.getOperand(1)))
4591 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4592 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4595 if (Subtarget->hasSSE41()) {
4596 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4601 EVT VT = Op.getValueType();
4602 DebugLoc dl = Op.getDebugLoc();
4603 // TODO: handle v16i8.
4604 if (VT.getSizeInBits() == 16) {
4605 SDValue Vec = Op.getOperand(0);
4606 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4608 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4609 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4610 DAG.getNode(ISD::BIT_CONVERT, dl,
4613 // Transform it so it match pextrw which produces a 32-bit result.
4614 EVT EltVT = MVT::i32;
4615 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4616 Op.getOperand(0), Op.getOperand(1));
4617 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4618 DAG.getValueType(VT));
4619 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4620 } else if (VT.getSizeInBits() == 32) {
4621 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4625 // SHUFPS the element to the lowest double word, then movss.
4626 int Mask[4] = { Idx, -1, -1, -1 };
4627 EVT VVT = Op.getOperand(0).getValueType();
4628 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4629 DAG.getUNDEF(VVT), Mask);
4630 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4631 DAG.getIntPtrConstant(0));
4632 } else if (VT.getSizeInBits() == 64) {
4633 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4634 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4635 // to match extract_elt for f64.
4636 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4640 // UNPCKHPD the element to the lowest double word, then movsd.
4641 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4642 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4643 int Mask[2] = { 1, -1 };
4644 EVT VVT = Op.getOperand(0).getValueType();
4645 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4646 DAG.getUNDEF(VVT), Mask);
4647 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4648 DAG.getIntPtrConstant(0));
4655 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4656 EVT VT = Op.getValueType();
4657 EVT EltVT = VT.getVectorElementType();
4658 DebugLoc dl = Op.getDebugLoc();
4660 SDValue N0 = Op.getOperand(0);
4661 SDValue N1 = Op.getOperand(1);
4662 SDValue N2 = Op.getOperand(2);
4664 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4665 isa<ConstantSDNode>(N2)) {
4666 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4668 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4670 if (N1.getValueType() != MVT::i32)
4671 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4672 if (N2.getValueType() != MVT::i32)
4673 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4674 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4675 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4676 // Bits [7:6] of the constant are the source select. This will always be
4677 // zero here. The DAG Combiner may combine an extract_elt index into these
4678 // bits. For example (insert (extract, 3), 2) could be matched by putting
4679 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4680 // Bits [5:4] of the constant are the destination select. This is the
4681 // value of the incoming immediate.
4682 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4683 // combine either bitwise AND or insert of float 0.0 to set these bits.
4684 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4685 // Create this as a scalar to vector..
4686 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4687 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4688 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4689 // PINSR* works with constant index.
4696 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4697 EVT VT = Op.getValueType();
4698 EVT EltVT = VT.getVectorElementType();
4700 if (Subtarget->hasSSE41())
4701 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4703 if (EltVT == MVT::i8)
4706 DebugLoc dl = Op.getDebugLoc();
4707 SDValue N0 = Op.getOperand(0);
4708 SDValue N1 = Op.getOperand(1);
4709 SDValue N2 = Op.getOperand(2);
4711 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4712 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4713 // as its second argument.
4714 if (N1.getValueType() != MVT::i32)
4715 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4716 if (N2.getValueType() != MVT::i32)
4717 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4718 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4724 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4725 DebugLoc dl = Op.getDebugLoc();
4726 if (Op.getValueType() == MVT::v2f32)
4727 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4728 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4729 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4730 Op.getOperand(0))));
4732 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4733 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4735 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4736 EVT VT = MVT::v2i32;
4737 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4744 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4745 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4748 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4749 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4750 // one of the above mentioned nodes. It has to be wrapped because otherwise
4751 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4752 // be used to form addressing mode. These wrapped nodes will be selected
4755 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4756 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4758 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4760 unsigned char OpFlag = 0;
4761 unsigned WrapperKind = X86ISD::Wrapper;
4762 CodeModel::Model M = getTargetMachine().getCodeModel();
4764 if (Subtarget->isPICStyleRIPRel() &&
4765 (M == CodeModel::Small || M == CodeModel::Kernel))
4766 WrapperKind = X86ISD::WrapperRIP;
4767 else if (Subtarget->isPICStyleGOT())
4768 OpFlag = X86II::MO_GOTOFF;
4769 else if (Subtarget->isPICStyleStubPIC())
4770 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4772 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4774 CP->getOffset(), OpFlag);
4775 DebugLoc DL = CP->getDebugLoc();
4776 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4777 // With PIC, the address is actually $g + Offset.
4779 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4780 DAG.getNode(X86ISD::GlobalBaseReg,
4781 DebugLoc::getUnknownLoc(), getPointerTy()),
4788 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4789 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4791 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4793 unsigned char OpFlag = 0;
4794 unsigned WrapperKind = X86ISD::Wrapper;
4795 CodeModel::Model M = getTargetMachine().getCodeModel();
4797 if (Subtarget->isPICStyleRIPRel() &&
4798 (M == CodeModel::Small || M == CodeModel::Kernel))
4799 WrapperKind = X86ISD::WrapperRIP;
4800 else if (Subtarget->isPICStyleGOT())
4801 OpFlag = X86II::MO_GOTOFF;
4802 else if (Subtarget->isPICStyleStubPIC())
4803 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4805 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4807 DebugLoc DL = JT->getDebugLoc();
4808 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4810 // With PIC, the address is actually $g + Offset.
4812 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4813 DAG.getNode(X86ISD::GlobalBaseReg,
4814 DebugLoc::getUnknownLoc(), getPointerTy()),
4822 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4823 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4825 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4827 unsigned char OpFlag = 0;
4828 unsigned WrapperKind = X86ISD::Wrapper;
4829 CodeModel::Model M = getTargetMachine().getCodeModel();
4831 if (Subtarget->isPICStyleRIPRel() &&
4832 (M == CodeModel::Small || M == CodeModel::Kernel))
4833 WrapperKind = X86ISD::WrapperRIP;
4834 else if (Subtarget->isPICStyleGOT())
4835 OpFlag = X86II::MO_GOTOFF;
4836 else if (Subtarget->isPICStyleStubPIC())
4837 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4839 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4841 DebugLoc DL = Op.getDebugLoc();
4842 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4845 // With PIC, the address is actually $g + Offset.
4846 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4847 !Subtarget->is64Bit()) {
4848 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4849 DAG.getNode(X86ISD::GlobalBaseReg,
4850 DebugLoc::getUnknownLoc(),
4859 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4860 // Create the TargetBlockAddressAddress node.
4861 unsigned char OpFlags =
4862 Subtarget->ClassifyBlockAddressReference();
4863 CodeModel::Model M = getTargetMachine().getCodeModel();
4864 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4865 DebugLoc dl = Op.getDebugLoc();
4866 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4867 /*isTarget=*/true, OpFlags);
4869 if (Subtarget->isPICStyleRIPRel() &&
4870 (M == CodeModel::Small || M == CodeModel::Kernel))
4871 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4873 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4875 // With PIC, the address is actually $g + Offset.
4876 if (isGlobalRelativeToPICBase(OpFlags)) {
4877 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4878 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4886 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4888 SelectionDAG &DAG) const {
4889 // Create the TargetGlobalAddress node, folding in the constant
4890 // offset if it is legal.
4891 unsigned char OpFlags =
4892 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4893 CodeModel::Model M = getTargetMachine().getCodeModel();
4895 if (OpFlags == X86II::MO_NO_FLAG &&
4896 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4897 // A direct static reference to a global.
4898 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4901 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4904 if (Subtarget->isPICStyleRIPRel() &&
4905 (M == CodeModel::Small || M == CodeModel::Kernel))
4906 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4908 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4910 // With PIC, the address is actually $g + Offset.
4911 if (isGlobalRelativeToPICBase(OpFlags)) {
4912 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4913 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4917 // For globals that require a load from a stub to get the address, emit the
4919 if (isGlobalStubReference(OpFlags))
4920 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4921 PseudoSourceValue::getGOT(), 0);
4923 // If there was a non-zero offset that we didn't fold, create an explicit
4926 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4927 DAG.getConstant(Offset, getPointerTy()));
4933 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4934 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4935 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4936 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4940 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4941 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4942 unsigned char OperandFlags) {
4943 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4944 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4945 DebugLoc dl = GA->getDebugLoc();
4946 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4947 GA->getValueType(0),
4951 SDValue Ops[] = { Chain, TGA, *InFlag };
4952 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4954 SDValue Ops[] = { Chain, TGA };
4955 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4958 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
4959 MFI->setHasCalls(true);
4961 SDValue Flag = Chain.getValue(1);
4962 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4965 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4967 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4970 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4971 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4972 DAG.getNode(X86ISD::GlobalBaseReg,
4973 DebugLoc::getUnknownLoc(),
4975 InFlag = Chain.getValue(1);
4977 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4980 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4982 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4984 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4985 X86::RAX, X86II::MO_TLSGD);
4988 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4989 // "local exec" model.
4990 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4991 const EVT PtrVT, TLSModel::Model model,
4993 DebugLoc dl = GA->getDebugLoc();
4994 // Get the Thread Pointer
4995 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4996 DebugLoc::getUnknownLoc(), PtrVT,
4997 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5000 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5003 unsigned char OperandFlags = 0;
5004 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5006 unsigned WrapperKind = X86ISD::Wrapper;
5007 if (model == TLSModel::LocalExec) {
5008 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5009 } else if (is64Bit) {
5010 assert(model == TLSModel::InitialExec);
5011 OperandFlags = X86II::MO_GOTTPOFF;
5012 WrapperKind = X86ISD::WrapperRIP;
5014 assert(model == TLSModel::InitialExec);
5015 OperandFlags = X86II::MO_INDNTPOFF;
5018 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5020 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5021 GA->getOffset(), OperandFlags);
5022 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5024 if (model == TLSModel::InitialExec)
5025 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5026 PseudoSourceValue::getGOT(), 0);
5028 // The address of the thread local variable is the add of the thread
5029 // pointer with the offset of the variable.
5030 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5034 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5035 // TODO: implement the "local dynamic" model
5036 // TODO: implement the "initial exec"model for pic executables
5037 assert(Subtarget->isTargetELF() &&
5038 "TLS not implemented for non-ELF targets");
5039 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5040 const GlobalValue *GV = GA->getGlobal();
5042 // If GV is an alias then use the aliasee for determining
5043 // thread-localness.
5044 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5045 GV = GA->resolveAliasedGlobal(false);
5047 TLSModel::Model model = getTLSModel(GV,
5048 getTargetMachine().getRelocationModel());
5051 case TLSModel::GeneralDynamic:
5052 case TLSModel::LocalDynamic: // not implemented
5053 if (Subtarget->is64Bit())
5054 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5055 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5057 case TLSModel::InitialExec:
5058 case TLSModel::LocalExec:
5059 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5060 Subtarget->is64Bit());
5063 llvm_unreachable("Unreachable");
5068 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5069 /// take a 2 x i32 value to shift plus a shift amount.
5070 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5071 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5072 EVT VT = Op.getValueType();
5073 unsigned VTBits = VT.getSizeInBits();
5074 DebugLoc dl = Op.getDebugLoc();
5075 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5076 SDValue ShOpLo = Op.getOperand(0);
5077 SDValue ShOpHi = Op.getOperand(1);
5078 SDValue ShAmt = Op.getOperand(2);
5079 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5080 DAG.getConstant(VTBits - 1, MVT::i8))
5081 : DAG.getConstant(0, VT);
5084 if (Op.getOpcode() == ISD::SHL_PARTS) {
5085 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5086 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5088 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5089 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5092 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5093 DAG.getConstant(VTBits, MVT::i8));
5094 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5095 AndNode, DAG.getConstant(0, MVT::i8));
5098 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5099 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5100 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5102 if (Op.getOpcode() == ISD::SHL_PARTS) {
5103 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5104 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5106 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5107 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5110 SDValue Ops[2] = { Lo, Hi };
5111 return DAG.getMergeValues(Ops, 2, dl);
5114 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5115 EVT SrcVT = Op.getOperand(0).getValueType();
5117 if (SrcVT.isVector()) {
5118 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5124 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5125 "Unknown SINT_TO_FP to lower!");
5127 // These are really Legal; return the operand so the caller accepts it as
5129 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5131 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5132 Subtarget->is64Bit()) {
5136 DebugLoc dl = Op.getDebugLoc();
5137 unsigned Size = SrcVT.getSizeInBits()/8;
5138 MachineFunction &MF = DAG.getMachineFunction();
5139 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5140 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5141 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5143 PseudoSourceValue::getFixedStack(SSFI), 0);
5144 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5147 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5149 SelectionDAG &DAG) {
5151 DebugLoc dl = Op.getDebugLoc();
5153 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5155 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5157 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5158 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5159 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5160 Tys, Ops, array_lengthof(Ops));
5163 Chain = Result.getValue(1);
5164 SDValue InFlag = Result.getValue(2);
5166 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5167 // shouldn't be necessary except that RFP cannot be live across
5168 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5169 MachineFunction &MF = DAG.getMachineFunction();
5170 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5171 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5172 Tys = DAG.getVTList(MVT::Other);
5174 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5176 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5177 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5178 PseudoSourceValue::getFixedStack(SSFI), 0);
5184 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5185 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5186 // This algorithm is not obvious. Here it is in C code, more or less:
5188 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5189 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5190 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5192 // Copy ints to xmm registers.
5193 __m128i xh = _mm_cvtsi32_si128( hi );
5194 __m128i xl = _mm_cvtsi32_si128( lo );
5196 // Combine into low half of a single xmm register.
5197 __m128i x = _mm_unpacklo_epi32( xh, xl );
5201 // Merge in appropriate exponents to give the integer bits the right
5203 x = _mm_unpacklo_epi32( x, exp );
5205 // Subtract away the biases to deal with the IEEE-754 double precision
5207 d = _mm_sub_pd( (__m128d) x, bias );
5209 // All conversions up to here are exact. The correctly rounded result is
5210 // calculated using the current rounding mode using the following
5212 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5213 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5214 // store doesn't really need to be here (except
5215 // maybe to zero the other double)
5220 DebugLoc dl = Op.getDebugLoc();
5221 LLVMContext *Context = DAG.getContext();
5223 // Build some magic constants.
5224 std::vector<Constant*> CV0;
5225 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5226 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5227 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5228 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5229 Constant *C0 = ConstantVector::get(CV0);
5230 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5232 std::vector<Constant*> CV1;
5234 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5236 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5237 Constant *C1 = ConstantVector::get(CV1);
5238 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5240 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5241 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5243 DAG.getIntPtrConstant(1)));
5244 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5245 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5247 DAG.getIntPtrConstant(0)));
5248 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5249 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5250 PseudoSourceValue::getConstantPool(), 0,
5252 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5253 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5254 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5255 PseudoSourceValue::getConstantPool(), 0,
5257 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5259 // Add the halves; easiest way is to swap them into another reg first.
5260 int ShufMask[2] = { 1, -1 };
5261 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5262 DAG.getUNDEF(MVT::v2f64), ShufMask);
5263 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5264 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5265 DAG.getIntPtrConstant(0));
5268 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5269 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5270 DebugLoc dl = Op.getDebugLoc();
5271 // FP constant to bias correct the final result.
5272 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5275 // Load the 32-bit value into an XMM register.
5276 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5277 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5279 DAG.getIntPtrConstant(0)));
5281 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5282 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5283 DAG.getIntPtrConstant(0));
5285 // Or the load with the bias.
5286 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5287 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5288 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5290 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5291 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5292 MVT::v2f64, Bias)));
5293 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5294 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5295 DAG.getIntPtrConstant(0));
5297 // Subtract the bias.
5298 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5300 // Handle final rounding.
5301 EVT DestVT = Op.getValueType();
5303 if (DestVT.bitsLT(MVT::f64)) {
5304 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5305 DAG.getIntPtrConstant(0));
5306 } else if (DestVT.bitsGT(MVT::f64)) {
5307 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5310 // Handle final rounding.
5314 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5315 SDValue N0 = Op.getOperand(0);
5316 DebugLoc dl = Op.getDebugLoc();
5318 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5319 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5320 // the optimization here.
5321 if (DAG.SignBitIsZero(N0))
5322 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5324 EVT SrcVT = N0.getValueType();
5325 if (SrcVT == MVT::i64) {
5326 // We only handle SSE2 f64 target here; caller can expand the rest.
5327 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5330 return LowerUINT_TO_FP_i64(Op, DAG);
5331 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5332 return LowerUINT_TO_FP_i32(Op, DAG);
5335 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5337 // Make a 64-bit buffer, and use it to build an FILD.
5338 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5339 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5340 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5341 getPointerTy(), StackSlot, WordOff);
5342 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5343 StackSlot, NULL, 0);
5344 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5345 OffsetSlot, NULL, 0);
5346 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5349 std::pair<SDValue,SDValue> X86TargetLowering::
5350 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5351 DebugLoc dl = Op.getDebugLoc();
5353 EVT DstTy = Op.getValueType();
5356 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5360 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5361 DstTy.getSimpleVT() >= MVT::i16 &&
5362 "Unknown FP_TO_SINT to lower!");
5364 // These are really Legal.
5365 if (DstTy == MVT::i32 &&
5366 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5367 return std::make_pair(SDValue(), SDValue());
5368 if (Subtarget->is64Bit() &&
5369 DstTy == MVT::i64 &&
5370 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5371 return std::make_pair(SDValue(), SDValue());
5373 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5375 MachineFunction &MF = DAG.getMachineFunction();
5376 unsigned MemSize = DstTy.getSizeInBits()/8;
5377 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5378 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5381 switch (DstTy.getSimpleVT().SimpleTy) {
5382 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5383 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5384 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5385 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5388 SDValue Chain = DAG.getEntryNode();
5389 SDValue Value = Op.getOperand(0);
5390 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5391 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5392 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5393 PseudoSourceValue::getFixedStack(SSFI), 0);
5394 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5396 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5398 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5399 Chain = Value.getValue(1);
5400 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5401 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5404 // Build the FP_TO_INT*_IN_MEM
5405 SDValue Ops[] = { Chain, Value, StackSlot };
5406 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5408 return std::make_pair(FIST, StackSlot);
5411 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5412 if (Op.getValueType().isVector()) {
5413 if (Op.getValueType() == MVT::v2i32 &&
5414 Op.getOperand(0).getValueType() == MVT::v2f64) {
5420 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5421 SDValue FIST = Vals.first, StackSlot = Vals.second;
5422 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5423 if (FIST.getNode() == 0) return Op;
5426 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5427 FIST, StackSlot, NULL, 0);
5430 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5431 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5432 SDValue FIST = Vals.first, StackSlot = Vals.second;
5433 assert(FIST.getNode() && "Unexpected failure");
5436 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5437 FIST, StackSlot, NULL, 0);
5440 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5441 LLVMContext *Context = DAG.getContext();
5442 DebugLoc dl = Op.getDebugLoc();
5443 EVT VT = Op.getValueType();
5446 EltVT = VT.getVectorElementType();
5447 std::vector<Constant*> CV;
5448 if (EltVT == MVT::f64) {
5449 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5453 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5459 Constant *C = ConstantVector::get(CV);
5460 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5461 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5462 PseudoSourceValue::getConstantPool(), 0,
5464 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5467 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5468 LLVMContext *Context = DAG.getContext();
5469 DebugLoc dl = Op.getDebugLoc();
5470 EVT VT = Op.getValueType();
5473 EltVT = VT.getVectorElementType();
5474 std::vector<Constant*> CV;
5475 if (EltVT == MVT::f64) {
5476 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5480 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5486 Constant *C = ConstantVector::get(CV);
5487 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5488 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5489 PseudoSourceValue::getConstantPool(), 0,
5491 if (VT.isVector()) {
5492 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5493 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5494 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5496 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5498 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5502 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5503 LLVMContext *Context = DAG.getContext();
5504 SDValue Op0 = Op.getOperand(0);
5505 SDValue Op1 = Op.getOperand(1);
5506 DebugLoc dl = Op.getDebugLoc();
5507 EVT VT = Op.getValueType();
5508 EVT SrcVT = Op1.getValueType();
5510 // If second operand is smaller, extend it first.
5511 if (SrcVT.bitsLT(VT)) {
5512 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5515 // And if it is bigger, shrink it first.
5516 if (SrcVT.bitsGT(VT)) {
5517 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5521 // At this point the operands and the result should have the same
5522 // type, and that won't be f80 since that is not custom lowered.
5524 // First get the sign bit of second operand.
5525 std::vector<Constant*> CV;
5526 if (SrcVT == MVT::f64) {
5527 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5528 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5530 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5531 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5532 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5533 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5535 Constant *C = ConstantVector::get(CV);
5536 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5537 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5538 PseudoSourceValue::getConstantPool(), 0,
5540 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5542 // Shift sign bit right or left if the two operands have different types.
5543 if (SrcVT.bitsGT(VT)) {
5544 // Op0 is MVT::f32, Op1 is MVT::f64.
5545 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5546 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5547 DAG.getConstant(32, MVT::i32));
5548 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5549 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5550 DAG.getIntPtrConstant(0));
5553 // Clear first operand sign bit.
5555 if (VT == MVT::f64) {
5556 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5557 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5559 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5560 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5561 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5562 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5564 C = ConstantVector::get(CV);
5565 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5566 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5567 PseudoSourceValue::getConstantPool(), 0,
5569 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5571 // Or the value with the sign bit.
5572 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5575 /// Emit nodes that will be selected as "test Op0,Op0", or something
5577 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5578 SelectionDAG &DAG) {
5579 DebugLoc dl = Op.getDebugLoc();
5581 // CF and OF aren't always set the way we want. Determine which
5582 // of these we need.
5583 bool NeedCF = false;
5584 bool NeedOF = false;
5586 case X86::COND_A: case X86::COND_AE:
5587 case X86::COND_B: case X86::COND_BE:
5590 case X86::COND_G: case X86::COND_GE:
5591 case X86::COND_L: case X86::COND_LE:
5592 case X86::COND_O: case X86::COND_NO:
5598 // See if we can use the EFLAGS value from the operand instead of
5599 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5600 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5601 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5602 unsigned Opcode = 0;
5603 unsigned NumOperands = 0;
5604 switch (Op.getNode()->getOpcode()) {
5606 // Due to an isel shortcoming, be conservative if this add is likely to
5607 // be selected as part of a load-modify-store instruction. When the root
5608 // node in a match is a store, isel doesn't know how to remap non-chain
5609 // non-flag uses of other nodes in the match, such as the ADD in this
5610 // case. This leads to the ADD being left around and reselected, with
5611 // the result being two adds in the output.
5612 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5613 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5614 if (UI->getOpcode() == ISD::STORE)
5616 if (ConstantSDNode *C =
5617 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5618 // An add of one will be selected as an INC.
5619 if (C->getAPIntValue() == 1) {
5620 Opcode = X86ISD::INC;
5624 // An add of negative one (subtract of one) will be selected as a DEC.
5625 if (C->getAPIntValue().isAllOnesValue()) {
5626 Opcode = X86ISD::DEC;
5631 // Otherwise use a regular EFLAGS-setting add.
5632 Opcode = X86ISD::ADD;
5636 // If the primary and result isn't used, don't bother using X86ISD::AND,
5637 // because a TEST instruction will be better.
5638 bool NonFlagUse = false;
5639 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5640 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5642 unsigned UOpNo = UI.getOperandNo();
5643 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5644 // Look pass truncate.
5645 UOpNo = User->use_begin().getOperandNo();
5646 User = *User->use_begin();
5648 if (User->getOpcode() != ISD::BRCOND &&
5649 User->getOpcode() != ISD::SETCC &&
5650 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5662 // Due to the ISEL shortcoming noted above, be conservative if this op is
5663 // likely to be selected as part of a load-modify-store instruction.
5664 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5665 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5666 if (UI->getOpcode() == ISD::STORE)
5668 // Otherwise use a regular EFLAGS-setting instruction.
5669 switch (Op.getNode()->getOpcode()) {
5670 case ISD::SUB: Opcode = X86ISD::SUB; break;
5671 case ISD::OR: Opcode = X86ISD::OR; break;
5672 case ISD::XOR: Opcode = X86ISD::XOR; break;
5673 case ISD::AND: Opcode = X86ISD::AND; break;
5674 default: llvm_unreachable("unexpected operator!");
5685 return SDValue(Op.getNode(), 1);
5691 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5692 SmallVector<SDValue, 4> Ops;
5693 for (unsigned i = 0; i != NumOperands; ++i)
5694 Ops.push_back(Op.getOperand(i));
5695 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5696 DAG.ReplaceAllUsesWith(Op, New);
5697 return SDValue(New.getNode(), 1);
5701 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5702 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5703 DAG.getConstant(0, Op.getValueType()));
5706 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5708 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5709 SelectionDAG &DAG) {
5710 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5711 if (C->getAPIntValue() == 0)
5712 return EmitTest(Op0, X86CC, DAG);
5714 DebugLoc dl = Op0.getDebugLoc();
5715 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5718 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5719 /// if it's possible.
5720 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5721 DebugLoc dl, SelectionDAG &DAG) {
5723 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5724 if (ConstantSDNode *Op010C =
5725 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5726 if (Op010C->getZExtValue() == 1) {
5727 LHS = Op0.getOperand(0);
5728 RHS = Op0.getOperand(1).getOperand(1);
5730 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5731 if (ConstantSDNode *Op000C =
5732 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5733 if (Op000C->getZExtValue() == 1) {
5734 LHS = Op0.getOperand(1);
5735 RHS = Op0.getOperand(0).getOperand(1);
5737 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5738 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5739 SDValue AndLHS = Op0.getOperand(0);
5740 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5741 LHS = AndLHS.getOperand(0);
5742 RHS = AndLHS.getOperand(1);
5746 if (LHS.getNode()) {
5747 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5748 // instruction. Since the shift amount is in-range-or-undefined, we know
5749 // that doing a bittest on the i16 value is ok. We extend to i32 because
5750 // the encoding for the i16 version is larger than the i32 version.
5751 if (LHS.getValueType() == MVT::i8)
5752 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5754 // If the operand types disagree, extend the shift amount to match. Since
5755 // BT ignores high bits (like shifts) we can use anyextend.
5756 if (LHS.getValueType() != RHS.getValueType())
5757 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5759 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5760 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5761 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5762 DAG.getConstant(Cond, MVT::i8), BT);
5768 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5769 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5770 SDValue Op0 = Op.getOperand(0);
5771 SDValue Op1 = Op.getOperand(1);
5772 DebugLoc dl = Op.getDebugLoc();
5773 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5775 // Optimize to BT if possible.
5776 // Lower (X & (1 << N)) == 0 to BT(X, N).
5777 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5778 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5779 if (Op0.getOpcode() == ISD::AND &&
5781 Op1.getOpcode() == ISD::Constant &&
5782 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5783 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5784 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5785 if (NewSetCC.getNode())
5789 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5790 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5791 if (X86CC == X86::COND_INVALID)
5794 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5796 // Use sbb x, x to materialize carry bit into a GPR.
5797 if (X86CC == X86::COND_B)
5798 return DAG.getNode(ISD::AND, dl, MVT::i8,
5799 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5800 DAG.getConstant(X86CC, MVT::i8), Cond),
5801 DAG.getConstant(1, MVT::i8));
5803 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5804 DAG.getConstant(X86CC, MVT::i8), Cond);
5807 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5809 SDValue Op0 = Op.getOperand(0);
5810 SDValue Op1 = Op.getOperand(1);
5811 SDValue CC = Op.getOperand(2);
5812 EVT VT = Op.getValueType();
5813 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5814 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5815 DebugLoc dl = Op.getDebugLoc();
5819 EVT VT0 = Op0.getValueType();
5820 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5821 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5824 switch (SetCCOpcode) {
5827 case ISD::SETEQ: SSECC = 0; break;
5829 case ISD::SETGT: Swap = true; // Fallthrough
5831 case ISD::SETOLT: SSECC = 1; break;
5833 case ISD::SETGE: Swap = true; // Fallthrough
5835 case ISD::SETOLE: SSECC = 2; break;
5836 case ISD::SETUO: SSECC = 3; break;
5838 case ISD::SETNE: SSECC = 4; break;
5839 case ISD::SETULE: Swap = true;
5840 case ISD::SETUGE: SSECC = 5; break;
5841 case ISD::SETULT: Swap = true;
5842 case ISD::SETUGT: SSECC = 6; break;
5843 case ISD::SETO: SSECC = 7; break;
5846 std::swap(Op0, Op1);
5848 // In the two special cases we can't handle, emit two comparisons.
5850 if (SetCCOpcode == ISD::SETUEQ) {
5852 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5853 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5854 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5856 else if (SetCCOpcode == ISD::SETONE) {
5858 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5859 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5860 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5862 llvm_unreachable("Illegal FP comparison");
5864 // Handle all other FP comparisons here.
5865 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5868 // We are handling one of the integer comparisons here. Since SSE only has
5869 // GT and EQ comparisons for integer, swapping operands and multiple
5870 // operations may be required for some comparisons.
5871 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5872 bool Swap = false, Invert = false, FlipSigns = false;
5874 switch (VT.getSimpleVT().SimpleTy) {
5877 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5879 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5881 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5882 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5885 switch (SetCCOpcode) {
5887 case ISD::SETNE: Invert = true;
5888 case ISD::SETEQ: Opc = EQOpc; break;
5889 case ISD::SETLT: Swap = true;
5890 case ISD::SETGT: Opc = GTOpc; break;
5891 case ISD::SETGE: Swap = true;
5892 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5893 case ISD::SETULT: Swap = true;
5894 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5895 case ISD::SETUGE: Swap = true;
5896 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5899 std::swap(Op0, Op1);
5901 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5902 // bits of the inputs before performing those operations.
5904 EVT EltVT = VT.getVectorElementType();
5905 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5907 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5908 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5910 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5911 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5914 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5916 // If the logical-not of the result is required, perform that now.
5918 Result = DAG.getNOT(dl, Result, VT);
5923 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5924 static bool isX86LogicalCmp(SDValue Op) {
5925 unsigned Opc = Op.getNode()->getOpcode();
5926 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5928 if (Op.getResNo() == 1 &&
5929 (Opc == X86ISD::ADD ||
5930 Opc == X86ISD::SUB ||
5931 Opc == X86ISD::SMUL ||
5932 Opc == X86ISD::UMUL ||
5933 Opc == X86ISD::INC ||
5934 Opc == X86ISD::DEC ||
5935 Opc == X86ISD::OR ||
5936 Opc == X86ISD::XOR ||
5937 Opc == X86ISD::AND))
5943 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5944 bool addTest = true;
5945 SDValue Cond = Op.getOperand(0);
5946 DebugLoc dl = Op.getDebugLoc();
5949 if (Cond.getOpcode() == ISD::SETCC) {
5950 SDValue NewCond = LowerSETCC(Cond, DAG);
5951 if (NewCond.getNode())
5955 // Look pass (and (setcc_carry (cmp ...)), 1).
5956 if (Cond.getOpcode() == ISD::AND &&
5957 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
5958 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5959 if (C && C->getAPIntValue() == 1)
5960 Cond = Cond.getOperand(0);
5963 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5964 // setting operand in place of the X86ISD::SETCC.
5965 if (Cond.getOpcode() == X86ISD::SETCC ||
5966 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
5967 CC = Cond.getOperand(0);
5969 SDValue Cmp = Cond.getOperand(1);
5970 unsigned Opc = Cmp.getOpcode();
5971 EVT VT = Op.getValueType();
5973 bool IllegalFPCMov = false;
5974 if (VT.isFloatingPoint() && !VT.isVector() &&
5975 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5976 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5978 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5979 Opc == X86ISD::BT) { // FIXME
5986 // Look pass the truncate.
5987 if (Cond.getOpcode() == ISD::TRUNCATE)
5988 Cond = Cond.getOperand(0);
5990 // We know the result of AND is compared against zero. Try to match
5992 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
5993 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
5994 if (NewSetCC.getNode()) {
5995 CC = NewSetCC.getOperand(0);
5996 Cond = NewSetCC.getOperand(1);
6003 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6004 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6007 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6008 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6009 // condition is true.
6010 SDValue Ops[] = { Op.getOperand(2), Op.getOperand(1), CC, Cond };
6011 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6014 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6015 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6016 // from the AND / OR.
6017 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6018 Opc = Op.getOpcode();
6019 if (Opc != ISD::OR && Opc != ISD::AND)
6021 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6022 Op.getOperand(0).hasOneUse() &&
6023 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6024 Op.getOperand(1).hasOneUse());
6027 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6028 // 1 and that the SETCC node has a single use.
6029 static bool isXor1OfSetCC(SDValue Op) {
6030 if (Op.getOpcode() != ISD::XOR)
6032 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6033 if (N1C && N1C->getAPIntValue() == 1) {
6034 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6035 Op.getOperand(0).hasOneUse();
6040 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6041 bool addTest = true;
6042 SDValue Chain = Op.getOperand(0);
6043 SDValue Cond = Op.getOperand(1);
6044 SDValue Dest = Op.getOperand(2);
6045 DebugLoc dl = Op.getDebugLoc();
6048 if (Cond.getOpcode() == ISD::SETCC) {
6049 SDValue NewCond = LowerSETCC(Cond, DAG);
6050 if (NewCond.getNode())
6054 // FIXME: LowerXALUO doesn't handle these!!
6055 else if (Cond.getOpcode() == X86ISD::ADD ||
6056 Cond.getOpcode() == X86ISD::SUB ||
6057 Cond.getOpcode() == X86ISD::SMUL ||
6058 Cond.getOpcode() == X86ISD::UMUL)
6059 Cond = LowerXALUO(Cond, DAG);
6062 // Look pass (and (setcc_carry (cmp ...)), 1).
6063 if (Cond.getOpcode() == ISD::AND &&
6064 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6066 if (C && C->getAPIntValue() == 1)
6067 Cond = Cond.getOperand(0);
6070 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6071 // setting operand in place of the X86ISD::SETCC.
6072 if (Cond.getOpcode() == X86ISD::SETCC ||
6073 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6074 CC = Cond.getOperand(0);
6076 SDValue Cmp = Cond.getOperand(1);
6077 unsigned Opc = Cmp.getOpcode();
6078 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6079 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6083 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6087 // These can only come from an arithmetic instruction with overflow,
6088 // e.g. SADDO, UADDO.
6089 Cond = Cond.getNode()->getOperand(1);
6096 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6097 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6098 if (CondOpc == ISD::OR) {
6099 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6100 // two branches instead of an explicit OR instruction with a
6102 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6103 isX86LogicalCmp(Cmp)) {
6104 CC = Cond.getOperand(0).getOperand(0);
6105 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6106 Chain, Dest, CC, Cmp);
6107 CC = Cond.getOperand(1).getOperand(0);
6111 } else { // ISD::AND
6112 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6113 // two branches instead of an explicit AND instruction with a
6114 // separate test. However, we only do this if this block doesn't
6115 // have a fall-through edge, because this requires an explicit
6116 // jmp when the condition is false.
6117 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6118 isX86LogicalCmp(Cmp) &&
6119 Op.getNode()->hasOneUse()) {
6120 X86::CondCode CCode =
6121 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6122 CCode = X86::GetOppositeBranchCondition(CCode);
6123 CC = DAG.getConstant(CCode, MVT::i8);
6124 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6125 // Look for an unconditional branch following this conditional branch.
6126 // We need this because we need to reverse the successors in order
6127 // to implement FCMP_OEQ.
6128 if (User.getOpcode() == ISD::BR) {
6129 SDValue FalseBB = User.getOperand(1);
6131 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6132 assert(NewBR == User);
6135 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6136 Chain, Dest, CC, Cmp);
6137 X86::CondCode CCode =
6138 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6139 CCode = X86::GetOppositeBranchCondition(CCode);
6140 CC = DAG.getConstant(CCode, MVT::i8);
6146 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6147 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6148 // It should be transformed during dag combiner except when the condition
6149 // is set by a arithmetics with overflow node.
6150 X86::CondCode CCode =
6151 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6152 CCode = X86::GetOppositeBranchCondition(CCode);
6153 CC = DAG.getConstant(CCode, MVT::i8);
6154 Cond = Cond.getOperand(0).getOperand(1);
6160 // Look pass the truncate.
6161 if (Cond.getOpcode() == ISD::TRUNCATE)
6162 Cond = Cond.getOperand(0);
6164 // We know the result of AND is compared against zero. Try to match
6166 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6167 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6168 if (NewSetCC.getNode()) {
6169 CC = NewSetCC.getOperand(0);
6170 Cond = NewSetCC.getOperand(1);
6177 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6178 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6180 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6181 Chain, Dest, CC, Cond);
6185 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6186 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6187 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6188 // that the guard pages used by the OS virtual memory manager are allocated in
6189 // correct sequence.
6191 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6192 SelectionDAG &DAG) {
6193 assert(Subtarget->isTargetCygMing() &&
6194 "This should be used only on Cygwin/Mingw targets");
6195 DebugLoc dl = Op.getDebugLoc();
6198 SDValue Chain = Op.getOperand(0);
6199 SDValue Size = Op.getOperand(1);
6200 // FIXME: Ensure alignment here
6204 EVT IntPtr = getPointerTy();
6205 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6207 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6209 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6210 Flag = Chain.getValue(1);
6212 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6213 SDValue Ops[] = { Chain,
6214 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6215 DAG.getRegister(X86::EAX, IntPtr),
6216 DAG.getRegister(X86StackPtr, SPTy),
6218 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6219 Flag = Chain.getValue(1);
6221 Chain = DAG.getCALLSEQ_END(Chain,
6222 DAG.getIntPtrConstant(0, true),
6223 DAG.getIntPtrConstant(0, true),
6226 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6228 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6229 return DAG.getMergeValues(Ops1, 2, dl);
6233 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6235 SDValue Dst, SDValue Src,
6236 SDValue Size, unsigned Align,
6238 uint64_t DstSVOff) {
6239 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6241 // If not DWORD aligned or size is more than the threshold, call the library.
6242 // The libc version is likely to be faster for these cases. It can use the
6243 // address value and run time information about the CPU.
6244 if ((Align & 3) != 0 ||
6246 ConstantSize->getZExtValue() >
6247 getSubtarget()->getMaxInlineSizeThreshold()) {
6248 SDValue InFlag(0, 0);
6250 // Check to see if there is a specialized entry-point for memory zeroing.
6251 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6253 if (const char *bzeroEntry = V &&
6254 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6255 EVT IntPtr = getPointerTy();
6256 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6257 TargetLowering::ArgListTy Args;
6258 TargetLowering::ArgListEntry Entry;
6260 Entry.Ty = IntPtrTy;
6261 Args.push_back(Entry);
6263 Args.push_back(Entry);
6264 std::pair<SDValue,SDValue> CallResult =
6265 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6266 false, false, false, false,
6267 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6268 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6269 DAG.GetOrdering(Chain.getNode()));
6270 return CallResult.second;
6273 // Otherwise have the target-independent code call memset.
6277 uint64_t SizeVal = ConstantSize->getZExtValue();
6278 SDValue InFlag(0, 0);
6281 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6282 unsigned BytesLeft = 0;
6283 bool TwoRepStos = false;
6286 uint64_t Val = ValC->getZExtValue() & 255;
6288 // If the value is a constant, then we can potentially use larger sets.
6289 switch (Align & 3) {
6290 case 2: // WORD aligned
6293 Val = (Val << 8) | Val;
6295 case 0: // DWORD aligned
6298 Val = (Val << 8) | Val;
6299 Val = (Val << 16) | Val;
6300 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6303 Val = (Val << 32) | Val;
6306 default: // Byte aligned
6309 Count = DAG.getIntPtrConstant(SizeVal);
6313 if (AVT.bitsGT(MVT::i8)) {
6314 unsigned UBytes = AVT.getSizeInBits() / 8;
6315 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6316 BytesLeft = SizeVal % UBytes;
6319 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6321 InFlag = Chain.getValue(1);
6324 Count = DAG.getIntPtrConstant(SizeVal);
6325 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6326 InFlag = Chain.getValue(1);
6329 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6332 InFlag = Chain.getValue(1);
6333 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6336 InFlag = Chain.getValue(1);
6338 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6339 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6340 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6343 InFlag = Chain.getValue(1);
6345 EVT CVT = Count.getValueType();
6346 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6347 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6348 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6351 InFlag = Chain.getValue(1);
6352 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6353 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6354 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6355 } else if (BytesLeft) {
6356 // Handle the last 1 - 7 bytes.
6357 unsigned Offset = SizeVal - BytesLeft;
6358 EVT AddrVT = Dst.getValueType();
6359 EVT SizeVT = Size.getValueType();
6361 Chain = DAG.getMemset(Chain, dl,
6362 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6363 DAG.getConstant(Offset, AddrVT)),
6365 DAG.getConstant(BytesLeft, SizeVT),
6366 Align, DstSV, DstSVOff + Offset);
6369 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6374 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6375 SDValue Chain, SDValue Dst, SDValue Src,
6376 SDValue Size, unsigned Align,
6378 const Value *DstSV, uint64_t DstSVOff,
6379 const Value *SrcSV, uint64_t SrcSVOff) {
6380 // This requires the copy size to be a constant, preferrably
6381 // within a subtarget-specific limit.
6382 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6385 uint64_t SizeVal = ConstantSize->getZExtValue();
6386 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6389 /// If not DWORD aligned, call the library.
6390 if ((Align & 3) != 0)
6395 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6398 unsigned UBytes = AVT.getSizeInBits() / 8;
6399 unsigned CountVal = SizeVal / UBytes;
6400 SDValue Count = DAG.getIntPtrConstant(CountVal);
6401 unsigned BytesLeft = SizeVal % UBytes;
6403 SDValue InFlag(0, 0);
6404 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6407 InFlag = Chain.getValue(1);
6408 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6411 InFlag = Chain.getValue(1);
6412 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6415 InFlag = Chain.getValue(1);
6417 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6418 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6419 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6420 array_lengthof(Ops));
6422 SmallVector<SDValue, 4> Results;
6423 Results.push_back(RepMovs);
6425 // Handle the last 1 - 7 bytes.
6426 unsigned Offset = SizeVal - BytesLeft;
6427 EVT DstVT = Dst.getValueType();
6428 EVT SrcVT = Src.getValueType();
6429 EVT SizeVT = Size.getValueType();
6430 Results.push_back(DAG.getMemcpy(Chain, dl,
6431 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6432 DAG.getConstant(Offset, DstVT)),
6433 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6434 DAG.getConstant(Offset, SrcVT)),
6435 DAG.getConstant(BytesLeft, SizeVT),
6436 Align, AlwaysInline,
6437 DstSV, DstSVOff + Offset,
6438 SrcSV, SrcSVOff + Offset));
6441 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6442 &Results[0], Results.size());
6445 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6446 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6447 DebugLoc dl = Op.getDebugLoc();
6449 if (!Subtarget->is64Bit()) {
6450 // vastart just stores the address of the VarArgsFrameIndex slot into the
6451 // memory location argument.
6452 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6453 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6457 // gp_offset (0 - 6 * 8)
6458 // fp_offset (48 - 48 + 8 * 16)
6459 // overflow_arg_area (point to parameters coming in memory).
6461 SmallVector<SDValue, 8> MemOps;
6462 SDValue FIN = Op.getOperand(1);
6464 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6465 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6467 MemOps.push_back(Store);
6470 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6471 FIN, DAG.getIntPtrConstant(4));
6472 Store = DAG.getStore(Op.getOperand(0), dl,
6473 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6475 MemOps.push_back(Store);
6477 // Store ptr to overflow_arg_area
6478 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6479 FIN, DAG.getIntPtrConstant(4));
6480 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6481 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6482 MemOps.push_back(Store);
6484 // Store ptr to reg_save_area.
6485 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6486 FIN, DAG.getIntPtrConstant(8));
6487 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6488 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6489 MemOps.push_back(Store);
6490 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6491 &MemOps[0], MemOps.size());
6494 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6495 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6496 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6497 SDValue Chain = Op.getOperand(0);
6498 SDValue SrcPtr = Op.getOperand(1);
6499 SDValue SrcSV = Op.getOperand(2);
6501 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6505 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6506 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6507 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6508 SDValue Chain = Op.getOperand(0);
6509 SDValue DstPtr = Op.getOperand(1);
6510 SDValue SrcPtr = Op.getOperand(2);
6511 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6512 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6513 DebugLoc dl = Op.getDebugLoc();
6515 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6516 DAG.getIntPtrConstant(24), 8, false,
6517 DstSV, 0, SrcSV, 0);
6521 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6522 DebugLoc dl = Op.getDebugLoc();
6523 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6525 default: return SDValue(); // Don't custom lower most intrinsics.
6526 // Comparison intrinsics.
6527 case Intrinsic::x86_sse_comieq_ss:
6528 case Intrinsic::x86_sse_comilt_ss:
6529 case Intrinsic::x86_sse_comile_ss:
6530 case Intrinsic::x86_sse_comigt_ss:
6531 case Intrinsic::x86_sse_comige_ss:
6532 case Intrinsic::x86_sse_comineq_ss:
6533 case Intrinsic::x86_sse_ucomieq_ss:
6534 case Intrinsic::x86_sse_ucomilt_ss:
6535 case Intrinsic::x86_sse_ucomile_ss:
6536 case Intrinsic::x86_sse_ucomigt_ss:
6537 case Intrinsic::x86_sse_ucomige_ss:
6538 case Intrinsic::x86_sse_ucomineq_ss:
6539 case Intrinsic::x86_sse2_comieq_sd:
6540 case Intrinsic::x86_sse2_comilt_sd:
6541 case Intrinsic::x86_sse2_comile_sd:
6542 case Intrinsic::x86_sse2_comigt_sd:
6543 case Intrinsic::x86_sse2_comige_sd:
6544 case Intrinsic::x86_sse2_comineq_sd:
6545 case Intrinsic::x86_sse2_ucomieq_sd:
6546 case Intrinsic::x86_sse2_ucomilt_sd:
6547 case Intrinsic::x86_sse2_ucomile_sd:
6548 case Intrinsic::x86_sse2_ucomigt_sd:
6549 case Intrinsic::x86_sse2_ucomige_sd:
6550 case Intrinsic::x86_sse2_ucomineq_sd: {
6552 ISD::CondCode CC = ISD::SETCC_INVALID;
6555 case Intrinsic::x86_sse_comieq_ss:
6556 case Intrinsic::x86_sse2_comieq_sd:
6560 case Intrinsic::x86_sse_comilt_ss:
6561 case Intrinsic::x86_sse2_comilt_sd:
6565 case Intrinsic::x86_sse_comile_ss:
6566 case Intrinsic::x86_sse2_comile_sd:
6570 case Intrinsic::x86_sse_comigt_ss:
6571 case Intrinsic::x86_sse2_comigt_sd:
6575 case Intrinsic::x86_sse_comige_ss:
6576 case Intrinsic::x86_sse2_comige_sd:
6580 case Intrinsic::x86_sse_comineq_ss:
6581 case Intrinsic::x86_sse2_comineq_sd:
6585 case Intrinsic::x86_sse_ucomieq_ss:
6586 case Intrinsic::x86_sse2_ucomieq_sd:
6587 Opc = X86ISD::UCOMI;
6590 case Intrinsic::x86_sse_ucomilt_ss:
6591 case Intrinsic::x86_sse2_ucomilt_sd:
6592 Opc = X86ISD::UCOMI;
6595 case Intrinsic::x86_sse_ucomile_ss:
6596 case Intrinsic::x86_sse2_ucomile_sd:
6597 Opc = X86ISD::UCOMI;
6600 case Intrinsic::x86_sse_ucomigt_ss:
6601 case Intrinsic::x86_sse2_ucomigt_sd:
6602 Opc = X86ISD::UCOMI;
6605 case Intrinsic::x86_sse_ucomige_ss:
6606 case Intrinsic::x86_sse2_ucomige_sd:
6607 Opc = X86ISD::UCOMI;
6610 case Intrinsic::x86_sse_ucomineq_ss:
6611 case Intrinsic::x86_sse2_ucomineq_sd:
6612 Opc = X86ISD::UCOMI;
6617 SDValue LHS = Op.getOperand(1);
6618 SDValue RHS = Op.getOperand(2);
6619 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6620 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6621 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6622 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6623 DAG.getConstant(X86CC, MVT::i8), Cond);
6624 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6626 // ptest intrinsics. The intrinsic these come from are designed to return
6627 // an integer value, not just an instruction so lower it to the ptest
6628 // pattern and a setcc for the result.
6629 case Intrinsic::x86_sse41_ptestz:
6630 case Intrinsic::x86_sse41_ptestc:
6631 case Intrinsic::x86_sse41_ptestnzc:{
6634 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6635 case Intrinsic::x86_sse41_ptestz:
6637 X86CC = X86::COND_E;
6639 case Intrinsic::x86_sse41_ptestc:
6641 X86CC = X86::COND_B;
6643 case Intrinsic::x86_sse41_ptestnzc:
6645 X86CC = X86::COND_A;
6649 SDValue LHS = Op.getOperand(1);
6650 SDValue RHS = Op.getOperand(2);
6651 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6652 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6653 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6654 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6657 // Fix vector shift instructions where the last operand is a non-immediate
6659 case Intrinsic::x86_sse2_pslli_w:
6660 case Intrinsic::x86_sse2_pslli_d:
6661 case Intrinsic::x86_sse2_pslli_q:
6662 case Intrinsic::x86_sse2_psrli_w:
6663 case Intrinsic::x86_sse2_psrli_d:
6664 case Intrinsic::x86_sse2_psrli_q:
6665 case Intrinsic::x86_sse2_psrai_w:
6666 case Intrinsic::x86_sse2_psrai_d:
6667 case Intrinsic::x86_mmx_pslli_w:
6668 case Intrinsic::x86_mmx_pslli_d:
6669 case Intrinsic::x86_mmx_pslli_q:
6670 case Intrinsic::x86_mmx_psrli_w:
6671 case Intrinsic::x86_mmx_psrli_d:
6672 case Intrinsic::x86_mmx_psrli_q:
6673 case Intrinsic::x86_mmx_psrai_w:
6674 case Intrinsic::x86_mmx_psrai_d: {
6675 SDValue ShAmt = Op.getOperand(2);
6676 if (isa<ConstantSDNode>(ShAmt))
6679 unsigned NewIntNo = 0;
6680 EVT ShAmtVT = MVT::v4i32;
6682 case Intrinsic::x86_sse2_pslli_w:
6683 NewIntNo = Intrinsic::x86_sse2_psll_w;
6685 case Intrinsic::x86_sse2_pslli_d:
6686 NewIntNo = Intrinsic::x86_sse2_psll_d;
6688 case Intrinsic::x86_sse2_pslli_q:
6689 NewIntNo = Intrinsic::x86_sse2_psll_q;
6691 case Intrinsic::x86_sse2_psrli_w:
6692 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6694 case Intrinsic::x86_sse2_psrli_d:
6695 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6697 case Intrinsic::x86_sse2_psrli_q:
6698 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6700 case Intrinsic::x86_sse2_psrai_w:
6701 NewIntNo = Intrinsic::x86_sse2_psra_w;
6703 case Intrinsic::x86_sse2_psrai_d:
6704 NewIntNo = Intrinsic::x86_sse2_psra_d;
6707 ShAmtVT = MVT::v2i32;
6709 case Intrinsic::x86_mmx_pslli_w:
6710 NewIntNo = Intrinsic::x86_mmx_psll_w;
6712 case Intrinsic::x86_mmx_pslli_d:
6713 NewIntNo = Intrinsic::x86_mmx_psll_d;
6715 case Intrinsic::x86_mmx_pslli_q:
6716 NewIntNo = Intrinsic::x86_mmx_psll_q;
6718 case Intrinsic::x86_mmx_psrli_w:
6719 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6721 case Intrinsic::x86_mmx_psrli_d:
6722 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6724 case Intrinsic::x86_mmx_psrli_q:
6725 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6727 case Intrinsic::x86_mmx_psrai_w:
6728 NewIntNo = Intrinsic::x86_mmx_psra_w;
6730 case Intrinsic::x86_mmx_psrai_d:
6731 NewIntNo = Intrinsic::x86_mmx_psra_d;
6733 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6739 // The vector shift intrinsics with scalars uses 32b shift amounts but
6740 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6744 ShOps[1] = DAG.getConstant(0, MVT::i32);
6745 if (ShAmtVT == MVT::v4i32) {
6746 ShOps[2] = DAG.getUNDEF(MVT::i32);
6747 ShOps[3] = DAG.getUNDEF(MVT::i32);
6748 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6750 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6753 EVT VT = Op.getValueType();
6754 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6755 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6756 DAG.getConstant(NewIntNo, MVT::i32),
6757 Op.getOperand(1), ShAmt);
6762 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6763 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6764 DebugLoc dl = Op.getDebugLoc();
6767 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6769 DAG.getConstant(TD->getPointerSize(),
6770 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6771 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6772 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6777 // Just load the return address.
6778 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6779 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6780 RetAddrFI, NULL, 0);
6783 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6784 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6785 MFI->setFrameAddressIsTaken(true);
6786 EVT VT = Op.getValueType();
6787 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6788 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6789 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6790 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6792 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6796 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6797 SelectionDAG &DAG) {
6798 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6801 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6803 MachineFunction &MF = DAG.getMachineFunction();
6804 SDValue Chain = Op.getOperand(0);
6805 SDValue Offset = Op.getOperand(1);
6806 SDValue Handler = Op.getOperand(2);
6807 DebugLoc dl = Op.getDebugLoc();
6809 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6811 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6813 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6814 DAG.getIntPtrConstant(-TD->getPointerSize()));
6815 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6816 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6817 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6818 MF.getRegInfo().addLiveOut(StoreAddrReg);
6820 return DAG.getNode(X86ISD::EH_RETURN, dl,
6822 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6825 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6826 SelectionDAG &DAG) {
6827 SDValue Root = Op.getOperand(0);
6828 SDValue Trmp = Op.getOperand(1); // trampoline
6829 SDValue FPtr = Op.getOperand(2); // nested function
6830 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6831 DebugLoc dl = Op.getDebugLoc();
6833 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6835 const X86InstrInfo *TII =
6836 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6838 if (Subtarget->is64Bit()) {
6839 SDValue OutChains[6];
6841 // Large code-model.
6843 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6844 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6846 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6847 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6849 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6851 // Load the pointer to the nested function into R11.
6852 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6853 SDValue Addr = Trmp;
6854 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6857 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6858 DAG.getConstant(2, MVT::i64));
6859 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6861 // Load the 'nest' parameter value into R10.
6862 // R10 is specified in X86CallingConv.td
6863 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6864 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6865 DAG.getConstant(10, MVT::i64));
6866 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6867 Addr, TrmpAddr, 10);
6869 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6870 DAG.getConstant(12, MVT::i64));
6871 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6873 // Jump to the nested function.
6874 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6875 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6876 DAG.getConstant(20, MVT::i64));
6877 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6878 Addr, TrmpAddr, 20);
6880 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6881 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6882 DAG.getConstant(22, MVT::i64));
6883 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6887 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6888 return DAG.getMergeValues(Ops, 2, dl);
6890 const Function *Func =
6891 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6892 CallingConv::ID CC = Func->getCallingConv();
6897 llvm_unreachable("Unsupported calling convention");
6898 case CallingConv::C:
6899 case CallingConv::X86_StdCall: {
6900 // Pass 'nest' parameter in ECX.
6901 // Must be kept in sync with X86CallingConv.td
6904 // Check that ECX wasn't needed by an 'inreg' parameter.
6905 const FunctionType *FTy = Func->getFunctionType();
6906 const AttrListPtr &Attrs = Func->getAttributes();
6908 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6909 unsigned InRegCount = 0;
6912 for (FunctionType::param_iterator I = FTy->param_begin(),
6913 E = FTy->param_end(); I != E; ++I, ++Idx)
6914 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6915 // FIXME: should only count parameters that are lowered to integers.
6916 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6918 if (InRegCount > 2) {
6919 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6924 case CallingConv::X86_FastCall:
6925 case CallingConv::Fast:
6926 // Pass 'nest' parameter in EAX.
6927 // Must be kept in sync with X86CallingConv.td
6932 SDValue OutChains[4];
6935 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6936 DAG.getConstant(10, MVT::i32));
6937 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6939 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6940 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6941 OutChains[0] = DAG.getStore(Root, dl,
6942 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6945 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6946 DAG.getConstant(1, MVT::i32));
6947 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6949 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6950 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6951 DAG.getConstant(5, MVT::i32));
6952 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6953 TrmpAddr, 5, false, 1);
6955 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6956 DAG.getConstant(6, MVT::i32));
6957 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6960 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6961 return DAG.getMergeValues(Ops, 2, dl);
6965 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6967 The rounding mode is in bits 11:10 of FPSR, and has the following
6974 FLT_ROUNDS, on the other hand, expects the following:
6981 To perform the conversion, we do:
6982 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6985 MachineFunction &MF = DAG.getMachineFunction();
6986 const TargetMachine &TM = MF.getTarget();
6987 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6988 unsigned StackAlignment = TFI.getStackAlignment();
6989 EVT VT = Op.getValueType();
6990 DebugLoc dl = Op.getDebugLoc();
6992 // Save FP Control Word to stack slot
6993 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
6994 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6996 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6997 DAG.getEntryNode(), StackSlot);
6999 // Load FP Control Word from stack slot
7000 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7002 // Transform as necessary
7004 DAG.getNode(ISD::SRL, dl, MVT::i16,
7005 DAG.getNode(ISD::AND, dl, MVT::i16,
7006 CWD, DAG.getConstant(0x800, MVT::i16)),
7007 DAG.getConstant(11, MVT::i8));
7009 DAG.getNode(ISD::SRL, dl, MVT::i16,
7010 DAG.getNode(ISD::AND, dl, MVT::i16,
7011 CWD, DAG.getConstant(0x400, MVT::i16)),
7012 DAG.getConstant(9, MVT::i8));
7015 DAG.getNode(ISD::AND, dl, MVT::i16,
7016 DAG.getNode(ISD::ADD, dl, MVT::i16,
7017 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7018 DAG.getConstant(1, MVT::i16)),
7019 DAG.getConstant(3, MVT::i16));
7022 return DAG.getNode((VT.getSizeInBits() < 16 ?
7023 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7026 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7027 EVT VT = Op.getValueType();
7029 unsigned NumBits = VT.getSizeInBits();
7030 DebugLoc dl = Op.getDebugLoc();
7032 Op = Op.getOperand(0);
7033 if (VT == MVT::i8) {
7034 // Zero extend to i32 since there is not an i8 bsr.
7036 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7039 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7040 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7041 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7043 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7046 DAG.getConstant(NumBits+NumBits-1, OpVT),
7047 DAG.getConstant(X86::COND_E, MVT::i8),
7050 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7052 // Finally xor with NumBits-1.
7053 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7056 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7060 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7061 EVT VT = Op.getValueType();
7063 unsigned NumBits = VT.getSizeInBits();
7064 DebugLoc dl = Op.getDebugLoc();
7066 Op = Op.getOperand(0);
7067 if (VT == MVT::i8) {
7069 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7072 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7073 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7074 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7076 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7079 DAG.getConstant(NumBits, OpVT),
7080 DAG.getConstant(X86::COND_E, MVT::i8),
7083 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7086 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7090 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7091 EVT VT = Op.getValueType();
7092 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7093 DebugLoc dl = Op.getDebugLoc();
7095 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7096 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7097 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7098 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7099 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7101 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7102 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7103 // return AloBlo + AloBhi + AhiBlo;
7105 SDValue A = Op.getOperand(0);
7106 SDValue B = Op.getOperand(1);
7108 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7109 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7110 A, DAG.getConstant(32, MVT::i32));
7111 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7112 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7113 B, DAG.getConstant(32, MVT::i32));
7114 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7115 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7117 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7118 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7120 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7121 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7123 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7124 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7125 AloBhi, DAG.getConstant(32, MVT::i32));
7126 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7127 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7128 AhiBlo, DAG.getConstant(32, MVT::i32));
7129 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7130 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7135 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7136 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7137 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7138 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7139 // has only one use.
7140 SDNode *N = Op.getNode();
7141 SDValue LHS = N->getOperand(0);
7142 SDValue RHS = N->getOperand(1);
7143 unsigned BaseOp = 0;
7145 DebugLoc dl = Op.getDebugLoc();
7147 switch (Op.getOpcode()) {
7148 default: llvm_unreachable("Unknown ovf instruction!");
7150 // A subtract of one will be selected as a INC. Note that INC doesn't
7151 // set CF, so we can't do this for UADDO.
7152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7153 if (C->getAPIntValue() == 1) {
7154 BaseOp = X86ISD::INC;
7158 BaseOp = X86ISD::ADD;
7162 BaseOp = X86ISD::ADD;
7166 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7167 // set CF, so we can't do this for USUBO.
7168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7169 if (C->getAPIntValue() == 1) {
7170 BaseOp = X86ISD::DEC;
7174 BaseOp = X86ISD::SUB;
7178 BaseOp = X86ISD::SUB;
7182 BaseOp = X86ISD::SMUL;
7186 BaseOp = X86ISD::UMUL;
7191 // Also sets EFLAGS.
7192 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7193 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7196 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7197 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7199 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7203 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7204 EVT T = Op.getValueType();
7205 DebugLoc dl = Op.getDebugLoc();
7208 switch(T.getSimpleVT().SimpleTy) {
7210 assert(false && "Invalid value type!");
7211 case MVT::i8: Reg = X86::AL; size = 1; break;
7212 case MVT::i16: Reg = X86::AX; size = 2; break;
7213 case MVT::i32: Reg = X86::EAX; size = 4; break;
7215 assert(Subtarget->is64Bit() && "Node not type legal!");
7216 Reg = X86::RAX; size = 8;
7219 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7220 Op.getOperand(2), SDValue());
7221 SDValue Ops[] = { cpIn.getValue(0),
7224 DAG.getTargetConstant(size, MVT::i8),
7226 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7227 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7229 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7233 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7234 SelectionDAG &DAG) {
7235 assert(Subtarget->is64Bit() && "Result not type legalized?");
7236 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7237 SDValue TheChain = Op.getOperand(0);
7238 DebugLoc dl = Op.getDebugLoc();
7239 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7240 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7241 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7243 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7244 DAG.getConstant(32, MVT::i8));
7246 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7249 return DAG.getMergeValues(Ops, 2, dl);
7252 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7253 SDNode *Node = Op.getNode();
7254 DebugLoc dl = Node->getDebugLoc();
7255 EVT T = Node->getValueType(0);
7256 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7257 DAG.getConstant(0, T), Node->getOperand(2));
7258 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7259 cast<AtomicSDNode>(Node)->getMemoryVT(),
7260 Node->getOperand(0),
7261 Node->getOperand(1), negOp,
7262 cast<AtomicSDNode>(Node)->getSrcValue(),
7263 cast<AtomicSDNode>(Node)->getAlignment());
7266 /// LowerOperation - Provide custom lowering hooks for some operations.
7268 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7269 switch (Op.getOpcode()) {
7270 default: llvm_unreachable("Should not custom lower this!");
7271 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7272 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7273 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7274 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7275 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7276 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7277 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7278 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7279 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7280 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7281 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7282 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7283 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7284 case ISD::SHL_PARTS:
7285 case ISD::SRA_PARTS:
7286 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7287 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7288 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7289 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7290 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7291 case ISD::FABS: return LowerFABS(Op, DAG);
7292 case ISD::FNEG: return LowerFNEG(Op, DAG);
7293 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7294 case ISD::SETCC: return LowerSETCC(Op, DAG);
7295 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7296 case ISD::SELECT: return LowerSELECT(Op, DAG);
7297 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7298 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7299 case ISD::VASTART: return LowerVASTART(Op, DAG);
7300 case ISD::VAARG: return LowerVAARG(Op, DAG);
7301 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7302 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7303 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7304 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7305 case ISD::FRAME_TO_ARGS_OFFSET:
7306 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7307 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7308 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7309 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7310 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7311 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7312 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7313 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7319 case ISD::UMULO: return LowerXALUO(Op, DAG);
7320 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7324 void X86TargetLowering::
7325 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7326 SelectionDAG &DAG, unsigned NewOp) {
7327 EVT T = Node->getValueType(0);
7328 DebugLoc dl = Node->getDebugLoc();
7329 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7331 SDValue Chain = Node->getOperand(0);
7332 SDValue In1 = Node->getOperand(1);
7333 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7334 Node->getOperand(2), DAG.getIntPtrConstant(0));
7335 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7336 Node->getOperand(2), DAG.getIntPtrConstant(1));
7337 SDValue Ops[] = { Chain, In1, In2L, In2H };
7338 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7340 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7341 cast<MemSDNode>(Node)->getMemOperand());
7342 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7343 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7344 Results.push_back(Result.getValue(2));
7347 /// ReplaceNodeResults - Replace a node with an illegal result type
7348 /// with a new node built out of custom code.
7349 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7350 SmallVectorImpl<SDValue>&Results,
7351 SelectionDAG &DAG) {
7352 DebugLoc dl = N->getDebugLoc();
7353 switch (N->getOpcode()) {
7355 assert(false && "Do not know how to custom type legalize this operation!");
7357 case ISD::FP_TO_SINT: {
7358 std::pair<SDValue,SDValue> Vals =
7359 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7360 SDValue FIST = Vals.first, StackSlot = Vals.second;
7361 if (FIST.getNode() != 0) {
7362 EVT VT = N->getValueType(0);
7363 // Return a load from the stack slot.
7364 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7368 case ISD::READCYCLECOUNTER: {
7369 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7370 SDValue TheChain = N->getOperand(0);
7371 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7372 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7374 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7376 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7377 SDValue Ops[] = { eax, edx };
7378 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7379 Results.push_back(edx.getValue(1));
7386 EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7387 Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7390 case ISD::ATOMIC_CMP_SWAP: {
7391 EVT T = N->getValueType(0);
7392 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7393 SDValue cpInL, cpInH;
7394 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7395 DAG.getConstant(0, MVT::i32));
7396 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7397 DAG.getConstant(1, MVT::i32));
7398 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7399 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7401 SDValue swapInL, swapInH;
7402 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7403 DAG.getConstant(0, MVT::i32));
7404 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7405 DAG.getConstant(1, MVT::i32));
7406 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7408 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7409 swapInL.getValue(1));
7410 SDValue Ops[] = { swapInH.getValue(0),
7412 swapInH.getValue(1) };
7413 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7414 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7415 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7416 MVT::i32, Result.getValue(1));
7417 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7418 MVT::i32, cpOutL.getValue(2));
7419 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7420 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7421 Results.push_back(cpOutH.getValue(1));
7424 case ISD::ATOMIC_LOAD_ADD:
7425 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7427 case ISD::ATOMIC_LOAD_AND:
7428 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7430 case ISD::ATOMIC_LOAD_NAND:
7431 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7433 case ISD::ATOMIC_LOAD_OR:
7434 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7436 case ISD::ATOMIC_LOAD_SUB:
7437 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7439 case ISD::ATOMIC_LOAD_XOR:
7440 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7442 case ISD::ATOMIC_SWAP:
7443 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7448 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7450 default: return NULL;
7451 case X86ISD::BSF: return "X86ISD::BSF";
7452 case X86ISD::BSR: return "X86ISD::BSR";
7453 case X86ISD::SHLD: return "X86ISD::SHLD";
7454 case X86ISD::SHRD: return "X86ISD::SHRD";
7455 case X86ISD::FAND: return "X86ISD::FAND";
7456 case X86ISD::FOR: return "X86ISD::FOR";
7457 case X86ISD::FXOR: return "X86ISD::FXOR";
7458 case X86ISD::FSRL: return "X86ISD::FSRL";
7459 case X86ISD::FILD: return "X86ISD::FILD";
7460 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7461 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7462 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7463 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7464 case X86ISD::FLD: return "X86ISD::FLD";
7465 case X86ISD::FST: return "X86ISD::FST";
7466 case X86ISD::CALL: return "X86ISD::CALL";
7467 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7468 case X86ISD::BT: return "X86ISD::BT";
7469 case X86ISD::CMP: return "X86ISD::CMP";
7470 case X86ISD::COMI: return "X86ISD::COMI";
7471 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7472 case X86ISD::SETCC: return "X86ISD::SETCC";
7473 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7474 case X86ISD::CMOV: return "X86ISD::CMOV";
7475 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7476 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7477 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7478 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7479 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7480 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7481 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7482 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7483 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7484 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7485 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7486 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7487 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7488 case X86ISD::FMAX: return "X86ISD::FMAX";
7489 case X86ISD::FMIN: return "X86ISD::FMIN";
7490 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7491 case X86ISD::FRCP: return "X86ISD::FRCP";
7492 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7493 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7494 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7495 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7496 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7497 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7498 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7499 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7500 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7501 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7502 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7503 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7504 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7505 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7506 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7507 case X86ISD::VSHL: return "X86ISD::VSHL";
7508 case X86ISD::VSRL: return "X86ISD::VSRL";
7509 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7510 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7511 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7512 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7513 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7514 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7515 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7516 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7517 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7518 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7519 case X86ISD::ADD: return "X86ISD::ADD";
7520 case X86ISD::SUB: return "X86ISD::SUB";
7521 case X86ISD::SMUL: return "X86ISD::SMUL";
7522 case X86ISD::UMUL: return "X86ISD::UMUL";
7523 case X86ISD::INC: return "X86ISD::INC";
7524 case X86ISD::DEC: return "X86ISD::DEC";
7525 case X86ISD::OR: return "X86ISD::OR";
7526 case X86ISD::XOR: return "X86ISD::XOR";
7527 case X86ISD::AND: return "X86ISD::AND";
7528 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7529 case X86ISD::PTEST: return "X86ISD::PTEST";
7530 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7534 // isLegalAddressingMode - Return true if the addressing mode represented
7535 // by AM is legal for this target, for a load/store of the specified type.
7536 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7537 const Type *Ty) const {
7538 // X86 supports extremely general addressing modes.
7539 CodeModel::Model M = getTargetMachine().getCodeModel();
7541 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7542 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7547 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7549 // If a reference to this global requires an extra load, we can't fold it.
7550 if (isGlobalStubReference(GVFlags))
7553 // If BaseGV requires a register for the PIC base, we cannot also have a
7554 // BaseReg specified.
7555 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7558 // If lower 4G is not available, then we must use rip-relative addressing.
7559 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7569 // These scales always work.
7574 // These scales are formed with basereg+scalereg. Only accept if there is
7579 default: // Other stuff never works.
7587 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7588 if (!Ty1->isInteger() || !Ty2->isInteger())
7590 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7591 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7592 if (NumBits1 <= NumBits2)
7594 return Subtarget->is64Bit() || NumBits1 < 64;
7597 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7598 if (!VT1.isInteger() || !VT2.isInteger())
7600 unsigned NumBits1 = VT1.getSizeInBits();
7601 unsigned NumBits2 = VT2.getSizeInBits();
7602 if (NumBits1 <= NumBits2)
7604 return Subtarget->is64Bit() || NumBits1 < 64;
7607 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7608 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7609 return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7612 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7613 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7614 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7617 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7618 // i16 instructions are longer (0x66 prefix) and potentially slower.
7619 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7622 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7623 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7624 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7625 /// are assumed to be legal.
7627 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7629 // Only do shuffles on 128-bit vector types for now.
7630 if (VT.getSizeInBits() == 64)
7633 // FIXME: pshufb, blends, shifts.
7634 return (VT.getVectorNumElements() == 2 ||
7635 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7636 isMOVLMask(M, VT) ||
7637 isSHUFPMask(M, VT) ||
7638 isPSHUFDMask(M, VT) ||
7639 isPSHUFHWMask(M, VT) ||
7640 isPSHUFLWMask(M, VT) ||
7641 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7642 isUNPCKLMask(M, VT) ||
7643 isUNPCKHMask(M, VT) ||
7644 isUNPCKL_v_undef_Mask(M, VT) ||
7645 isUNPCKH_v_undef_Mask(M, VT));
7649 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7651 unsigned NumElts = VT.getVectorNumElements();
7652 // FIXME: This collection of masks seems suspect.
7655 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7656 return (isMOVLMask(Mask, VT) ||
7657 isCommutedMOVLMask(Mask, VT, true) ||
7658 isSHUFPMask(Mask, VT) ||
7659 isCommutedSHUFPMask(Mask, VT));
7664 //===----------------------------------------------------------------------===//
7665 // X86 Scheduler Hooks
7666 //===----------------------------------------------------------------------===//
7668 // private utility function
7670 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7671 MachineBasicBlock *MBB,
7679 TargetRegisterClass *RC,
7680 bool invSrc) const {
7681 // For the atomic bitwise operator, we generate
7684 // ld t1 = [bitinstr.addr]
7685 // op t2 = t1, [bitinstr.val]
7687 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7689 // fallthrough -->nextMBB
7690 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7691 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7692 MachineFunction::iterator MBBIter = MBB;
7695 /// First build the CFG
7696 MachineFunction *F = MBB->getParent();
7697 MachineBasicBlock *thisMBB = MBB;
7698 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7699 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7700 F->insert(MBBIter, newMBB);
7701 F->insert(MBBIter, nextMBB);
7703 // Move all successors to thisMBB to nextMBB
7704 nextMBB->transferSuccessors(thisMBB);
7706 // Update thisMBB to fall through to newMBB
7707 thisMBB->addSuccessor(newMBB);
7709 // newMBB jumps to itself and fall through to nextMBB
7710 newMBB->addSuccessor(nextMBB);
7711 newMBB->addSuccessor(newMBB);
7713 // Insert instructions into newMBB based on incoming instruction
7714 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7715 "unexpected number of operands");
7716 DebugLoc dl = bInstr->getDebugLoc();
7717 MachineOperand& destOper = bInstr->getOperand(0);
7718 MachineOperand* argOpers[2 + X86AddrNumOperands];
7719 int numArgs = bInstr->getNumOperands() - 1;
7720 for (int i=0; i < numArgs; ++i)
7721 argOpers[i] = &bInstr->getOperand(i+1);
7723 // x86 address has 4 operands: base, index, scale, and displacement
7724 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7725 int valArgIndx = lastAddrIndx + 1;
7727 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7728 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7729 for (int i=0; i <= lastAddrIndx; ++i)
7730 (*MIB).addOperand(*argOpers[i]);
7732 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7734 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7739 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7740 assert((argOpers[valArgIndx]->isReg() ||
7741 argOpers[valArgIndx]->isImm()) &&
7743 if (argOpers[valArgIndx]->isReg())
7744 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7746 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7748 (*MIB).addOperand(*argOpers[valArgIndx]);
7750 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7753 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7754 for (int i=0; i <= lastAddrIndx; ++i)
7755 (*MIB).addOperand(*argOpers[i]);
7757 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7758 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7759 bInstr->memoperands_end());
7761 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7765 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7767 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7771 // private utility function: 64 bit atomics on 32 bit host.
7773 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7774 MachineBasicBlock *MBB,
7779 bool invSrc) const {
7780 // For the atomic bitwise operator, we generate
7781 // thisMBB (instructions are in pairs, except cmpxchg8b)
7782 // ld t1,t2 = [bitinstr.addr]
7784 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7785 // op t5, t6 <- out1, out2, [bitinstr.val]
7786 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7787 // mov ECX, EBX <- t5, t6
7788 // mov EAX, EDX <- t1, t2
7789 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7790 // mov t3, t4 <- EAX, EDX
7792 // result in out1, out2
7793 // fallthrough -->nextMBB
7795 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7796 const unsigned LoadOpc = X86::MOV32rm;
7797 const unsigned copyOpc = X86::MOV32rr;
7798 const unsigned NotOpc = X86::NOT32r;
7799 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7800 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7801 MachineFunction::iterator MBBIter = MBB;
7804 /// First build the CFG
7805 MachineFunction *F = MBB->getParent();
7806 MachineBasicBlock *thisMBB = MBB;
7807 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7808 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7809 F->insert(MBBIter, newMBB);
7810 F->insert(MBBIter, nextMBB);
7812 // Move all successors to thisMBB to nextMBB
7813 nextMBB->transferSuccessors(thisMBB);
7815 // Update thisMBB to fall through to newMBB
7816 thisMBB->addSuccessor(newMBB);
7818 // newMBB jumps to itself and fall through to nextMBB
7819 newMBB->addSuccessor(nextMBB);
7820 newMBB->addSuccessor(newMBB);
7822 DebugLoc dl = bInstr->getDebugLoc();
7823 // Insert instructions into newMBB based on incoming instruction
7824 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7825 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7826 "unexpected number of operands");
7827 MachineOperand& dest1Oper = bInstr->getOperand(0);
7828 MachineOperand& dest2Oper = bInstr->getOperand(1);
7829 MachineOperand* argOpers[2 + X86AddrNumOperands];
7830 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7831 argOpers[i] = &bInstr->getOperand(i+2);
7833 // x86 address has 5 operands: base, index, scale, displacement, and segment.
7834 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7836 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7837 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7838 for (int i=0; i <= lastAddrIndx; ++i)
7839 (*MIB).addOperand(*argOpers[i]);
7840 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7841 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7842 // add 4 to displacement.
7843 for (int i=0; i <= lastAddrIndx-2; ++i)
7844 (*MIB).addOperand(*argOpers[i]);
7845 MachineOperand newOp3 = *(argOpers[3]);
7847 newOp3.setImm(newOp3.getImm()+4);
7849 newOp3.setOffset(newOp3.getOffset()+4);
7850 (*MIB).addOperand(newOp3);
7851 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7853 // t3/4 are defined later, at the bottom of the loop
7854 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7855 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7856 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7857 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7858 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7859 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7861 // The subsequent operations should be using the destination registers of
7862 //the PHI instructions.
7864 t1 = F->getRegInfo().createVirtualRegister(RC);
7865 t2 = F->getRegInfo().createVirtualRegister(RC);
7866 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
7867 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
7869 t1 = dest1Oper.getReg();
7870 t2 = dest2Oper.getReg();
7873 int valArgIndx = lastAddrIndx + 1;
7874 assert((argOpers[valArgIndx]->isReg() ||
7875 argOpers[valArgIndx]->isImm()) &&
7877 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7878 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7879 if (argOpers[valArgIndx]->isReg())
7880 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7882 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7883 if (regOpcL != X86::MOV32rr)
7885 (*MIB).addOperand(*argOpers[valArgIndx]);
7886 assert(argOpers[valArgIndx + 1]->isReg() ==
7887 argOpers[valArgIndx]->isReg());
7888 assert(argOpers[valArgIndx + 1]->isImm() ==
7889 argOpers[valArgIndx]->isImm());
7890 if (argOpers[valArgIndx + 1]->isReg())
7891 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7893 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7894 if (regOpcH != X86::MOV32rr)
7896 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7898 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7900 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7903 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7905 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7908 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7909 for (int i=0; i <= lastAddrIndx; ++i)
7910 (*MIB).addOperand(*argOpers[i]);
7912 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7913 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7914 bInstr->memoperands_end());
7916 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7917 MIB.addReg(X86::EAX);
7918 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7919 MIB.addReg(X86::EDX);
7922 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7924 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7928 // private utility function
7930 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7931 MachineBasicBlock *MBB,
7932 unsigned cmovOpc) const {
7933 // For the atomic min/max operator, we generate
7936 // ld t1 = [min/max.addr]
7937 // mov t2 = [min/max.val]
7939 // cmov[cond] t2 = t1
7941 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7943 // fallthrough -->nextMBB
7945 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7946 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7947 MachineFunction::iterator MBBIter = MBB;
7950 /// First build the CFG
7951 MachineFunction *F = MBB->getParent();
7952 MachineBasicBlock *thisMBB = MBB;
7953 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7954 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7955 F->insert(MBBIter, newMBB);
7956 F->insert(MBBIter, nextMBB);
7958 // Move all successors of thisMBB to nextMBB
7959 nextMBB->transferSuccessors(thisMBB);
7961 // Update thisMBB to fall through to newMBB
7962 thisMBB->addSuccessor(newMBB);
7964 // newMBB jumps to newMBB and fall through to nextMBB
7965 newMBB->addSuccessor(nextMBB);
7966 newMBB->addSuccessor(newMBB);
7968 DebugLoc dl = mInstr->getDebugLoc();
7969 // Insert instructions into newMBB based on incoming instruction
7970 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7971 "unexpected number of operands");
7972 MachineOperand& destOper = mInstr->getOperand(0);
7973 MachineOperand* argOpers[2 + X86AddrNumOperands];
7974 int numArgs = mInstr->getNumOperands() - 1;
7975 for (int i=0; i < numArgs; ++i)
7976 argOpers[i] = &mInstr->getOperand(i+1);
7978 // x86 address has 4 operands: base, index, scale, and displacement
7979 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7980 int valArgIndx = lastAddrIndx + 1;
7982 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7983 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7984 for (int i=0; i <= lastAddrIndx; ++i)
7985 (*MIB).addOperand(*argOpers[i]);
7987 // We only support register and immediate values
7988 assert((argOpers[valArgIndx]->isReg() ||
7989 argOpers[valArgIndx]->isImm()) &&
7992 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7993 if (argOpers[valArgIndx]->isReg())
7994 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7996 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7997 (*MIB).addOperand(*argOpers[valArgIndx]);
7999 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8002 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8007 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8008 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8012 // Cmp and exchange if none has modified the memory location
8013 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8014 for (int i=0; i <= lastAddrIndx; ++i)
8015 (*MIB).addOperand(*argOpers[i]);
8017 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8018 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8019 mInstr->memoperands_end());
8021 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8022 MIB.addReg(X86::EAX);
8025 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8027 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8031 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8032 // all of this code can be replaced with that in the .td file.
8034 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8035 unsigned numArgs, bool memArg) const {
8037 MachineFunction *F = BB->getParent();
8038 DebugLoc dl = MI->getDebugLoc();
8039 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8043 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8045 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8047 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8049 for (unsigned i = 0; i < numArgs; ++i) {
8050 MachineOperand &Op = MI->getOperand(i+1);
8052 if (!(Op.isReg() && Op.isImplicit()))
8056 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8059 F->DeleteMachineInstr(MI);
8065 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8067 MachineBasicBlock *MBB) const {
8068 // Emit code to save XMM registers to the stack. The ABI says that the
8069 // number of registers to save is given in %al, so it's theoretically
8070 // possible to do an indirect jump trick to avoid saving all of them,
8071 // however this code takes a simpler approach and just executes all
8072 // of the stores if %al is non-zero. It's less code, and it's probably
8073 // easier on the hardware branch predictor, and stores aren't all that
8074 // expensive anyway.
8076 // Create the new basic blocks. One block contains all the XMM stores,
8077 // and one block is the final destination regardless of whether any
8078 // stores were performed.
8079 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8080 MachineFunction *F = MBB->getParent();
8081 MachineFunction::iterator MBBIter = MBB;
8083 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8084 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8085 F->insert(MBBIter, XMMSaveMBB);
8086 F->insert(MBBIter, EndMBB);
8089 // Move any original successors of MBB to the end block.
8090 EndMBB->transferSuccessors(MBB);
8091 // The original block will now fall through to the XMM save block.
8092 MBB->addSuccessor(XMMSaveMBB);
8093 // The XMMSaveMBB will fall through to the end block.
8094 XMMSaveMBB->addSuccessor(EndMBB);
8096 // Now add the instructions.
8097 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8098 DebugLoc DL = MI->getDebugLoc();
8100 unsigned CountReg = MI->getOperand(0).getReg();
8101 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8102 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8104 if (!Subtarget->isTargetWin64()) {
8105 // If %al is 0, branch around the XMM save block.
8106 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8107 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8108 MBB->addSuccessor(EndMBB);
8111 // In the XMM save block, save all the XMM argument registers.
8112 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8113 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8114 MachineMemOperand *MMO =
8115 F->getMachineMemOperand(
8116 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8117 MachineMemOperand::MOStore, Offset,
8118 /*Size=*/16, /*Align=*/16);
8119 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8120 .addFrameIndex(RegSaveFrameIndex)
8121 .addImm(/*Scale=*/1)
8122 .addReg(/*IndexReg=*/0)
8123 .addImm(/*Disp=*/Offset)
8124 .addReg(/*Segment=*/0)
8125 .addReg(MI->getOperand(i).getReg())
8126 .addMemOperand(MMO);
8129 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8135 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8136 MachineBasicBlock *BB,
8137 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8138 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8139 DebugLoc DL = MI->getDebugLoc();
8141 // To "insert" a SELECT_CC instruction, we actually have to insert the
8142 // diamond control-flow pattern. The incoming instruction knows the
8143 // destination vreg to set, the condition code register to branch on, the
8144 // true/false values to select between, and a branch opcode to use.
8145 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8146 MachineFunction::iterator It = BB;
8152 // cmpTY ccX, r1, r2
8154 // fallthrough --> copy0MBB
8155 MachineBasicBlock *thisMBB = BB;
8156 MachineFunction *F = BB->getParent();
8157 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8158 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8160 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8161 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8162 F->insert(It, copy0MBB);
8163 F->insert(It, sinkMBB);
8164 // Update machine-CFG edges by first adding all successors of the current
8165 // block to the new block which will contain the Phi node for the select.
8166 // Also inform sdisel of the edge changes.
8167 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8168 E = BB->succ_end(); I != E; ++I) {
8169 EM->insert(std::make_pair(*I, sinkMBB));
8170 sinkMBB->addSuccessor(*I);
8172 // Next, remove all successors of the current block, and add the true
8173 // and fallthrough blocks as its successors.
8174 while (!BB->succ_empty())
8175 BB->removeSuccessor(BB->succ_begin());
8176 // Add the true and fallthrough blocks as its successors.
8177 BB->addSuccessor(copy0MBB);
8178 BB->addSuccessor(sinkMBB);
8181 // %FalseValue = ...
8182 // # fallthrough to sinkMBB
8185 // Update machine-CFG edges
8186 BB->addSuccessor(sinkMBB);
8189 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8192 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8193 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8194 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8196 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8202 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8203 MachineBasicBlock *BB,
8204 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8205 switch (MI->getOpcode()) {
8206 default: assert(false && "Unexpected instr type to insert");
8208 case X86::CMOV_V1I64:
8209 case X86::CMOV_FR32:
8210 case X86::CMOV_FR64:
8211 case X86::CMOV_V4F32:
8212 case X86::CMOV_V2F64:
8213 case X86::CMOV_V2I64:
8214 return EmitLoweredSelect(MI, BB, EM);
8216 case X86::FP32_TO_INT16_IN_MEM:
8217 case X86::FP32_TO_INT32_IN_MEM:
8218 case X86::FP32_TO_INT64_IN_MEM:
8219 case X86::FP64_TO_INT16_IN_MEM:
8220 case X86::FP64_TO_INT32_IN_MEM:
8221 case X86::FP64_TO_INT64_IN_MEM:
8222 case X86::FP80_TO_INT16_IN_MEM:
8223 case X86::FP80_TO_INT32_IN_MEM:
8224 case X86::FP80_TO_INT64_IN_MEM: {
8225 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8226 DebugLoc DL = MI->getDebugLoc();
8228 // Change the floating point control register to use "round towards zero"
8229 // mode when truncating to an integer value.
8230 MachineFunction *F = BB->getParent();
8231 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8232 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8234 // Load the old value of the high byte of the control word...
8236 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8237 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8240 // Set the high part to be round to zero...
8241 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8244 // Reload the modified control word now...
8245 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8247 // Restore the memory image of control word to original value
8248 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8251 // Get the X86 opcode to use.
8253 switch (MI->getOpcode()) {
8254 default: llvm_unreachable("illegal opcode!");
8255 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8256 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8257 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8258 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8259 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8260 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8261 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8262 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8263 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8267 MachineOperand &Op = MI->getOperand(0);
8269 AM.BaseType = X86AddressMode::RegBase;
8270 AM.Base.Reg = Op.getReg();
8272 AM.BaseType = X86AddressMode::FrameIndexBase;
8273 AM.Base.FrameIndex = Op.getIndex();
8275 Op = MI->getOperand(1);
8277 AM.Scale = Op.getImm();
8278 Op = MI->getOperand(2);
8280 AM.IndexReg = Op.getImm();
8281 Op = MI->getOperand(3);
8282 if (Op.isGlobal()) {
8283 AM.GV = Op.getGlobal();
8285 AM.Disp = Op.getImm();
8287 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8288 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8290 // Reload the original control word now.
8291 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8293 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8296 // String/text processing lowering.
8297 case X86::PCMPISTRM128REG:
8298 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8299 case X86::PCMPISTRM128MEM:
8300 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8301 case X86::PCMPESTRM128REG:
8302 return EmitPCMP(MI, BB, 5, false /* in mem */);
8303 case X86::PCMPESTRM128MEM:
8304 return EmitPCMP(MI, BB, 5, true /* in mem */);
8307 case X86::ATOMAND32:
8308 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8309 X86::AND32ri, X86::MOV32rm,
8310 X86::LCMPXCHG32, X86::MOV32rr,
8311 X86::NOT32r, X86::EAX,
8312 X86::GR32RegisterClass);
8314 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8315 X86::OR32ri, X86::MOV32rm,
8316 X86::LCMPXCHG32, X86::MOV32rr,
8317 X86::NOT32r, X86::EAX,
8318 X86::GR32RegisterClass);
8319 case X86::ATOMXOR32:
8320 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8321 X86::XOR32ri, X86::MOV32rm,
8322 X86::LCMPXCHG32, X86::MOV32rr,
8323 X86::NOT32r, X86::EAX,
8324 X86::GR32RegisterClass);
8325 case X86::ATOMNAND32:
8326 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8327 X86::AND32ri, X86::MOV32rm,
8328 X86::LCMPXCHG32, X86::MOV32rr,
8329 X86::NOT32r, X86::EAX,
8330 X86::GR32RegisterClass, true);
8331 case X86::ATOMMIN32:
8332 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8333 case X86::ATOMMAX32:
8334 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8335 case X86::ATOMUMIN32:
8336 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8337 case X86::ATOMUMAX32:
8338 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8340 case X86::ATOMAND16:
8341 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8342 X86::AND16ri, X86::MOV16rm,
8343 X86::LCMPXCHG16, X86::MOV16rr,
8344 X86::NOT16r, X86::AX,
8345 X86::GR16RegisterClass);
8347 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8348 X86::OR16ri, X86::MOV16rm,
8349 X86::LCMPXCHG16, X86::MOV16rr,
8350 X86::NOT16r, X86::AX,
8351 X86::GR16RegisterClass);
8352 case X86::ATOMXOR16:
8353 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8354 X86::XOR16ri, X86::MOV16rm,
8355 X86::LCMPXCHG16, X86::MOV16rr,
8356 X86::NOT16r, X86::AX,
8357 X86::GR16RegisterClass);
8358 case X86::ATOMNAND16:
8359 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8360 X86::AND16ri, X86::MOV16rm,
8361 X86::LCMPXCHG16, X86::MOV16rr,
8362 X86::NOT16r, X86::AX,
8363 X86::GR16RegisterClass, true);
8364 case X86::ATOMMIN16:
8365 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8366 case X86::ATOMMAX16:
8367 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8368 case X86::ATOMUMIN16:
8369 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8370 case X86::ATOMUMAX16:
8371 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8374 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8375 X86::AND8ri, X86::MOV8rm,
8376 X86::LCMPXCHG8, X86::MOV8rr,
8377 X86::NOT8r, X86::AL,
8378 X86::GR8RegisterClass);
8380 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8381 X86::OR8ri, X86::MOV8rm,
8382 X86::LCMPXCHG8, X86::MOV8rr,
8383 X86::NOT8r, X86::AL,
8384 X86::GR8RegisterClass);
8386 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8387 X86::XOR8ri, X86::MOV8rm,
8388 X86::LCMPXCHG8, X86::MOV8rr,
8389 X86::NOT8r, X86::AL,
8390 X86::GR8RegisterClass);
8391 case X86::ATOMNAND8:
8392 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8393 X86::AND8ri, X86::MOV8rm,
8394 X86::LCMPXCHG8, X86::MOV8rr,
8395 X86::NOT8r, X86::AL,
8396 X86::GR8RegisterClass, true);
8397 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8398 // This group is for 64-bit host.
8399 case X86::ATOMAND64:
8400 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8401 X86::AND64ri32, X86::MOV64rm,
8402 X86::LCMPXCHG64, X86::MOV64rr,
8403 X86::NOT64r, X86::RAX,
8404 X86::GR64RegisterClass);
8406 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8407 X86::OR64ri32, X86::MOV64rm,
8408 X86::LCMPXCHG64, X86::MOV64rr,
8409 X86::NOT64r, X86::RAX,
8410 X86::GR64RegisterClass);
8411 case X86::ATOMXOR64:
8412 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8413 X86::XOR64ri32, X86::MOV64rm,
8414 X86::LCMPXCHG64, X86::MOV64rr,
8415 X86::NOT64r, X86::RAX,
8416 X86::GR64RegisterClass);
8417 case X86::ATOMNAND64:
8418 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8419 X86::AND64ri32, X86::MOV64rm,
8420 X86::LCMPXCHG64, X86::MOV64rr,
8421 X86::NOT64r, X86::RAX,
8422 X86::GR64RegisterClass, true);
8423 case X86::ATOMMIN64:
8424 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8425 case X86::ATOMMAX64:
8426 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8427 case X86::ATOMUMIN64:
8428 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8429 case X86::ATOMUMAX64:
8430 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8432 // This group does 64-bit operations on a 32-bit host.
8433 case X86::ATOMAND6432:
8434 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8435 X86::AND32rr, X86::AND32rr,
8436 X86::AND32ri, X86::AND32ri,
8438 case X86::ATOMOR6432:
8439 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8440 X86::OR32rr, X86::OR32rr,
8441 X86::OR32ri, X86::OR32ri,
8443 case X86::ATOMXOR6432:
8444 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8445 X86::XOR32rr, X86::XOR32rr,
8446 X86::XOR32ri, X86::XOR32ri,
8448 case X86::ATOMNAND6432:
8449 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8450 X86::AND32rr, X86::AND32rr,
8451 X86::AND32ri, X86::AND32ri,
8453 case X86::ATOMADD6432:
8454 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8455 X86::ADD32rr, X86::ADC32rr,
8456 X86::ADD32ri, X86::ADC32ri,
8458 case X86::ATOMSUB6432:
8459 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8460 X86::SUB32rr, X86::SBB32rr,
8461 X86::SUB32ri, X86::SBB32ri,
8463 case X86::ATOMSWAP6432:
8464 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8465 X86::MOV32rr, X86::MOV32rr,
8466 X86::MOV32ri, X86::MOV32ri,
8468 case X86::VASTART_SAVE_XMM_REGS:
8469 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8473 //===----------------------------------------------------------------------===//
8474 // X86 Optimization Hooks
8475 //===----------------------------------------------------------------------===//
8477 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8481 const SelectionDAG &DAG,
8482 unsigned Depth) const {
8483 unsigned Opc = Op.getOpcode();
8484 assert((Opc >= ISD::BUILTIN_OP_END ||
8485 Opc == ISD::INTRINSIC_WO_CHAIN ||
8486 Opc == ISD::INTRINSIC_W_CHAIN ||
8487 Opc == ISD::INTRINSIC_VOID) &&
8488 "Should use MaskedValueIsZero if you don't know whether Op"
8489 " is a target node!");
8491 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8503 // These nodes' second result is a boolean.
8504 if (Op.getResNo() == 0)
8508 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8509 Mask.getBitWidth() - 1);
8514 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8515 /// node is a GlobalAddress + offset.
8516 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8517 GlobalValue* &GA, int64_t &Offset) const{
8518 if (N->getOpcode() == X86ISD::Wrapper) {
8519 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8520 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8521 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8525 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8528 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8529 EVT EltVT, LoadSDNode *&LDBase,
8530 unsigned &LastLoadedElt,
8531 SelectionDAG &DAG, MachineFrameInfo *MFI,
8532 const TargetLowering &TLI) {
8534 LastLoadedElt = -1U;
8535 for (unsigned i = 0; i < NumElems; ++i) {
8536 if (N->getMaskElt(i) < 0) {
8542 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8543 if (!Elt.getNode() ||
8544 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8547 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8549 LDBase = cast<LoadSDNode>(Elt.getNode());
8553 if (Elt.getOpcode() == ISD::UNDEF)
8556 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8557 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8564 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8565 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8566 /// if the load addresses are consecutive, non-overlapping, and in the right
8567 /// order. In the case of v2i64, it will see if it can rewrite the
8568 /// shuffle to be an appropriate build vector so it can take advantage of
8569 // performBuildVectorCombine.
8570 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8571 const TargetLowering &TLI) {
8572 DebugLoc dl = N->getDebugLoc();
8573 EVT VT = N->getValueType(0);
8574 EVT EltVT = VT.getVectorElementType();
8575 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8576 unsigned NumElems = VT.getVectorNumElements();
8578 if (VT.getSizeInBits() != 128)
8581 // Try to combine a vector_shuffle into a 128-bit load.
8582 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8583 LoadSDNode *LD = NULL;
8584 unsigned LastLoadedElt;
8585 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8589 if (LastLoadedElt == NumElems - 1) {
8590 if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8591 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8592 LD->getSrcValue(), LD->getSrcValueOffset(),
8594 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8595 LD->getSrcValue(), LD->getSrcValueOffset(),
8596 LD->isVolatile(), LD->getAlignment());
8597 } else if (NumElems == 4 && LastLoadedElt == 1) {
8598 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8599 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8600 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8601 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8606 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8607 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8608 const X86Subtarget *Subtarget) {
8609 DebugLoc DL = N->getDebugLoc();
8610 SDValue Cond = N->getOperand(0);
8611 // Get the LHS/RHS of the select.
8612 SDValue LHS = N->getOperand(1);
8613 SDValue RHS = N->getOperand(2);
8615 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8616 // instructions have the peculiarity that if either operand is a NaN,
8617 // they chose what we call the RHS operand (and as such are not symmetric).
8618 // It happens that this matches the semantics of the common C idiom
8619 // x<y?x:y and related forms, so we can recognize these cases.
8620 if (Subtarget->hasSSE2() &&
8621 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8622 Cond.getOpcode() == ISD::SETCC) {
8623 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8625 unsigned Opcode = 0;
8626 // Check for x CC y ? x : y.
8627 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8631 // This can be a min if we can prove that at least one of the operands
8633 if (!FiniteOnlyFPMath()) {
8634 if (DAG.isKnownNeverNaN(RHS)) {
8635 // Put the potential NaN in the RHS so that SSE will preserve it.
8636 std::swap(LHS, RHS);
8637 } else if (!DAG.isKnownNeverNaN(LHS))
8640 Opcode = X86ISD::FMIN;
8643 // This can be a min if we can prove that at least one of the operands
8645 if (!FiniteOnlyFPMath()) {
8646 if (DAG.isKnownNeverNaN(LHS)) {
8647 // Put the potential NaN in the RHS so that SSE will preserve it.
8648 std::swap(LHS, RHS);
8649 } else if (!DAG.isKnownNeverNaN(RHS))
8652 Opcode = X86ISD::FMIN;
8655 // This can be a min, but if either operand is a NaN we need it to
8656 // preserve the original LHS.
8657 std::swap(LHS, RHS);
8661 Opcode = X86ISD::FMIN;
8665 // This can be a max if we can prove that at least one of the operands
8667 if (!FiniteOnlyFPMath()) {
8668 if (DAG.isKnownNeverNaN(LHS)) {
8669 // Put the potential NaN in the RHS so that SSE will preserve it.
8670 std::swap(LHS, RHS);
8671 } else if (!DAG.isKnownNeverNaN(RHS))
8674 Opcode = X86ISD::FMAX;
8677 // This can be a max if we can prove that at least one of the operands
8679 if (!FiniteOnlyFPMath()) {
8680 if (DAG.isKnownNeverNaN(RHS)) {
8681 // Put the potential NaN in the RHS so that SSE will preserve it.
8682 std::swap(LHS, RHS);
8683 } else if (!DAG.isKnownNeverNaN(LHS))
8686 Opcode = X86ISD::FMAX;
8689 // This can be a max, but if either operand is a NaN we need it to
8690 // preserve the original LHS.
8691 std::swap(LHS, RHS);
8695 Opcode = X86ISD::FMAX;
8698 // Check for x CC y ? y : x -- a min/max with reversed arms.
8699 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8703 // This can be a min if we can prove that at least one of the operands
8705 if (!FiniteOnlyFPMath()) {
8706 if (DAG.isKnownNeverNaN(RHS)) {
8707 // Put the potential NaN in the RHS so that SSE will preserve it.
8708 std::swap(LHS, RHS);
8709 } else if (!DAG.isKnownNeverNaN(LHS))
8712 Opcode = X86ISD::FMIN;
8715 // This can be a min if we can prove that at least one of the operands
8717 if (!FiniteOnlyFPMath()) {
8718 if (DAG.isKnownNeverNaN(LHS)) {
8719 // Put the potential NaN in the RHS so that SSE will preserve it.
8720 std::swap(LHS, RHS);
8721 } else if (!DAG.isKnownNeverNaN(RHS))
8724 Opcode = X86ISD::FMIN;
8727 // This can be a min, but if either operand is a NaN we need it to
8728 // preserve the original LHS.
8729 std::swap(LHS, RHS);
8733 Opcode = X86ISD::FMIN;
8737 // This can be a max if we can prove that at least one of the operands
8739 if (!FiniteOnlyFPMath()) {
8740 if (DAG.isKnownNeverNaN(LHS)) {
8741 // Put the potential NaN in the RHS so that SSE will preserve it.
8742 std::swap(LHS, RHS);
8743 } else if (!DAG.isKnownNeverNaN(RHS))
8746 Opcode = X86ISD::FMAX;
8749 // This can be a max if we can prove that at least one of the operands
8751 if (!FiniteOnlyFPMath()) {
8752 if (DAG.isKnownNeverNaN(RHS)) {
8753 // Put the potential NaN in the RHS so that SSE will preserve it.
8754 std::swap(LHS, RHS);
8755 } else if (!DAG.isKnownNeverNaN(LHS))
8758 Opcode = X86ISD::FMAX;
8761 // This can be a max, but if either operand is a NaN we need it to
8762 // preserve the original LHS.
8763 std::swap(LHS, RHS);
8767 Opcode = X86ISD::FMAX;
8773 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8776 // If this is a select between two integer constants, try to do some
8778 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8779 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8780 // Don't do this for crazy integer types.
8781 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8782 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8783 // so that TrueC (the true value) is larger than FalseC.
8784 bool NeedsCondInvert = false;
8786 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8787 // Efficiently invertible.
8788 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8789 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8790 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8791 NeedsCondInvert = true;
8792 std::swap(TrueC, FalseC);
8795 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8796 if (FalseC->getAPIntValue() == 0 &&
8797 TrueC->getAPIntValue().isPowerOf2()) {
8798 if (NeedsCondInvert) // Invert the condition if needed.
8799 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8800 DAG.getConstant(1, Cond.getValueType()));
8802 // Zero extend the condition if needed.
8803 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8805 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8806 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8807 DAG.getConstant(ShAmt, MVT::i8));
8810 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8811 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8812 if (NeedsCondInvert) // Invert the condition if needed.
8813 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8814 DAG.getConstant(1, Cond.getValueType()));
8816 // Zero extend the condition if needed.
8817 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8818 FalseC->getValueType(0), Cond);
8819 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8820 SDValue(FalseC, 0));
8823 // Optimize cases that will turn into an LEA instruction. This requires
8824 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8825 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8826 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8827 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8829 bool isFastMultiplier = false;
8831 switch ((unsigned char)Diff) {
8833 case 1: // result = add base, cond
8834 case 2: // result = lea base( , cond*2)
8835 case 3: // result = lea base(cond, cond*2)
8836 case 4: // result = lea base( , cond*4)
8837 case 5: // result = lea base(cond, cond*4)
8838 case 8: // result = lea base( , cond*8)
8839 case 9: // result = lea base(cond, cond*8)
8840 isFastMultiplier = true;
8845 if (isFastMultiplier) {
8846 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8847 if (NeedsCondInvert) // Invert the condition if needed.
8848 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8849 DAG.getConstant(1, Cond.getValueType()));
8851 // Zero extend the condition if needed.
8852 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8854 // Scale the condition by the difference.
8856 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8857 DAG.getConstant(Diff, Cond.getValueType()));
8859 // Add the base if non-zero.
8860 if (FalseC->getAPIntValue() != 0)
8861 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8862 SDValue(FalseC, 0));
8872 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8873 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8874 TargetLowering::DAGCombinerInfo &DCI) {
8875 DebugLoc DL = N->getDebugLoc();
8877 // If the flag operand isn't dead, don't touch this CMOV.
8878 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8881 // If this is a select between two integer constants, try to do some
8882 // optimizations. Note that the operands are ordered the opposite of SELECT
8884 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8885 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8886 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8887 // larger than FalseC (the false value).
8888 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8890 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8891 CC = X86::GetOppositeBranchCondition(CC);
8892 std::swap(TrueC, FalseC);
8895 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8896 // This is efficient for any integer data type (including i8/i16) and
8898 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8899 SDValue Cond = N->getOperand(3);
8900 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8901 DAG.getConstant(CC, MVT::i8), Cond);
8903 // Zero extend the condition if needed.
8904 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8906 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8907 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8908 DAG.getConstant(ShAmt, MVT::i8));
8909 if (N->getNumValues() == 2) // Dead flag value?
8910 return DCI.CombineTo(N, Cond, SDValue());
8914 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8915 // for any integer data type, including i8/i16.
8916 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8917 SDValue Cond = N->getOperand(3);
8918 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8919 DAG.getConstant(CC, MVT::i8), Cond);
8921 // Zero extend the condition if needed.
8922 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8923 FalseC->getValueType(0), Cond);
8924 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8925 SDValue(FalseC, 0));
8927 if (N->getNumValues() == 2) // Dead flag value?
8928 return DCI.CombineTo(N, Cond, SDValue());
8932 // Optimize cases that will turn into an LEA instruction. This requires
8933 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8934 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8935 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8936 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8938 bool isFastMultiplier = false;
8940 switch ((unsigned char)Diff) {
8942 case 1: // result = add base, cond
8943 case 2: // result = lea base( , cond*2)
8944 case 3: // result = lea base(cond, cond*2)
8945 case 4: // result = lea base( , cond*4)
8946 case 5: // result = lea base(cond, cond*4)
8947 case 8: // result = lea base( , cond*8)
8948 case 9: // result = lea base(cond, cond*8)
8949 isFastMultiplier = true;
8954 if (isFastMultiplier) {
8955 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8956 SDValue Cond = N->getOperand(3);
8957 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8958 DAG.getConstant(CC, MVT::i8), Cond);
8959 // Zero extend the condition if needed.
8960 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8962 // Scale the condition by the difference.
8964 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8965 DAG.getConstant(Diff, Cond.getValueType()));
8967 // Add the base if non-zero.
8968 if (FalseC->getAPIntValue() != 0)
8969 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8970 SDValue(FalseC, 0));
8971 if (N->getNumValues() == 2) // Dead flag value?
8972 return DCI.CombineTo(N, Cond, SDValue());
8982 /// PerformMulCombine - Optimize a single multiply with constant into two
8983 /// in order to implement it with two cheaper instructions, e.g.
8984 /// LEA + SHL, LEA + LEA.
8985 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8986 TargetLowering::DAGCombinerInfo &DCI) {
8987 if (DAG.getMachineFunction().
8988 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8991 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8994 EVT VT = N->getValueType(0);
8998 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9001 uint64_t MulAmt = C->getZExtValue();
9002 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9005 uint64_t MulAmt1 = 0;
9006 uint64_t MulAmt2 = 0;
9007 if ((MulAmt % 9) == 0) {
9009 MulAmt2 = MulAmt / 9;
9010 } else if ((MulAmt % 5) == 0) {
9012 MulAmt2 = MulAmt / 5;
9013 } else if ((MulAmt % 3) == 0) {
9015 MulAmt2 = MulAmt / 3;
9018 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9019 DebugLoc DL = N->getDebugLoc();
9021 if (isPowerOf2_64(MulAmt2) &&
9022 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9023 // If second multiplifer is pow2, issue it first. We want the multiply by
9024 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9026 std::swap(MulAmt1, MulAmt2);
9029 if (isPowerOf2_64(MulAmt1))
9030 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9031 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9033 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9034 DAG.getConstant(MulAmt1, VT));
9036 if (isPowerOf2_64(MulAmt2))
9037 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9038 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9040 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9041 DAG.getConstant(MulAmt2, VT));
9043 // Do not add new nodes to DAG combiner worklist.
9044 DCI.CombineTo(N, NewMul, false);
9049 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9050 SDValue N0 = N->getOperand(0);
9051 SDValue N1 = N->getOperand(1);
9052 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9053 EVT VT = N0.getValueType();
9055 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9056 // since the result of setcc_c is all zero's or all ones.
9057 if (N1C && N0.getOpcode() == ISD::AND &&
9058 N0.getOperand(1).getOpcode() == ISD::Constant) {
9059 SDValue N00 = N0.getOperand(0);
9060 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9061 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9062 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9063 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9064 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9065 APInt ShAmt = N1C->getAPIntValue();
9066 Mask = Mask.shl(ShAmt);
9068 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9069 N00, DAG.getConstant(Mask, VT));
9076 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9078 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9079 const X86Subtarget *Subtarget) {
9080 EVT VT = N->getValueType(0);
9081 if (!VT.isVector() && VT.isInteger() &&
9082 N->getOpcode() == ISD::SHL)
9083 return PerformSHLCombine(N, DAG);
9085 // On X86 with SSE2 support, we can transform this to a vector shift if
9086 // all elements are shifted by the same amount. We can't do this in legalize
9087 // because the a constant vector is typically transformed to a constant pool
9088 // so we have no knowledge of the shift amount.
9089 if (!Subtarget->hasSSE2())
9092 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9095 SDValue ShAmtOp = N->getOperand(1);
9096 EVT EltVT = VT.getVectorElementType();
9097 DebugLoc DL = N->getDebugLoc();
9098 SDValue BaseShAmt = SDValue();
9099 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9100 unsigned NumElts = VT.getVectorNumElements();
9102 for (; i != NumElts; ++i) {
9103 SDValue Arg = ShAmtOp.getOperand(i);
9104 if (Arg.getOpcode() == ISD::UNDEF) continue;
9108 for (; i != NumElts; ++i) {
9109 SDValue Arg = ShAmtOp.getOperand(i);
9110 if (Arg.getOpcode() == ISD::UNDEF) continue;
9111 if (Arg != BaseShAmt) {
9115 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9116 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9117 SDValue InVec = ShAmtOp.getOperand(0);
9118 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9119 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9121 for (; i != NumElts; ++i) {
9122 SDValue Arg = InVec.getOperand(i);
9123 if (Arg.getOpcode() == ISD::UNDEF) continue;
9127 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9129 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9130 if (C->getZExtValue() == SplatIdx)
9131 BaseShAmt = InVec.getOperand(1);
9134 if (BaseShAmt.getNode() == 0)
9135 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9136 DAG.getIntPtrConstant(0));
9140 // The shift amount is an i32.
9141 if (EltVT.bitsGT(MVT::i32))
9142 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9143 else if (EltVT.bitsLT(MVT::i32))
9144 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9146 // The shift amount is identical so we can do a vector shift.
9147 SDValue ValOp = N->getOperand(0);
9148 switch (N->getOpcode()) {
9150 llvm_unreachable("Unknown shift opcode!");
9153 if (VT == MVT::v2i64)
9154 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9155 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9157 if (VT == MVT::v4i32)
9158 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9159 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9161 if (VT == MVT::v8i16)
9162 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9163 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9167 if (VT == MVT::v4i32)
9168 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9169 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9171 if (VT == MVT::v8i16)
9172 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9173 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9177 if (VT == MVT::v2i64)
9178 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9179 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9181 if (VT == MVT::v4i32)
9182 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9183 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9185 if (VT == MVT::v8i16)
9186 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9187 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9194 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9195 const X86Subtarget *Subtarget) {
9196 EVT VT = N->getValueType(0);
9197 if (VT != MVT::i64 || !Subtarget->is64Bit())
9200 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9201 SDValue N0 = N->getOperand(0);
9202 SDValue N1 = N->getOperand(1);
9203 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9205 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9208 SDValue ShAmt0 = N0.getOperand(1);
9209 if (ShAmt0.getValueType() != MVT::i8)
9211 SDValue ShAmt1 = N1.getOperand(1);
9212 if (ShAmt1.getValueType() != MVT::i8)
9214 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9215 ShAmt0 = ShAmt0.getOperand(0);
9216 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9217 ShAmt1 = ShAmt1.getOperand(0);
9219 DebugLoc DL = N->getDebugLoc();
9220 unsigned Opc = X86ISD::SHLD;
9221 SDValue Op0 = N0.getOperand(0);
9222 SDValue Op1 = N1.getOperand(0);
9223 if (ShAmt0.getOpcode() == ISD::SUB) {
9225 std::swap(Op0, Op1);
9226 std::swap(ShAmt0, ShAmt1);
9229 if (ShAmt1.getOpcode() == ISD::SUB) {
9230 SDValue Sum = ShAmt1.getOperand(0);
9231 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9232 if (SumC->getSExtValue() == 64 &&
9233 ShAmt1.getOperand(1) == ShAmt0)
9234 return DAG.getNode(Opc, DL, VT,
9236 DAG.getNode(ISD::TRUNCATE, DL,
9239 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9240 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9242 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9243 return DAG.getNode(Opc, DL, VT,
9244 N0.getOperand(0), N1.getOperand(0),
9245 DAG.getNode(ISD::TRUNCATE, DL,
9252 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9253 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9254 const X86Subtarget *Subtarget) {
9255 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9256 // the FP state in cases where an emms may be missing.
9257 // A preferable solution to the general problem is to figure out the right
9258 // places to insert EMMS. This qualifies as a quick hack.
9260 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9261 StoreSDNode *St = cast<StoreSDNode>(N);
9262 EVT VT = St->getValue().getValueType();
9263 if (VT.getSizeInBits() != 64)
9266 const Function *F = DAG.getMachineFunction().getFunction();
9267 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9268 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9269 && Subtarget->hasSSE2();
9270 if ((VT.isVector() ||
9271 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9272 isa<LoadSDNode>(St->getValue()) &&
9273 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9274 St->getChain().hasOneUse() && !St->isVolatile()) {
9275 SDNode* LdVal = St->getValue().getNode();
9277 int TokenFactorIndex = -1;
9278 SmallVector<SDValue, 8> Ops;
9279 SDNode* ChainVal = St->getChain().getNode();
9280 // Must be a store of a load. We currently handle two cases: the load
9281 // is a direct child, and it's under an intervening TokenFactor. It is
9282 // possible to dig deeper under nested TokenFactors.
9283 if (ChainVal == LdVal)
9284 Ld = cast<LoadSDNode>(St->getChain());
9285 else if (St->getValue().hasOneUse() &&
9286 ChainVal->getOpcode() == ISD::TokenFactor) {
9287 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9288 if (ChainVal->getOperand(i).getNode() == LdVal) {
9289 TokenFactorIndex = i;
9290 Ld = cast<LoadSDNode>(St->getValue());
9292 Ops.push_back(ChainVal->getOperand(i));
9296 if (!Ld || !ISD::isNormalLoad(Ld))
9299 // If this is not the MMX case, i.e. we are just turning i64 load/store
9300 // into f64 load/store, avoid the transformation if there are multiple
9301 // uses of the loaded value.
9302 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9305 DebugLoc LdDL = Ld->getDebugLoc();
9306 DebugLoc StDL = N->getDebugLoc();
9307 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9308 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9310 if (Subtarget->is64Bit() || F64IsLegal) {
9311 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9312 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9313 Ld->getBasePtr(), Ld->getSrcValue(),
9314 Ld->getSrcValueOffset(), Ld->isVolatile(),
9315 Ld->getAlignment());
9316 SDValue NewChain = NewLd.getValue(1);
9317 if (TokenFactorIndex != -1) {
9318 Ops.push_back(NewChain);
9319 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9322 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9323 St->getSrcValue(), St->getSrcValueOffset(),
9324 St->isVolatile(), St->getAlignment());
9327 // Otherwise, lower to two pairs of 32-bit loads / stores.
9328 SDValue LoAddr = Ld->getBasePtr();
9329 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9330 DAG.getConstant(4, MVT::i32));
9332 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9333 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9334 Ld->isVolatile(), Ld->getAlignment());
9335 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9336 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9338 MinAlign(Ld->getAlignment(), 4));
9340 SDValue NewChain = LoLd.getValue(1);
9341 if (TokenFactorIndex != -1) {
9342 Ops.push_back(LoLd);
9343 Ops.push_back(HiLd);
9344 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9348 LoAddr = St->getBasePtr();
9349 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9350 DAG.getConstant(4, MVT::i32));
9352 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9353 St->getSrcValue(), St->getSrcValueOffset(),
9354 St->isVolatile(), St->getAlignment());
9355 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9357 St->getSrcValueOffset() + 4,
9359 MinAlign(St->getAlignment(), 4));
9360 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9365 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9366 /// X86ISD::FXOR nodes.
9367 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9368 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9369 // F[X]OR(0.0, x) -> x
9370 // F[X]OR(x, 0.0) -> x
9371 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9372 if (C->getValueAPF().isPosZero())
9373 return N->getOperand(1);
9374 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9375 if (C->getValueAPF().isPosZero())
9376 return N->getOperand(0);
9380 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9381 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9382 // FAND(0.0, x) -> 0.0
9383 // FAND(x, 0.0) -> 0.0
9384 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9385 if (C->getValueAPF().isPosZero())
9386 return N->getOperand(0);
9387 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9388 if (C->getValueAPF().isPosZero())
9389 return N->getOperand(1);
9393 static SDValue PerformBTCombine(SDNode *N,
9395 TargetLowering::DAGCombinerInfo &DCI) {
9396 // BT ignores high bits in the bit index operand.
9397 SDValue Op1 = N->getOperand(1);
9398 if (Op1.hasOneUse()) {
9399 unsigned BitWidth = Op1.getValueSizeInBits();
9400 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9401 APInt KnownZero, KnownOne;
9402 TargetLowering::TargetLoweringOpt TLO(DAG);
9403 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9404 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9405 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9406 DCI.CommitTargetLoweringOpt(TLO);
9411 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9412 SDValue Op = N->getOperand(0);
9413 if (Op.getOpcode() == ISD::BIT_CONVERT)
9414 Op = Op.getOperand(0);
9415 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9416 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9417 VT.getVectorElementType().getSizeInBits() ==
9418 OpVT.getVectorElementType().getSizeInBits()) {
9419 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9424 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9425 // Locked instructions, in turn, have implicit fence semantics (all memory
9426 // operations are flushed before issuing the locked instruction, and the
9427 // are not buffered), so we can fold away the common pattern of
9428 // fence-atomic-fence.
9429 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9430 SDValue atomic = N->getOperand(0);
9431 switch (atomic.getOpcode()) {
9432 case ISD::ATOMIC_CMP_SWAP:
9433 case ISD::ATOMIC_SWAP:
9434 case ISD::ATOMIC_LOAD_ADD:
9435 case ISD::ATOMIC_LOAD_SUB:
9436 case ISD::ATOMIC_LOAD_AND:
9437 case ISD::ATOMIC_LOAD_OR:
9438 case ISD::ATOMIC_LOAD_XOR:
9439 case ISD::ATOMIC_LOAD_NAND:
9440 case ISD::ATOMIC_LOAD_MIN:
9441 case ISD::ATOMIC_LOAD_MAX:
9442 case ISD::ATOMIC_LOAD_UMIN:
9443 case ISD::ATOMIC_LOAD_UMAX:
9449 SDValue fence = atomic.getOperand(0);
9450 if (fence.getOpcode() != ISD::MEMBARRIER)
9453 switch (atomic.getOpcode()) {
9454 case ISD::ATOMIC_CMP_SWAP:
9455 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9456 atomic.getOperand(1), atomic.getOperand(2),
9457 atomic.getOperand(3));
9458 case ISD::ATOMIC_SWAP:
9459 case ISD::ATOMIC_LOAD_ADD:
9460 case ISD::ATOMIC_LOAD_SUB:
9461 case ISD::ATOMIC_LOAD_AND:
9462 case ISD::ATOMIC_LOAD_OR:
9463 case ISD::ATOMIC_LOAD_XOR:
9464 case ISD::ATOMIC_LOAD_NAND:
9465 case ISD::ATOMIC_LOAD_MIN:
9466 case ISD::ATOMIC_LOAD_MAX:
9467 case ISD::ATOMIC_LOAD_UMIN:
9468 case ISD::ATOMIC_LOAD_UMAX:
9469 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9470 atomic.getOperand(1), atomic.getOperand(2));
9476 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9477 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9478 // (and (i32 x86isd::setcc_carry), 1)
9479 // This eliminates the zext. This transformation is necessary because
9480 // ISD::SETCC is always legalized to i8.
9481 DebugLoc dl = N->getDebugLoc();
9482 SDValue N0 = N->getOperand(0);
9483 EVT VT = N->getValueType(0);
9484 if (N0.getOpcode() == ISD::AND &&
9486 N0.getOperand(0).hasOneUse()) {
9487 SDValue N00 = N0.getOperand(0);
9488 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9490 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9491 if (!C || C->getZExtValue() != 1)
9493 return DAG.getNode(ISD::AND, dl, VT,
9494 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9495 N00.getOperand(0), N00.getOperand(1)),
9496 DAG.getConstant(1, VT));
9502 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9503 DAGCombinerInfo &DCI) const {
9504 SelectionDAG &DAG = DCI.DAG;
9505 switch (N->getOpcode()) {
9507 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9508 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9509 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9510 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9513 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9514 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9515 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9517 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9518 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9519 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9520 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9521 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9522 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9528 //===----------------------------------------------------------------------===//
9529 // X86 Inline Assembly Support
9530 //===----------------------------------------------------------------------===//
9532 static bool LowerToBSwap(CallInst *CI) {
9533 // FIXME: this should verify that we are targetting a 486 or better. If not,
9534 // we will turn this bswap into something that will be lowered to logical ops
9535 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9536 // so don't worry about this.
9538 // Verify this is a simple bswap.
9539 if (CI->getNumOperands() != 2 ||
9540 CI->getType() != CI->getOperand(1)->getType() ||
9541 !CI->getType()->isInteger())
9544 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9545 if (!Ty || Ty->getBitWidth() % 16 != 0)
9548 // Okay, we can do this xform, do so now.
9549 const Type *Tys[] = { Ty };
9550 Module *M = CI->getParent()->getParent()->getParent();
9551 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9553 Value *Op = CI->getOperand(1);
9554 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9556 CI->replaceAllUsesWith(Op);
9557 CI->eraseFromParent();
9561 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9562 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9563 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9565 std::string AsmStr = IA->getAsmString();
9567 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9568 SmallVector<StringRef, 4> AsmPieces;
9569 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9571 switch (AsmPieces.size()) {
9572 default: return false;
9574 AsmStr = AsmPieces[0];
9576 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9579 if (AsmPieces.size() == 2 &&
9580 (AsmPieces[0] == "bswap" ||
9581 AsmPieces[0] == "bswapq" ||
9582 AsmPieces[0] == "bswapl") &&
9583 (AsmPieces[1] == "$0" ||
9584 AsmPieces[1] == "${0:q}")) {
9585 // No need to check constraints, nothing other than the equivalent of
9586 // "=r,0" would be valid here.
9587 return LowerToBSwap(CI);
9589 // rorw $$8, ${0:w} --> llvm.bswap.i16
9590 if (CI->getType()->isInteger(16) &&
9591 AsmPieces.size() == 3 &&
9592 AsmPieces[0] == "rorw" &&
9593 AsmPieces[1] == "$$8," &&
9594 AsmPieces[2] == "${0:w}" &&
9595 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9596 return LowerToBSwap(CI);
9600 if (CI->getType()->isInteger(64) &&
9601 Constraints.size() >= 2 &&
9602 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9603 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9604 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9605 SmallVector<StringRef, 4> Words;
9606 SplitString(AsmPieces[0], Words, " \t");
9607 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9609 SplitString(AsmPieces[1], Words, " \t");
9610 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9612 SplitString(AsmPieces[2], Words, " \t,");
9613 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9614 Words[2] == "%edx") {
9615 return LowerToBSwap(CI);
9627 /// getConstraintType - Given a constraint letter, return the type of
9628 /// constraint it is for this target.
9629 X86TargetLowering::ConstraintType
9630 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9631 if (Constraint.size() == 1) {
9632 switch (Constraint[0]) {
9644 return C_RegisterClass;
9652 return TargetLowering::getConstraintType(Constraint);
9655 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9656 /// with another that has more specific requirements based on the type of the
9657 /// corresponding operand.
9658 const char *X86TargetLowering::
9659 LowerXConstraint(EVT ConstraintVT) const {
9660 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9661 // 'f' like normal targets.
9662 if (ConstraintVT.isFloatingPoint()) {
9663 if (Subtarget->hasSSE2())
9665 if (Subtarget->hasSSE1())
9669 return TargetLowering::LowerXConstraint(ConstraintVT);
9672 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9673 /// vector. If it is invalid, don't add anything to Ops.
9674 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9677 std::vector<SDValue>&Ops,
9678 SelectionDAG &DAG) const {
9679 SDValue Result(0, 0);
9681 switch (Constraint) {
9684 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9685 if (C->getZExtValue() <= 31) {
9686 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9692 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9693 if (C->getZExtValue() <= 63) {
9694 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9700 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9701 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9702 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9708 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9709 if (C->getZExtValue() <= 255) {
9710 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9716 // 32-bit signed value
9717 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9718 const ConstantInt *CI = C->getConstantIntValue();
9719 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9720 C->getSExtValue())) {
9721 // Widen to 64 bits here to get it sign extended.
9722 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9725 // FIXME gcc accepts some relocatable values here too, but only in certain
9726 // memory models; it's complicated.
9731 // 32-bit unsigned value
9732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9733 const ConstantInt *CI = C->getConstantIntValue();
9734 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9735 C->getZExtValue())) {
9736 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9740 // FIXME gcc accepts some relocatable values here too, but only in certain
9741 // memory models; it's complicated.
9745 // Literal immediates are always ok.
9746 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9747 // Widen to 64 bits here to get it sign extended.
9748 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9752 // If we are in non-pic codegen mode, we allow the address of a global (with
9753 // an optional displacement) to be used with 'i'.
9754 GlobalAddressSDNode *GA = 0;
9757 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9759 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9760 Offset += GA->getOffset();
9762 } else if (Op.getOpcode() == ISD::ADD) {
9763 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9764 Offset += C->getZExtValue();
9765 Op = Op.getOperand(0);
9768 } else if (Op.getOpcode() == ISD::SUB) {
9769 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9770 Offset += -C->getZExtValue();
9771 Op = Op.getOperand(0);
9776 // Otherwise, this isn't something we can handle, reject it.
9780 GlobalValue *GV = GA->getGlobal();
9781 // If we require an extra load to get this address, as in PIC mode, we
9783 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9784 getTargetMachine())))
9788 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9790 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9796 if (Result.getNode()) {
9797 Ops.push_back(Result);
9800 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9804 std::vector<unsigned> X86TargetLowering::
9805 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9807 if (Constraint.size() == 1) {
9808 // FIXME: not handling fp-stack yet!
9809 switch (Constraint[0]) { // GCC X86 Constraint Letters
9810 default: break; // Unknown constraint letter
9811 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9812 if (Subtarget->is64Bit()) {
9814 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9815 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9816 X86::R10D,X86::R11D,X86::R12D,
9817 X86::R13D,X86::R14D,X86::R15D,
9818 X86::EBP, X86::ESP, 0);
9819 else if (VT == MVT::i16)
9820 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9821 X86::SI, X86::DI, X86::R8W,X86::R9W,
9822 X86::R10W,X86::R11W,X86::R12W,
9823 X86::R13W,X86::R14W,X86::R15W,
9824 X86::BP, X86::SP, 0);
9825 else if (VT == MVT::i8)
9826 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9827 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9828 X86::R10B,X86::R11B,X86::R12B,
9829 X86::R13B,X86::R14B,X86::R15B,
9830 X86::BPL, X86::SPL, 0);
9832 else if (VT == MVT::i64)
9833 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9834 X86::RSI, X86::RDI, X86::R8, X86::R9,
9835 X86::R10, X86::R11, X86::R12,
9836 X86::R13, X86::R14, X86::R15,
9837 X86::RBP, X86::RSP, 0);
9841 // 32-bit fallthrough
9844 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9845 else if (VT == MVT::i16)
9846 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9847 else if (VT == MVT::i8)
9848 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9849 else if (VT == MVT::i64)
9850 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9855 return std::vector<unsigned>();
9858 std::pair<unsigned, const TargetRegisterClass*>
9859 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9861 // First, see if this is a constraint that directly corresponds to an LLVM
9863 if (Constraint.size() == 1) {
9864 // GCC Constraint Letters
9865 switch (Constraint[0]) {
9867 case 'r': // GENERAL_REGS
9868 case 'l': // INDEX_REGS
9870 return std::make_pair(0U, X86::GR8RegisterClass);
9872 return std::make_pair(0U, X86::GR16RegisterClass);
9873 if (VT == MVT::i32 || !Subtarget->is64Bit())
9874 return std::make_pair(0U, X86::GR32RegisterClass);
9875 return std::make_pair(0U, X86::GR64RegisterClass);
9876 case 'R': // LEGACY_REGS
9878 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9880 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9881 if (VT == MVT::i32 || !Subtarget->is64Bit())
9882 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9883 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9884 case 'f': // FP Stack registers.
9885 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9886 // value to the correct fpstack register class.
9887 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9888 return std::make_pair(0U, X86::RFP32RegisterClass);
9889 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9890 return std::make_pair(0U, X86::RFP64RegisterClass);
9891 return std::make_pair(0U, X86::RFP80RegisterClass);
9892 case 'y': // MMX_REGS if MMX allowed.
9893 if (!Subtarget->hasMMX()) break;
9894 return std::make_pair(0U, X86::VR64RegisterClass);
9895 case 'Y': // SSE_REGS if SSE2 allowed
9896 if (!Subtarget->hasSSE2()) break;
9898 case 'x': // SSE_REGS if SSE1 allowed
9899 if (!Subtarget->hasSSE1()) break;
9901 switch (VT.getSimpleVT().SimpleTy) {
9903 // Scalar SSE types.
9906 return std::make_pair(0U, X86::FR32RegisterClass);
9909 return std::make_pair(0U, X86::FR64RegisterClass);
9917 return std::make_pair(0U, X86::VR128RegisterClass);
9923 // Use the default implementation in TargetLowering to convert the register
9924 // constraint into a member of a register class.
9925 std::pair<unsigned, const TargetRegisterClass*> Res;
9926 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9928 // Not found as a standard register?
9929 if (Res.second == 0) {
9930 // Map st(0) -> st(7) -> ST0
9931 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9932 tolower(Constraint[1]) == 's' &&
9933 tolower(Constraint[2]) == 't' &&
9934 Constraint[3] == '(' &&
9935 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9936 Constraint[5] == ')' &&
9937 Constraint[6] == '}') {
9939 Res.first = X86::ST0+Constraint[4]-'0';
9940 Res.second = X86::RFP80RegisterClass;
9944 // GCC allows "st(0)" to be called just plain "st".
9945 if (StringRef("{st}").equals_lower(Constraint)) {
9946 Res.first = X86::ST0;
9947 Res.second = X86::RFP80RegisterClass;
9952 if (StringRef("{flags}").equals_lower(Constraint)) {
9953 Res.first = X86::EFLAGS;
9954 Res.second = X86::CCRRegisterClass;
9958 // 'A' means EAX + EDX.
9959 if (Constraint == "A") {
9960 Res.first = X86::EAX;
9961 Res.second = X86::GR32_ADRegisterClass;
9967 // Otherwise, check to see if this is a register class of the wrong value
9968 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9969 // turn into {ax},{dx}.
9970 if (Res.second->hasType(VT))
9971 return Res; // Correct type already, nothing to do.
9973 // All of the single-register GCC register classes map their values onto
9974 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9975 // really want an 8-bit or 32-bit register, map to the appropriate register
9976 // class and return the appropriate register.
9977 if (Res.second == X86::GR16RegisterClass) {
9978 if (VT == MVT::i8) {
9979 unsigned DestReg = 0;
9980 switch (Res.first) {
9982 case X86::AX: DestReg = X86::AL; break;
9983 case X86::DX: DestReg = X86::DL; break;
9984 case X86::CX: DestReg = X86::CL; break;
9985 case X86::BX: DestReg = X86::BL; break;
9988 Res.first = DestReg;
9989 Res.second = X86::GR8RegisterClass;
9991 } else if (VT == MVT::i32) {
9992 unsigned DestReg = 0;
9993 switch (Res.first) {
9995 case X86::AX: DestReg = X86::EAX; break;
9996 case X86::DX: DestReg = X86::EDX; break;
9997 case X86::CX: DestReg = X86::ECX; break;
9998 case X86::BX: DestReg = X86::EBX; break;
9999 case X86::SI: DestReg = X86::ESI; break;
10000 case X86::DI: DestReg = X86::EDI; break;
10001 case X86::BP: DestReg = X86::EBP; break;
10002 case X86::SP: DestReg = X86::ESP; break;
10005 Res.first = DestReg;
10006 Res.second = X86::GR32RegisterClass;
10008 } else if (VT == MVT::i64) {
10009 unsigned DestReg = 0;
10010 switch (Res.first) {
10012 case X86::AX: DestReg = X86::RAX; break;
10013 case X86::DX: DestReg = X86::RDX; break;
10014 case X86::CX: DestReg = X86::RCX; break;
10015 case X86::BX: DestReg = X86::RBX; break;
10016 case X86::SI: DestReg = X86::RSI; break;
10017 case X86::DI: DestReg = X86::RDI; break;
10018 case X86::BP: DestReg = X86::RBP; break;
10019 case X86::SP: DestReg = X86::RSP; break;
10022 Res.first = DestReg;
10023 Res.second = X86::GR64RegisterClass;
10026 } else if (Res.second == X86::FR32RegisterClass ||
10027 Res.second == X86::FR64RegisterClass ||
10028 Res.second == X86::VR128RegisterClass) {
10029 // Handle references to XMM physical registers that got mapped into the
10030 // wrong class. This can happen with constraints like {xmm0} where the
10031 // target independent register mapper will just pick the first match it can
10032 // find, ignoring the required type.
10033 if (VT == MVT::f32)
10034 Res.second = X86::FR32RegisterClass;
10035 else if (VT == MVT::f64)
10036 Res.second = X86::FR64RegisterClass;
10037 else if (X86::VR128RegisterClass->hasType(VT))
10038 Res.second = X86::VR128RegisterClass;
10044 //===----------------------------------------------------------------------===//
10045 // X86 Widen vector type
10046 //===----------------------------------------------------------------------===//
10048 /// getWidenVectorType: given a vector type, returns the type to widen
10049 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10050 /// If there is no vector type that we want to widen to, returns MVT::Other
10051 /// When and where to widen is target dependent based on the cost of
10052 /// scalarizing vs using the wider vector type.
10054 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10055 assert(VT.isVector());
10056 if (isTypeLegal(VT))
10059 // TODO: In computeRegisterProperty, we can compute the list of legal vector
10060 // type based on element type. This would speed up our search (though
10061 // it may not be worth it since the size of the list is relatively
10063 EVT EltVT = VT.getVectorElementType();
10064 unsigned NElts = VT.getVectorNumElements();
10066 // On X86, it make sense to widen any vector wider than 1
10070 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10071 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10072 EVT SVT = (MVT::SimpleValueType)nVT;
10074 if (isTypeLegal(SVT) &&
10075 SVT.getVectorElementType() == EltVT &&
10076 SVT.getVectorNumElements() > NElts)