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);
600 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
601 // with -msoft-float, disable use of MMX as well.
602 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
603 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
604 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
605 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
606 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
607 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
609 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
610 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
611 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
612 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
614 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
615 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
616 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
617 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
619 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
620 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
622 setOperationAction(ISD::AND, MVT::v8i8, Promote);
623 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
624 setOperationAction(ISD::AND, MVT::v4i16, Promote);
625 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
626 setOperationAction(ISD::AND, MVT::v2i32, Promote);
627 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
628 setOperationAction(ISD::AND, MVT::v1i64, Legal);
630 setOperationAction(ISD::OR, MVT::v8i8, Promote);
631 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
632 setOperationAction(ISD::OR, MVT::v4i16, Promote);
633 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
634 setOperationAction(ISD::OR, MVT::v2i32, Promote);
635 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
636 setOperationAction(ISD::OR, MVT::v1i64, Legal);
638 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
639 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
640 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
641 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
642 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
643 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
644 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
646 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
647 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
648 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
649 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
650 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
651 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
652 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
653 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
654 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
656 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
657 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
659 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
662 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
663 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
667 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
669 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
672 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
674 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
675 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
676 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
677 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
678 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
679 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
680 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
682 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
685 if (!UseSoftFloat && Subtarget->hasSSE1()) {
686 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
688 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
689 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
690 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
691 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
692 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
693 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
694 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
695 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
696 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
697 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
698 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
699 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
702 if (!UseSoftFloat && Subtarget->hasSSE2()) {
703 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
705 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
706 // registers cannot be used even for integer operations.
707 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
708 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
709 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
710 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
712 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
713 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
714 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
715 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
716 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
717 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
718 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
719 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
720 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
721 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
722 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
723 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
724 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
725 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
726 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
727 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
729 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
730 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
731 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
732 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
734 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
737 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
740 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
741 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
742 EVT VT = (MVT::SimpleValueType)i;
743 // Do not attempt to custom lower non-power-of-2 vectors
744 if (!isPowerOf2_32(VT.getVectorNumElements()))
746 // Do not attempt to custom lower non-128-bit vectors
747 if (!VT.is128BitVector())
749 setOperationAction(ISD::BUILD_VECTOR,
750 VT.getSimpleVT().SimpleTy, Custom);
751 setOperationAction(ISD::VECTOR_SHUFFLE,
752 VT.getSimpleVT().SimpleTy, Custom);
753 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
754 VT.getSimpleVT().SimpleTy, Custom);
757 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
758 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
759 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
760 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
761 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
764 if (Subtarget->is64Bit()) {
765 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
766 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
769 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
770 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
771 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
774 // Do not attempt to promote non-128-bit vectors
775 if (!VT.is128BitVector()) {
778 setOperationAction(ISD::AND, SVT, Promote);
779 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
780 setOperationAction(ISD::OR, SVT, Promote);
781 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
782 setOperationAction(ISD::XOR, SVT, Promote);
783 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
784 setOperationAction(ISD::LOAD, SVT, Promote);
785 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
786 setOperationAction(ISD::SELECT, SVT, Promote);
787 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
790 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
792 // Custom lower v2i64 and v2f64 selects.
793 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
794 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
795 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
796 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
798 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
799 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
800 if (!DisableMMX && Subtarget->hasMMX()) {
801 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
802 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
806 if (Subtarget->hasSSE41()) {
807 // FIXME: Do we need to handle scalar-to-vector here?
808 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
810 // i8 and i16 vectors are custom , because the source register and source
811 // source memory operand types are not the same width. f32 vectors are
812 // custom since the immediate controlling the insert encodes additional
814 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
819 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824 if (Subtarget->is64Bit()) {
825 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
826 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
830 if (Subtarget->hasSSE42()) {
831 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
834 if (!UseSoftFloat && Subtarget->hasAVX()) {
835 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
836 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
837 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
838 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
840 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
841 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
842 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
843 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
844 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
845 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
846 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
847 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
848 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
849 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
850 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
851 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
852 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
853 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
854 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
856 // Operations to consider commented out -v16i16 v32i8
857 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
858 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
859 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
860 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
861 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
862 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
863 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
864 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
865 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
866 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
867 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
868 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
869 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
870 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
872 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
873 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
874 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
875 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
877 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
878 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
879 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
880 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
881 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
885 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
891 // Not sure we want to do this since there are no 256-bit integer
894 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895 // This includes 256-bit vectors
896 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
897 EVT VT = (MVT::SimpleValueType)i;
899 // Do not attempt to custom lower non-power-of-2 vectors
900 if (!isPowerOf2_32(VT.getVectorNumElements()))
903 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
908 if (Subtarget->is64Bit()) {
909 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
915 // Not sure we want to do this since there are no 256-bit integer
918 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
919 // Including 256-bit vectors
920 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
921 EVT VT = (MVT::SimpleValueType)i;
923 if (!VT.is256BitVector()) {
926 setOperationAction(ISD::AND, VT, Promote);
927 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
928 setOperationAction(ISD::OR, VT, Promote);
929 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
930 setOperationAction(ISD::XOR, VT, Promote);
931 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
932 setOperationAction(ISD::LOAD, VT, Promote);
933 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
934 setOperationAction(ISD::SELECT, VT, Promote);
935 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
938 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
942 // We want to custom lower some of our intrinsics.
943 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
945 // Add/Sub/Mul with overflow operations are custom lowered.
946 setOperationAction(ISD::SADDO, MVT::i32, Custom);
947 setOperationAction(ISD::SADDO, MVT::i64, Custom);
948 setOperationAction(ISD::UADDO, MVT::i32, Custom);
949 setOperationAction(ISD::UADDO, MVT::i64, Custom);
950 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
951 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
952 setOperationAction(ISD::USUBO, MVT::i32, Custom);
953 setOperationAction(ISD::USUBO, MVT::i64, Custom);
954 setOperationAction(ISD::SMULO, MVT::i32, Custom);
955 setOperationAction(ISD::SMULO, MVT::i64, Custom);
957 if (!Subtarget->is64Bit()) {
958 // These libcalls are not available in 32-bit.
959 setLibcallName(RTLIB::SHL_I128, 0);
960 setLibcallName(RTLIB::SRL_I128, 0);
961 setLibcallName(RTLIB::SRA_I128, 0);
964 // We have target-specific dag combine patterns for the following nodes:
965 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
966 setTargetDAGCombine(ISD::BUILD_VECTOR);
967 setTargetDAGCombine(ISD::SELECT);
968 setTargetDAGCombine(ISD::SHL);
969 setTargetDAGCombine(ISD::SRA);
970 setTargetDAGCombine(ISD::SRL);
971 setTargetDAGCombine(ISD::STORE);
972 setTargetDAGCombine(ISD::MEMBARRIER);
973 if (Subtarget->is64Bit())
974 setTargetDAGCombine(ISD::MUL);
976 computeRegisterProperties();
978 // Divide and reminder operations have no vector equivalent and can
979 // trap. Do a custom widening for these operations in which we never
980 // generate more divides/remainder than the original vector width.
981 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
982 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
983 if (!isTypeLegal((MVT::SimpleValueType)VT)) {
984 setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
985 setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
986 setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
987 setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
991 // FIXME: These should be based on subtarget info. Plus, the values should
992 // be smaller when we are in optimizing for size mode.
993 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
994 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
995 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
996 setPrefLoopAlignment(16);
997 benefitFromCodePlacementOpt = true;
1001 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1006 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1007 /// the desired ByVal argument alignment.
1008 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1011 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1012 if (VTy->getBitWidth() == 128)
1014 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1015 unsigned EltAlign = 0;
1016 getMaxByValAlign(ATy->getElementType(), EltAlign);
1017 if (EltAlign > MaxAlign)
1018 MaxAlign = EltAlign;
1019 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1020 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1021 unsigned EltAlign = 0;
1022 getMaxByValAlign(STy->getElementType(i), EltAlign);
1023 if (EltAlign > MaxAlign)
1024 MaxAlign = EltAlign;
1032 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1033 /// function arguments in the caller parameter area. For X86, aggregates
1034 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1035 /// are at 4-byte boundaries.
1036 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1037 if (Subtarget->is64Bit()) {
1038 // Max of 8 and alignment of type.
1039 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1046 if (Subtarget->hasSSE1())
1047 getMaxByValAlign(Ty, Align);
1051 /// getOptimalMemOpType - Returns the target specific optimal type for load
1052 /// and store operations as a result of memset, memcpy, and memmove
1053 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1056 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1057 bool isSrcConst, bool isSrcStr,
1058 SelectionDAG &DAG) const {
1059 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1060 // linux. This is because the stack realignment code can't handle certain
1061 // cases like PR2962. This should be removed when PR2962 is fixed.
1062 const Function *F = DAG.getMachineFunction().getFunction();
1063 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1064 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1065 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1067 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1070 if (Subtarget->is64Bit() && Size >= 8)
1075 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1077 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1078 SelectionDAG &DAG) const {
1079 if (usesGlobalOffsetTable())
1080 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1081 if (!Subtarget->is64Bit())
1082 // This doesn't have DebugLoc associated with it, but is not really the
1083 // same as a Register.
1084 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1089 /// getFunctionAlignment - Return the Log2 alignment of this function.
1090 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1091 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1094 //===----------------------------------------------------------------------===//
1095 // Return Value Calling Convention Implementation
1096 //===----------------------------------------------------------------------===//
1098 #include "X86GenCallingConv.inc"
1101 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1102 const SmallVectorImpl<EVT> &OutTys,
1103 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1104 SelectionDAG &DAG) {
1105 SmallVector<CCValAssign, 16> RVLocs;
1106 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1107 RVLocs, *DAG.getContext());
1108 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1112 X86TargetLowering::LowerReturn(SDValue Chain,
1113 CallingConv::ID CallConv, bool isVarArg,
1114 const SmallVectorImpl<ISD::OutputArg> &Outs,
1115 DebugLoc dl, SelectionDAG &DAG) {
1117 SmallVector<CCValAssign, 16> RVLocs;
1118 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1119 RVLocs, *DAG.getContext());
1120 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1122 // If this is the first return lowered for this function, add the regs to the
1123 // liveout set for the function.
1124 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1125 for (unsigned i = 0; i != RVLocs.size(); ++i)
1126 if (RVLocs[i].isRegLoc())
1127 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1132 SmallVector<SDValue, 6> RetOps;
1133 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1134 // Operand #1 = Bytes To Pop
1135 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1137 // Copy the result values into the output registers.
1138 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1139 CCValAssign &VA = RVLocs[i];
1140 assert(VA.isRegLoc() && "Can only return in registers!");
1141 SDValue ValToCopy = Outs[i].Val;
1143 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1144 // the RET instruction and handled by the FP Stackifier.
1145 if (VA.getLocReg() == X86::ST0 ||
1146 VA.getLocReg() == X86::ST1) {
1147 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1148 // change the value to the FP stack register class.
1149 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1150 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1151 RetOps.push_back(ValToCopy);
1152 // Don't emit a copytoreg.
1156 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1157 // which is returned in RAX / RDX.
1158 if (Subtarget->is64Bit()) {
1159 EVT ValVT = ValToCopy.getValueType();
1160 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1161 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1162 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1163 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1167 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1168 Flag = Chain.getValue(1);
1171 // The x86-64 ABI for returning structs by value requires that we copy
1172 // the sret argument into %rax for the return. We saved the argument into
1173 // a virtual register in the entry block, so now we copy the value out
1175 if (Subtarget->is64Bit() &&
1176 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1177 MachineFunction &MF = DAG.getMachineFunction();
1178 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1179 unsigned Reg = FuncInfo->getSRetReturnReg();
1181 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1182 FuncInfo->setSRetReturnReg(Reg);
1184 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1186 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1187 Flag = Chain.getValue(1);
1189 // RAX now acts like a return value.
1190 MF.getRegInfo().addLiveOut(X86::RAX);
1193 RetOps[0] = Chain; // Update chain.
1195 // Add the flag if we have it.
1197 RetOps.push_back(Flag);
1199 return DAG.getNode(X86ISD::RET_FLAG, dl,
1200 MVT::Other, &RetOps[0], RetOps.size());
1203 /// LowerCallResult - Lower the result values of a call into the
1204 /// appropriate copies out of appropriate physical registers.
1207 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1208 CallingConv::ID CallConv, bool isVarArg,
1209 const SmallVectorImpl<ISD::InputArg> &Ins,
1210 DebugLoc dl, SelectionDAG &DAG,
1211 SmallVectorImpl<SDValue> &InVals) {
1213 // Assign locations to each value returned by this call.
1214 SmallVector<CCValAssign, 16> RVLocs;
1215 bool Is64Bit = Subtarget->is64Bit();
1216 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1217 RVLocs, *DAG.getContext());
1218 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1220 // Copy all of the result registers out of their specified physreg.
1221 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1222 CCValAssign &VA = RVLocs[i];
1223 EVT CopyVT = VA.getValVT();
1225 // If this is x86-64, and we disabled SSE, we can't return FP values
1226 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1227 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1228 llvm_report_error("SSE register return with SSE disabled");
1231 // If this is a call to a function that returns an fp value on the floating
1232 // point stack, but where we prefer to use the value in xmm registers, copy
1233 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1234 if ((VA.getLocReg() == X86::ST0 ||
1235 VA.getLocReg() == X86::ST1) &&
1236 isScalarFPTypeInSSEReg(VA.getValVT())) {
1241 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1242 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1243 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1244 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1245 MVT::v2i64, InFlag).getValue(1);
1246 Val = Chain.getValue(0);
1247 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1248 Val, DAG.getConstant(0, MVT::i64));
1250 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1251 MVT::i64, InFlag).getValue(1);
1252 Val = Chain.getValue(0);
1254 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1256 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1257 CopyVT, InFlag).getValue(1);
1258 Val = Chain.getValue(0);
1260 InFlag = Chain.getValue(2);
1262 if (CopyVT != VA.getValVT()) {
1263 // Round the F80 the right size, which also moves to the appropriate xmm
1265 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1266 // This truncation won't change the value.
1267 DAG.getIntPtrConstant(1));
1270 InVals.push_back(Val);
1277 //===----------------------------------------------------------------------===//
1278 // C & StdCall & Fast Calling Convention implementation
1279 //===----------------------------------------------------------------------===//
1280 // StdCall calling convention seems to be standard for many Windows' API
1281 // routines and around. It differs from C calling convention just a little:
1282 // callee should clean up the stack, not caller. Symbols should be also
1283 // decorated in some fancy way :) It doesn't support any vector arguments.
1284 // For info on fast calling convention see Fast Calling Convention (tail call)
1285 // implementation LowerX86_32FastCCCallTo.
1287 /// CallIsStructReturn - Determines whether a call uses struct return
1289 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1293 return Outs[0].Flags.isSRet();
1296 /// ArgsAreStructReturn - Determines whether a function uses struct
1297 /// return semantics.
1299 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1303 return Ins[0].Flags.isSRet();
1306 /// IsCalleePop - Determines whether the callee is required to pop its
1307 /// own arguments. Callee pop is necessary to support tail calls.
1308 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1312 switch (CallingConv) {
1315 case CallingConv::X86_StdCall:
1316 return !Subtarget->is64Bit();
1317 case CallingConv::X86_FastCall:
1318 return !Subtarget->is64Bit();
1319 case CallingConv::Fast:
1320 return PerformTailCallOpt;
1324 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1325 /// given CallingConvention value.
1326 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1327 if (Subtarget->is64Bit()) {
1328 if (Subtarget->isTargetWin64())
1329 return CC_X86_Win64_C;
1334 if (CC == CallingConv::X86_FastCall)
1335 return CC_X86_32_FastCall;
1336 else if (CC == CallingConv::Fast)
1337 return CC_X86_32_FastCC;
1342 /// NameDecorationForCallConv - Selects the appropriate decoration to
1343 /// apply to a MachineFunction containing a given calling convention.
1345 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1346 if (CallConv == CallingConv::X86_FastCall)
1348 else if (CallConv == CallingConv::X86_StdCall)
1354 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1355 /// by "Src" to address "Dst" with size and alignment information specified by
1356 /// the specific parameter attribute. The copy will be passed as a byval
1357 /// function parameter.
1359 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1360 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1362 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1363 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1364 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1368 X86TargetLowering::LowerMemArgument(SDValue Chain,
1369 CallingConv::ID CallConv,
1370 const SmallVectorImpl<ISD::InputArg> &Ins,
1371 DebugLoc dl, SelectionDAG &DAG,
1372 const CCValAssign &VA,
1373 MachineFrameInfo *MFI,
1376 // Create the nodes corresponding to a load from this parameter slot.
1377 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1378 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1379 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1382 // If value is passed by pointer we have address passed instead of the value
1384 if (VA.getLocInfo() == CCValAssign::Indirect)
1385 ValVT = VA.getLocVT();
1387 ValVT = VA.getValVT();
1389 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1390 // changed with more analysis.
1391 // In case of tail call optimization mark all arguments mutable. Since they
1392 // could be overwritten by lowering of arguments in case of a tail call.
1393 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1394 VA.getLocMemOffset(), isImmutable, false);
1395 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1396 if (Flags.isByVal())
1398 return DAG.getLoad(ValVT, dl, Chain, FIN,
1399 PseudoSourceValue::getFixedStack(FI), 0);
1403 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1404 CallingConv::ID CallConv,
1406 const SmallVectorImpl<ISD::InputArg> &Ins,
1409 SmallVectorImpl<SDValue> &InVals) {
1411 MachineFunction &MF = DAG.getMachineFunction();
1412 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1414 const Function* Fn = MF.getFunction();
1415 if (Fn->hasExternalLinkage() &&
1416 Subtarget->isTargetCygMing() &&
1417 Fn->getName() == "main")
1418 FuncInfo->setForceFramePointer(true);
1420 // Decorate the function name.
1421 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1423 MachineFrameInfo *MFI = MF.getFrameInfo();
1424 bool Is64Bit = Subtarget->is64Bit();
1425 bool IsWin64 = Subtarget->isTargetWin64();
1427 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1428 "Var args not supported with calling convention fastcc");
1430 // Assign locations to all of the incoming arguments.
1431 SmallVector<CCValAssign, 16> ArgLocs;
1432 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1433 ArgLocs, *DAG.getContext());
1434 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1436 unsigned LastVal = ~0U;
1438 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1439 CCValAssign &VA = ArgLocs[i];
1440 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1442 assert(VA.getValNo() != LastVal &&
1443 "Don't support value assigned to multiple locs yet");
1444 LastVal = VA.getValNo();
1446 if (VA.isRegLoc()) {
1447 EVT RegVT = VA.getLocVT();
1448 TargetRegisterClass *RC = NULL;
1449 if (RegVT == MVT::i32)
1450 RC = X86::GR32RegisterClass;
1451 else if (Is64Bit && RegVT == MVT::i64)
1452 RC = X86::GR64RegisterClass;
1453 else if (RegVT == MVT::f32)
1454 RC = X86::FR32RegisterClass;
1455 else if (RegVT == MVT::f64)
1456 RC = X86::FR64RegisterClass;
1457 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1458 RC = X86::VR128RegisterClass;
1459 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1460 RC = X86::VR64RegisterClass;
1462 llvm_unreachable("Unknown argument type!");
1464 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1465 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1467 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1468 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1470 if (VA.getLocInfo() == CCValAssign::SExt)
1471 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1472 DAG.getValueType(VA.getValVT()));
1473 else if (VA.getLocInfo() == CCValAssign::ZExt)
1474 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1475 DAG.getValueType(VA.getValVT()));
1476 else if (VA.getLocInfo() == CCValAssign::BCvt)
1477 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1479 if (VA.isExtInLoc()) {
1480 // Handle MMX values passed in XMM regs.
1481 if (RegVT.isVector()) {
1482 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1483 ArgValue, DAG.getConstant(0, MVT::i64));
1484 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1486 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1489 assert(VA.isMemLoc());
1490 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1493 // If value is passed via pointer - do a load.
1494 if (VA.getLocInfo() == CCValAssign::Indirect)
1495 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1497 InVals.push_back(ArgValue);
1500 // The x86-64 ABI for returning structs by value requires that we copy
1501 // the sret argument into %rax for the return. Save the argument into
1502 // a virtual register so that we can access it from the return points.
1503 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1504 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1505 unsigned Reg = FuncInfo->getSRetReturnReg();
1507 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1508 FuncInfo->setSRetReturnReg(Reg);
1510 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1511 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1514 unsigned StackSize = CCInfo.getNextStackOffset();
1515 // align stack specially for tail calls
1516 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1517 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1519 // If the function takes variable number of arguments, make a frame index for
1520 // the start of the first vararg value... for expansion of llvm.va_start.
1522 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1523 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1526 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1528 // FIXME: We should really autogenerate these arrays
1529 static const unsigned GPR64ArgRegsWin64[] = {
1530 X86::RCX, X86::RDX, X86::R8, X86::R9
1532 static const unsigned XMMArgRegsWin64[] = {
1533 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1535 static const unsigned GPR64ArgRegs64Bit[] = {
1536 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1538 static const unsigned XMMArgRegs64Bit[] = {
1539 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1540 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1542 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1545 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1546 GPR64ArgRegs = GPR64ArgRegsWin64;
1547 XMMArgRegs = XMMArgRegsWin64;
1549 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1550 GPR64ArgRegs = GPR64ArgRegs64Bit;
1551 XMMArgRegs = XMMArgRegs64Bit;
1553 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1555 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1558 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1559 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1560 "SSE register cannot be used when SSE is disabled!");
1561 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1562 "SSE register cannot be used when SSE is disabled!");
1563 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1564 // Kernel mode asks for SSE to be disabled, so don't push them
1566 TotalNumXMMRegs = 0;
1568 // For X86-64, if there are vararg parameters that are passed via
1569 // registers, then we must store them to their spots on the stack so they
1570 // may be loaded by deferencing the result of va_next.
1571 VarArgsGPOffset = NumIntRegs * 8;
1572 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1573 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1574 TotalNumXMMRegs * 16, 16,
1577 // Store the integer parameter registers.
1578 SmallVector<SDValue, 8> MemOps;
1579 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1580 unsigned Offset = VarArgsGPOffset;
1581 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1582 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1583 DAG.getIntPtrConstant(Offset));
1584 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1585 X86::GR64RegisterClass);
1586 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1588 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1589 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1591 MemOps.push_back(Store);
1595 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1596 // Now store the XMM (fp + vector) parameter registers.
1597 SmallVector<SDValue, 11> SaveXMMOps;
1598 SaveXMMOps.push_back(Chain);
1600 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1601 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1602 SaveXMMOps.push_back(ALVal);
1604 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1605 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1607 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1608 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1609 X86::VR128RegisterClass);
1610 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1611 SaveXMMOps.push_back(Val);
1613 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1615 &SaveXMMOps[0], SaveXMMOps.size()));
1618 if (!MemOps.empty())
1619 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1620 &MemOps[0], MemOps.size());
1624 // Some CCs need callee pop.
1625 if (IsCalleePop(isVarArg, CallConv)) {
1626 BytesToPopOnReturn = StackSize; // Callee pops everything.
1627 BytesCallerReserves = 0;
1629 BytesToPopOnReturn = 0; // Callee pops nothing.
1630 // If this is an sret function, the return should pop the hidden pointer.
1631 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1632 BytesToPopOnReturn = 4;
1633 BytesCallerReserves = StackSize;
1637 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1638 if (CallConv == CallingConv::X86_FastCall)
1639 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1642 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1648 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1649 SDValue StackPtr, SDValue Arg,
1650 DebugLoc dl, SelectionDAG &DAG,
1651 const CCValAssign &VA,
1652 ISD::ArgFlagsTy Flags) {
1653 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1654 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1655 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1656 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1657 if (Flags.isByVal()) {
1658 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1660 return DAG.getStore(Chain, dl, Arg, PtrOff,
1661 PseudoSourceValue::getStack(), LocMemOffset);
1664 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1665 /// optimization is performed and it is required.
1667 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1668 SDValue &OutRetAddr,
1674 if (!IsTailCall || FPDiff==0) return Chain;
1676 // Adjust the Return address stack slot.
1677 EVT VT = getPointerTy();
1678 OutRetAddr = getReturnAddressFrameIndex(DAG);
1680 // Load the "old" Return address.
1681 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1682 return SDValue(OutRetAddr.getNode(), 1);
1685 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1686 /// optimization is performed and it is required (FPDiff!=0).
1688 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1689 SDValue Chain, SDValue RetAddrFrIdx,
1690 bool Is64Bit, int FPDiff, DebugLoc dl) {
1691 // Store the return address to the appropriate stack slot.
1692 if (!FPDiff) return Chain;
1693 // Calculate the new stack slot for the return address.
1694 int SlotSize = Is64Bit ? 8 : 4;
1695 int NewReturnAddrFI =
1696 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize,
1698 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1699 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1700 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1701 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1706 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1707 CallingConv::ID CallConv, bool isVarArg,
1709 const SmallVectorImpl<ISD::OutputArg> &Outs,
1710 const SmallVectorImpl<ISD::InputArg> &Ins,
1711 DebugLoc dl, SelectionDAG &DAG,
1712 SmallVectorImpl<SDValue> &InVals) {
1714 MachineFunction &MF = DAG.getMachineFunction();
1715 bool Is64Bit = Subtarget->is64Bit();
1716 bool IsStructRet = CallIsStructReturn(Outs);
1718 assert((!isTailCall ||
1719 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1720 "IsEligibleForTailCallOptimization missed a case!");
1721 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1722 "Var args not supported with calling convention fastcc");
1724 // Analyze operands of the call, assigning locations to each operand.
1725 SmallVector<CCValAssign, 16> ArgLocs;
1726 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1727 ArgLocs, *DAG.getContext());
1728 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1730 // Get a count of how many bytes are to be pushed on the stack.
1731 unsigned NumBytes = CCInfo.getNextStackOffset();
1732 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1733 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1737 // Lower arguments at fp - stackoffset + fpdiff.
1738 unsigned NumBytesCallerPushed =
1739 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1740 FPDiff = NumBytesCallerPushed - NumBytes;
1742 // Set the delta of movement of the returnaddr stackslot.
1743 // But only set if delta is greater than previous delta.
1744 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1745 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1748 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1750 SDValue RetAddrFrIdx;
1751 // Load return adress for tail calls.
1752 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1755 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1756 SmallVector<SDValue, 8> MemOpChains;
1759 // Walk the register/memloc assignments, inserting copies/loads. In the case
1760 // of tail call optimization arguments are handle later.
1761 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1762 CCValAssign &VA = ArgLocs[i];
1763 EVT RegVT = VA.getLocVT();
1764 SDValue Arg = Outs[i].Val;
1765 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1766 bool isByVal = Flags.isByVal();
1768 // Promote the value if needed.
1769 switch (VA.getLocInfo()) {
1770 default: llvm_unreachable("Unknown loc info!");
1771 case CCValAssign::Full: break;
1772 case CCValAssign::SExt:
1773 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1775 case CCValAssign::ZExt:
1776 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1778 case CCValAssign::AExt:
1779 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1780 // Special case: passing MMX values in XMM registers.
1781 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1782 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1783 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1785 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1787 case CCValAssign::BCvt:
1788 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1790 case CCValAssign::Indirect: {
1791 // Store the argument.
1792 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1793 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1794 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1795 PseudoSourceValue::getFixedStack(FI), 0);
1801 if (VA.isRegLoc()) {
1802 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1804 if (!isTailCall || (isTailCall && isByVal)) {
1805 assert(VA.isMemLoc());
1806 if (StackPtr.getNode() == 0)
1807 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1809 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1810 dl, DAG, VA, Flags));
1815 if (!MemOpChains.empty())
1816 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1817 &MemOpChains[0], MemOpChains.size());
1819 // Build a sequence of copy-to-reg nodes chained together with token chain
1820 // and flag operands which copy the outgoing args into registers.
1822 // Tail call byval lowering might overwrite argument registers so in case of
1823 // tail call optimization the copies to registers are lowered later.
1825 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1826 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1827 RegsToPass[i].second, InFlag);
1828 InFlag = Chain.getValue(1);
1832 if (Subtarget->isPICStyleGOT()) {
1833 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1836 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1837 DAG.getNode(X86ISD::GlobalBaseReg,
1838 DebugLoc::getUnknownLoc(),
1841 InFlag = Chain.getValue(1);
1843 // If we are tail calling and generating PIC/GOT style code load the
1844 // address of the callee into ECX. The value in ecx is used as target of
1845 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1846 // for tail calls on PIC/GOT architectures. Normally we would just put the
1847 // address of GOT into ebx and then call target@PLT. But for tail calls
1848 // ebx would be restored (since ebx is callee saved) before jumping to the
1851 // Note: The actual moving to ECX is done further down.
1852 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1853 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1854 !G->getGlobal()->hasProtectedVisibility())
1855 Callee = LowerGlobalAddress(Callee, DAG);
1856 else if (isa<ExternalSymbolSDNode>(Callee))
1857 Callee = LowerExternalSymbol(Callee, DAG);
1861 if (Is64Bit && isVarArg) {
1862 // From AMD64 ABI document:
1863 // For calls that may call functions that use varargs or stdargs
1864 // (prototype-less calls or calls to functions containing ellipsis (...) in
1865 // the declaration) %al is used as hidden argument to specify the number
1866 // of SSE registers used. The contents of %al do not need to match exactly
1867 // the number of registers, but must be an ubound on the number of SSE
1868 // registers used and is in the range 0 - 8 inclusive.
1870 // FIXME: Verify this on Win64
1871 // Count the number of XMM registers allocated.
1872 static const unsigned XMMArgRegs[] = {
1873 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1874 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1876 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1877 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1878 && "SSE registers cannot be used when SSE is disabled");
1880 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1881 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1882 InFlag = Chain.getValue(1);
1886 // For tail calls lower the arguments to the 'real' stack slot.
1888 // Force all the incoming stack arguments to be loaded from the stack
1889 // before any new outgoing arguments are stored to the stack, because the
1890 // outgoing stack slots may alias the incoming argument stack slots, and
1891 // the alias isn't otherwise explicit. This is slightly more conservative
1892 // than necessary, because it means that each store effectively depends
1893 // on every argument instead of just those arguments it would clobber.
1894 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1896 SmallVector<SDValue, 8> MemOpChains2;
1899 // Do not flag preceeding copytoreg stuff together with the following stuff.
1901 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1902 CCValAssign &VA = ArgLocs[i];
1903 if (!VA.isRegLoc()) {
1904 assert(VA.isMemLoc());
1905 SDValue Arg = Outs[i].Val;
1906 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1907 // Create frame index.
1908 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1909 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1910 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1911 FIN = DAG.getFrameIndex(FI, getPointerTy());
1913 if (Flags.isByVal()) {
1914 // Copy relative to framepointer.
1915 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1916 if (StackPtr.getNode() == 0)
1917 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1919 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1921 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1925 // Store relative to framepointer.
1926 MemOpChains2.push_back(
1927 DAG.getStore(ArgChain, dl, Arg, FIN,
1928 PseudoSourceValue::getFixedStack(FI), 0));
1933 if (!MemOpChains2.empty())
1934 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1935 &MemOpChains2[0], MemOpChains2.size());
1937 // Copy arguments to their registers.
1938 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1939 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1940 RegsToPass[i].second, InFlag);
1941 InFlag = Chain.getValue(1);
1945 // Store the return address to the appropriate stack slot.
1946 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1950 bool WasGlobalOrExternal = false;
1951 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
1952 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
1953 // In the 64-bit large code model, we have to make all calls
1954 // through a register, since the call instruction's 32-bit
1955 // pc-relative offset may not be large enough to hold the whole
1957 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1958 WasGlobalOrExternal = true;
1959 // If the callee is a GlobalAddress node (quite common, every direct call
1960 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
1963 // We should use extra load for direct calls to dllimported functions in
1965 GlobalValue *GV = G->getGlobal();
1966 if (!GV->hasDLLImportLinkage()) {
1967 unsigned char OpFlags = 0;
1969 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1970 // external symbols most go through the PLT in PIC mode. If the symbol
1971 // has hidden or protected visibility, or if it is static or local, then
1972 // we don't need to use the PLT - we can directly call it.
1973 if (Subtarget->isTargetELF() &&
1974 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1975 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1976 OpFlags = X86II::MO_PLT;
1977 } else if (Subtarget->isPICStyleStubAny() &&
1978 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1979 Subtarget->getDarwinVers() < 9) {
1980 // PC-relative references to external symbols should go through $stub,
1981 // unless we're building with the leopard linker or later, which
1982 // automatically synthesizes these stubs.
1983 OpFlags = X86II::MO_DARWIN_STUB;
1986 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1987 G->getOffset(), OpFlags);
1989 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1990 WasGlobalOrExternal = true;
1991 unsigned char OpFlags = 0;
1993 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1994 // symbols should go through the PLT.
1995 if (Subtarget->isTargetELF() &&
1996 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1997 OpFlags = X86II::MO_PLT;
1998 } else if (Subtarget->isPICStyleStubAny() &&
1999 Subtarget->getDarwinVers() < 9) {
2000 // PC-relative references to external symbols should go through $stub,
2001 // unless we're building with the leopard linker or later, which
2002 // automatically synthesizes these stubs.
2003 OpFlags = X86II::MO_DARWIN_STUB;
2006 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2010 if (isTailCall && !WasGlobalOrExternal) {
2011 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2013 Chain = DAG.getCopyToReg(Chain, dl,
2014 DAG.getRegister(Opc, getPointerTy()),
2016 Callee = DAG.getRegister(Opc, getPointerTy());
2017 // Add register as live out.
2018 MF.getRegInfo().addLiveOut(Opc);
2021 // Returns a chain & a flag for retval copy to use.
2022 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2023 SmallVector<SDValue, 8> Ops;
2026 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2027 DAG.getIntPtrConstant(0, true), InFlag);
2028 InFlag = Chain.getValue(1);
2031 Ops.push_back(Chain);
2032 Ops.push_back(Callee);
2035 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2037 // Add argument registers to the end of the list so that they are known live
2039 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2040 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2041 RegsToPass[i].second.getValueType()));
2043 // Add an implicit use GOT pointer in EBX.
2044 if (!isTailCall && Subtarget->isPICStyleGOT())
2045 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2047 // Add an implicit use of AL for x86 vararg functions.
2048 if (Is64Bit && isVarArg)
2049 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2051 if (InFlag.getNode())
2052 Ops.push_back(InFlag);
2055 // If this is the first return lowered for this function, add the regs
2056 // to the liveout set for the function.
2057 if (MF.getRegInfo().liveout_empty()) {
2058 SmallVector<CCValAssign, 16> RVLocs;
2059 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2061 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2062 for (unsigned i = 0; i != RVLocs.size(); ++i)
2063 if (RVLocs[i].isRegLoc())
2064 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2067 assert(((Callee.getOpcode() == ISD::Register &&
2068 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2069 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
2070 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2071 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2072 "Expecting an global address, external symbol, or register");
2074 return DAG.getNode(X86ISD::TC_RETURN, dl,
2075 NodeTys, &Ops[0], Ops.size());
2078 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2079 InFlag = Chain.getValue(1);
2081 // Create the CALLSEQ_END node.
2082 unsigned NumBytesForCalleeToPush;
2083 if (IsCalleePop(isVarArg, CallConv))
2084 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2085 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2086 // If this is is a call to a struct-return function, the callee
2087 // pops the hidden struct pointer, so we have to push it back.
2088 // This is common for Darwin/X86, Linux & Mingw32 targets.
2089 NumBytesForCalleeToPush = 4;
2091 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2093 // Returns a flag for retval copy to use.
2094 Chain = DAG.getCALLSEQ_END(Chain,
2095 DAG.getIntPtrConstant(NumBytes, true),
2096 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2099 InFlag = Chain.getValue(1);
2101 // Handle result values, copying them out of physregs into vregs that we
2103 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2104 Ins, dl, DAG, InVals);
2108 //===----------------------------------------------------------------------===//
2109 // Fast Calling Convention (tail call) implementation
2110 //===----------------------------------------------------------------------===//
2112 // Like std call, callee cleans arguments, convention except that ECX is
2113 // reserved for storing the tail called function address. Only 2 registers are
2114 // free for argument passing (inreg). Tail call optimization is performed
2116 // * tailcallopt is enabled
2117 // * caller/callee are fastcc
2118 // On X86_64 architecture with GOT-style position independent code only local
2119 // (within module) calls are supported at the moment.
2120 // To keep the stack aligned according to platform abi the function
2121 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2122 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2123 // If a tail called function callee has more arguments than the caller the
2124 // caller needs to make sure that there is room to move the RETADDR to. This is
2125 // achieved by reserving an area the size of the argument delta right after the
2126 // original REtADDR, but before the saved framepointer or the spilled registers
2127 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2139 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2140 /// for a 16 byte align requirement.
2141 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2142 SelectionDAG& DAG) {
2143 MachineFunction &MF = DAG.getMachineFunction();
2144 const TargetMachine &TM = MF.getTarget();
2145 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2146 unsigned StackAlignment = TFI.getStackAlignment();
2147 uint64_t AlignMask = StackAlignment - 1;
2148 int64_t Offset = StackSize;
2149 uint64_t SlotSize = TD->getPointerSize();
2150 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2151 // Number smaller than 12 so just add the difference.
2152 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2154 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2155 Offset = ((~AlignMask) & Offset) + StackAlignment +
2156 (StackAlignment-SlotSize);
2161 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2162 /// for tail call optimization. Targets which want to do tail call
2163 /// optimization should implement this function.
2165 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2166 CallingConv::ID CalleeCC,
2168 const SmallVectorImpl<ISD::InputArg> &Ins,
2169 SelectionDAG& DAG) const {
2170 MachineFunction &MF = DAG.getMachineFunction();
2171 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2172 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2176 X86TargetLowering::createFastISel(MachineFunction &mf,
2177 MachineModuleInfo *mmo,
2179 DenseMap<const Value *, unsigned> &vm,
2180 DenseMap<const BasicBlock *,
2181 MachineBasicBlock *> &bm,
2182 DenseMap<const AllocaInst *, int> &am
2184 , SmallSet<Instruction*, 8> &cil
2187 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2195 //===----------------------------------------------------------------------===//
2196 // Other Lowering Hooks
2197 //===----------------------------------------------------------------------===//
2200 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2201 MachineFunction &MF = DAG.getMachineFunction();
2202 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2203 int ReturnAddrIndex = FuncInfo->getRAIndex();
2205 if (ReturnAddrIndex == 0) {
2206 // Set up a frame object for the return address.
2207 uint64_t SlotSize = TD->getPointerSize();
2208 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2210 FuncInfo->setRAIndex(ReturnAddrIndex);
2213 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2217 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2218 bool hasSymbolicDisplacement) {
2219 // Offset should fit into 32 bit immediate field.
2220 if (!isInt32(Offset))
2223 // If we don't have a symbolic displacement - we don't have any extra
2225 if (!hasSymbolicDisplacement)
2228 // FIXME: Some tweaks might be needed for medium code model.
2229 if (M != CodeModel::Small && M != CodeModel::Kernel)
2232 // For small code model we assume that latest object is 16MB before end of 31
2233 // bits boundary. We may also accept pretty large negative constants knowing
2234 // that all objects are in the positive half of address space.
2235 if (M == CodeModel::Small && Offset < 16*1024*1024)
2238 // For kernel code model we know that all object resist in the negative half
2239 // of 32bits address space. We may not accept negative offsets, since they may
2240 // be just off and we may accept pretty large positive ones.
2241 if (M == CodeModel::Kernel && Offset > 0)
2247 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2248 /// specific condition code, returning the condition code and the LHS/RHS of the
2249 /// comparison to make.
2250 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2251 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2253 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2254 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2255 // X > -1 -> X == 0, jump !sign.
2256 RHS = DAG.getConstant(0, RHS.getValueType());
2257 return X86::COND_NS;
2258 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2259 // X < 0 -> X == 0, jump on sign.
2261 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2263 RHS = DAG.getConstant(0, RHS.getValueType());
2264 return X86::COND_LE;
2268 switch (SetCCOpcode) {
2269 default: llvm_unreachable("Invalid integer condition!");
2270 case ISD::SETEQ: return X86::COND_E;
2271 case ISD::SETGT: return X86::COND_G;
2272 case ISD::SETGE: return X86::COND_GE;
2273 case ISD::SETLT: return X86::COND_L;
2274 case ISD::SETLE: return X86::COND_LE;
2275 case ISD::SETNE: return X86::COND_NE;
2276 case ISD::SETULT: return X86::COND_B;
2277 case ISD::SETUGT: return X86::COND_A;
2278 case ISD::SETULE: return X86::COND_BE;
2279 case ISD::SETUGE: return X86::COND_AE;
2283 // First determine if it is required or is profitable to flip the operands.
2285 // If LHS is a foldable load, but RHS is not, flip the condition.
2286 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2287 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2288 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2289 std::swap(LHS, RHS);
2292 switch (SetCCOpcode) {
2298 std::swap(LHS, RHS);
2302 // On a floating point condition, the flags are set as follows:
2304 // 0 | 0 | 0 | X > Y
2305 // 0 | 0 | 1 | X < Y
2306 // 1 | 0 | 0 | X == Y
2307 // 1 | 1 | 1 | unordered
2308 switch (SetCCOpcode) {
2309 default: llvm_unreachable("Condcode should be pre-legalized away");
2311 case ISD::SETEQ: return X86::COND_E;
2312 case ISD::SETOLT: // flipped
2314 case ISD::SETGT: return X86::COND_A;
2315 case ISD::SETOLE: // flipped
2317 case ISD::SETGE: return X86::COND_AE;
2318 case ISD::SETUGT: // flipped
2320 case ISD::SETLT: return X86::COND_B;
2321 case ISD::SETUGE: // flipped
2323 case ISD::SETLE: return X86::COND_BE;
2325 case ISD::SETNE: return X86::COND_NE;
2326 case ISD::SETUO: return X86::COND_P;
2327 case ISD::SETO: return X86::COND_NP;
2329 case ISD::SETUNE: return X86::COND_INVALID;
2333 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2334 /// code. Current x86 isa includes the following FP cmov instructions:
2335 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2336 static bool hasFPCMov(unsigned X86CC) {
2352 /// isFPImmLegal - Returns true if the target can instruction select the
2353 /// specified FP immediate natively. If false, the legalizer will
2354 /// materialize the FP immediate as a load from a constant pool.
2355 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2356 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2357 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2363 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2364 /// the specified range (L, H].
2365 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2366 return (Val < 0) || (Val >= Low && Val < Hi);
2369 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2370 /// specified value.
2371 static bool isUndefOrEqual(int Val, int CmpVal) {
2372 if (Val < 0 || Val == CmpVal)
2377 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2378 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2379 /// the second operand.
2380 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2381 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2382 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2383 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2384 return (Mask[0] < 2 && Mask[1] < 2);
2388 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2389 SmallVector<int, 8> M;
2391 return ::isPSHUFDMask(M, N->getValueType(0));
2394 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2395 /// is suitable for input to PSHUFHW.
2396 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2397 if (VT != MVT::v8i16)
2400 // Lower quadword copied in order or undef.
2401 for (int i = 0; i != 4; ++i)
2402 if (Mask[i] >= 0 && Mask[i] != i)
2405 // Upper quadword shuffled.
2406 for (int i = 4; i != 8; ++i)
2407 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2413 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2414 SmallVector<int, 8> M;
2416 return ::isPSHUFHWMask(M, N->getValueType(0));
2419 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2420 /// is suitable for input to PSHUFLW.
2421 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2422 if (VT != MVT::v8i16)
2425 // Upper quadword copied in order.
2426 for (int i = 4; i != 8; ++i)
2427 if (Mask[i] >= 0 && Mask[i] != i)
2430 // Lower quadword shuffled.
2431 for (int i = 0; i != 4; ++i)
2438 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2439 SmallVector<int, 8> M;
2441 return ::isPSHUFLWMask(M, N->getValueType(0));
2444 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2445 /// is suitable for input to PALIGNR.
2446 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2448 int i, e = VT.getVectorNumElements();
2450 // Do not handle v2i64 / v2f64 shuffles with palignr.
2451 if (e < 4 || !hasSSSE3)
2454 for (i = 0; i != e; ++i)
2458 // All undef, not a palignr.
2462 // Determine if it's ok to perform a palignr with only the LHS, since we
2463 // don't have access to the actual shuffle elements to see if RHS is undef.
2464 bool Unary = Mask[i] < (int)e;
2465 bool NeedsUnary = false;
2467 int s = Mask[i] - i;
2469 // Check the rest of the elements to see if they are consecutive.
2470 for (++i; i != e; ++i) {
2475 Unary = Unary && (m < (int)e);
2476 NeedsUnary = NeedsUnary || (m < s);
2478 if (NeedsUnary && !Unary)
2480 if (Unary && m != ((s+i) & (e-1)))
2482 if (!Unary && m != (s+i))
2488 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2489 SmallVector<int, 8> M;
2491 return ::isPALIGNRMask(M, N->getValueType(0), true);
2494 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2495 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2496 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2497 int NumElems = VT.getVectorNumElements();
2498 if (NumElems != 2 && NumElems != 4)
2501 int Half = NumElems / 2;
2502 for (int i = 0; i < Half; ++i)
2503 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2505 for (int i = Half; i < NumElems; ++i)
2506 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2512 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2513 SmallVector<int, 8> M;
2515 return ::isSHUFPMask(M, N->getValueType(0));
2518 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2519 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2520 /// half elements to come from vector 1 (which would equal the dest.) and
2521 /// the upper half to come from vector 2.
2522 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2523 int NumElems = VT.getVectorNumElements();
2525 if (NumElems != 2 && NumElems != 4)
2528 int Half = NumElems / 2;
2529 for (int i = 0; i < Half; ++i)
2530 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2532 for (int i = Half; i < NumElems; ++i)
2533 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2538 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2539 SmallVector<int, 8> M;
2541 return isCommutedSHUFPMask(M, N->getValueType(0));
2544 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2545 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2546 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2547 if (N->getValueType(0).getVectorNumElements() != 4)
2550 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2551 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2552 isUndefOrEqual(N->getMaskElt(1), 7) &&
2553 isUndefOrEqual(N->getMaskElt(2), 2) &&
2554 isUndefOrEqual(N->getMaskElt(3), 3);
2557 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2558 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2560 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2561 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2566 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2567 isUndefOrEqual(N->getMaskElt(1), 3) &&
2568 isUndefOrEqual(N->getMaskElt(2), 2) &&
2569 isUndefOrEqual(N->getMaskElt(3), 3);
2572 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2573 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2574 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2575 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2577 if (NumElems != 2 && NumElems != 4)
2580 for (unsigned i = 0; i < NumElems/2; ++i)
2581 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2584 for (unsigned i = NumElems/2; i < NumElems; ++i)
2585 if (!isUndefOrEqual(N->getMaskElt(i), i))
2591 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2592 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2593 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2594 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2596 if (NumElems != 2 && NumElems != 4)
2599 for (unsigned i = 0; i < NumElems/2; ++i)
2600 if (!isUndefOrEqual(N->getMaskElt(i), i))
2603 for (unsigned i = 0; i < NumElems/2; ++i)
2604 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2610 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2611 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2612 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2613 bool V2IsSplat = false) {
2614 int NumElts = VT.getVectorNumElements();
2615 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2618 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2620 int BitI1 = Mask[i+1];
2621 if (!isUndefOrEqual(BitI, j))
2624 if (!isUndefOrEqual(BitI1, NumElts))
2627 if (!isUndefOrEqual(BitI1, j + NumElts))
2634 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2635 SmallVector<int, 8> M;
2637 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2640 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2641 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2642 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2643 bool V2IsSplat = false) {
2644 int NumElts = VT.getVectorNumElements();
2645 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2648 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2650 int BitI1 = Mask[i+1];
2651 if (!isUndefOrEqual(BitI, j + NumElts/2))
2654 if (isUndefOrEqual(BitI1, NumElts))
2657 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2664 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2665 SmallVector<int, 8> M;
2667 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2670 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2671 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2673 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2674 int NumElems = VT.getVectorNumElements();
2675 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2678 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2680 int BitI1 = Mask[i+1];
2681 if (!isUndefOrEqual(BitI, j))
2683 if (!isUndefOrEqual(BitI1, j))
2689 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2690 SmallVector<int, 8> M;
2692 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2695 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2696 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2698 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2699 int NumElems = VT.getVectorNumElements();
2700 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2703 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2705 int BitI1 = Mask[i+1];
2706 if (!isUndefOrEqual(BitI, j))
2708 if (!isUndefOrEqual(BitI1, j))
2714 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2715 SmallVector<int, 8> M;
2717 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2720 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2721 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2722 /// MOVSD, and MOVD, i.e. setting the lowest element.
2723 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2724 if (VT.getVectorElementType().getSizeInBits() < 32)
2727 int NumElts = VT.getVectorNumElements();
2729 if (!isUndefOrEqual(Mask[0], NumElts))
2732 for (int i = 1; i < NumElts; ++i)
2733 if (!isUndefOrEqual(Mask[i], i))
2739 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2740 SmallVector<int, 8> M;
2742 return ::isMOVLMask(M, N->getValueType(0));
2745 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2746 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2747 /// element of vector 2 and the other elements to come from vector 1 in order.
2748 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2749 bool V2IsSplat = false, bool V2IsUndef = false) {
2750 int NumOps = VT.getVectorNumElements();
2751 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2754 if (!isUndefOrEqual(Mask[0], 0))
2757 for (int i = 1; i < NumOps; ++i)
2758 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2759 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2760 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2766 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2767 bool V2IsUndef = false) {
2768 SmallVector<int, 8> M;
2770 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2773 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2774 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2775 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2776 if (N->getValueType(0).getVectorNumElements() != 4)
2779 // Expect 1, 1, 3, 3
2780 for (unsigned i = 0; i < 2; ++i) {
2781 int Elt = N->getMaskElt(i);
2782 if (Elt >= 0 && Elt != 1)
2787 for (unsigned i = 2; i < 4; ++i) {
2788 int Elt = N->getMaskElt(i);
2789 if (Elt >= 0 && Elt != 3)
2794 // Don't use movshdup if it can be done with a shufps.
2795 // FIXME: verify that matching u, u, 3, 3 is what we want.
2799 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2800 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2801 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2802 if (N->getValueType(0).getVectorNumElements() != 4)
2805 // Expect 0, 0, 2, 2
2806 for (unsigned i = 0; i < 2; ++i)
2807 if (N->getMaskElt(i) > 0)
2811 for (unsigned i = 2; i < 4; ++i) {
2812 int Elt = N->getMaskElt(i);
2813 if (Elt >= 0 && Elt != 2)
2818 // Don't use movsldup if it can be done with a shufps.
2822 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2823 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2824 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2825 int e = N->getValueType(0).getVectorNumElements() / 2;
2827 for (int i = 0; i < e; ++i)
2828 if (!isUndefOrEqual(N->getMaskElt(i), i))
2830 for (int i = 0; i < e; ++i)
2831 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2836 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2837 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2838 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2839 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2840 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2842 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2844 for (int i = 0; i < NumOperands; ++i) {
2845 int Val = SVOp->getMaskElt(NumOperands-i-1);
2846 if (Val < 0) Val = 0;
2847 if (Val >= NumOperands) Val -= NumOperands;
2849 if (i != NumOperands - 1)
2855 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2856 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2857 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2858 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2860 // 8 nodes, but we only care about the last 4.
2861 for (unsigned i = 7; i >= 4; --i) {
2862 int Val = SVOp->getMaskElt(i);
2871 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2872 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2873 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2874 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2876 // 8 nodes, but we only care about the first 4.
2877 for (int i = 3; i >= 0; --i) {
2878 int Val = SVOp->getMaskElt(i);
2887 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2888 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2889 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2890 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2891 EVT VVT = N->getValueType(0);
2892 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2896 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2897 Val = SVOp->getMaskElt(i);
2901 return (Val - i) * EltSize;
2904 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2906 bool X86::isZeroNode(SDValue Elt) {
2907 return ((isa<ConstantSDNode>(Elt) &&
2908 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2909 (isa<ConstantFPSDNode>(Elt) &&
2910 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2913 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2914 /// their permute mask.
2915 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2916 SelectionDAG &DAG) {
2917 EVT VT = SVOp->getValueType(0);
2918 unsigned NumElems = VT.getVectorNumElements();
2919 SmallVector<int, 8> MaskVec;
2921 for (unsigned i = 0; i != NumElems; ++i) {
2922 int idx = SVOp->getMaskElt(i);
2924 MaskVec.push_back(idx);
2925 else if (idx < (int)NumElems)
2926 MaskVec.push_back(idx + NumElems);
2928 MaskVec.push_back(idx - NumElems);
2930 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2931 SVOp->getOperand(0), &MaskVec[0]);
2934 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2935 /// the two vector operands have swapped position.
2936 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2937 unsigned NumElems = VT.getVectorNumElements();
2938 for (unsigned i = 0; i != NumElems; ++i) {
2942 else if (idx < (int)NumElems)
2943 Mask[i] = idx + NumElems;
2945 Mask[i] = idx - NumElems;
2949 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2950 /// match movhlps. The lower half elements should come from upper half of
2951 /// V1 (and in order), and the upper half elements should come from the upper
2952 /// half of V2 (and in order).
2953 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2954 if (Op->getValueType(0).getVectorNumElements() != 4)
2956 for (unsigned i = 0, e = 2; i != e; ++i)
2957 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2959 for (unsigned i = 2; i != 4; ++i)
2960 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2965 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2966 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2968 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2969 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2971 N = N->getOperand(0).getNode();
2972 if (!ISD::isNON_EXTLoad(N))
2975 *LD = cast<LoadSDNode>(N);
2979 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2980 /// match movlp{s|d}. The lower half elements should come from lower half of
2981 /// V1 (and in order), and the upper half elements should come from the upper
2982 /// half of V2 (and in order). And since V1 will become the source of the
2983 /// MOVLP, it must be either a vector load or a scalar load to vector.
2984 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2985 ShuffleVectorSDNode *Op) {
2986 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2988 // Is V2 is a vector load, don't do this transformation. We will try to use
2989 // load folding shufps op.
2990 if (ISD::isNON_EXTLoad(V2))
2993 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2995 if (NumElems != 2 && NumElems != 4)
2997 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2998 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3000 for (unsigned i = NumElems/2; i != NumElems; ++i)
3001 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3006 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3008 static bool isSplatVector(SDNode *N) {
3009 if (N->getOpcode() != ISD::BUILD_VECTOR)
3012 SDValue SplatValue = N->getOperand(0);
3013 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3014 if (N->getOperand(i) != SplatValue)
3019 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3020 /// to an zero vector.
3021 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3022 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3023 SDValue V1 = N->getOperand(0);
3024 SDValue V2 = N->getOperand(1);
3025 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3026 for (unsigned i = 0; i != NumElems; ++i) {
3027 int Idx = N->getMaskElt(i);
3028 if (Idx >= (int)NumElems) {
3029 unsigned Opc = V2.getOpcode();
3030 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3032 if (Opc != ISD::BUILD_VECTOR ||
3033 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3035 } else if (Idx >= 0) {
3036 unsigned Opc = V1.getOpcode();
3037 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3039 if (Opc != ISD::BUILD_VECTOR ||
3040 !X86::isZeroNode(V1.getOperand(Idx)))
3047 /// getZeroVector - Returns a vector of specified type with all zero elements.
3049 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3051 assert(VT.isVector() && "Expected a vector type");
3053 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3054 // type. This ensures they get CSE'd.
3056 if (VT.getSizeInBits() == 64) { // MMX
3057 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3058 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3059 } else if (HasSSE2) { // SSE2
3060 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3061 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3063 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3064 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3066 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3069 /// getOnesVector - Returns a vector of specified type with all bits set.
3071 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3072 assert(VT.isVector() && "Expected a vector type");
3074 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3075 // type. This ensures they get CSE'd.
3076 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3078 if (VT.getSizeInBits() == 64) // MMX
3079 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3081 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3082 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3086 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3087 /// that point to V2 points to its first element.
3088 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3089 EVT VT = SVOp->getValueType(0);
3090 unsigned NumElems = VT.getVectorNumElements();
3092 bool Changed = false;
3093 SmallVector<int, 8> MaskVec;
3094 SVOp->getMask(MaskVec);
3096 for (unsigned i = 0; i != NumElems; ++i) {
3097 if (MaskVec[i] > (int)NumElems) {
3098 MaskVec[i] = NumElems;
3103 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3104 SVOp->getOperand(1), &MaskVec[0]);
3105 return SDValue(SVOp, 0);
3108 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3109 /// operation of specified width.
3110 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3112 unsigned NumElems = VT.getVectorNumElements();
3113 SmallVector<int, 8> Mask;
3114 Mask.push_back(NumElems);
3115 for (unsigned i = 1; i != NumElems; ++i)
3117 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3120 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3121 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3123 unsigned NumElems = VT.getVectorNumElements();
3124 SmallVector<int, 8> Mask;
3125 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3127 Mask.push_back(i + NumElems);
3129 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3132 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3133 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3135 unsigned NumElems = VT.getVectorNumElements();
3136 unsigned Half = NumElems/2;
3137 SmallVector<int, 8> Mask;
3138 for (unsigned i = 0; i != Half; ++i) {
3139 Mask.push_back(i + Half);
3140 Mask.push_back(i + NumElems + Half);
3142 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3145 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3146 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3148 if (SV->getValueType(0).getVectorNumElements() <= 4)
3149 return SDValue(SV, 0);
3151 EVT PVT = MVT::v4f32;
3152 EVT VT = SV->getValueType(0);
3153 DebugLoc dl = SV->getDebugLoc();
3154 SDValue V1 = SV->getOperand(0);
3155 int NumElems = VT.getVectorNumElements();
3156 int EltNo = SV->getSplatIndex();
3158 // unpack elements to the correct location
3159 while (NumElems > 4) {
3160 if (EltNo < NumElems/2) {
3161 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3163 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3164 EltNo -= NumElems/2;
3169 // Perform the splat.
3170 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3171 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3172 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3173 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3176 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3177 /// vector of zero or undef vector. This produces a shuffle where the low
3178 /// element of V2 is swizzled into the zero/undef vector, landing at element
3179 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3180 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3181 bool isZero, bool HasSSE2,
3182 SelectionDAG &DAG) {
3183 EVT VT = V2.getValueType();
3185 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3186 unsigned NumElems = VT.getVectorNumElements();
3187 SmallVector<int, 16> MaskVec;
3188 for (unsigned i = 0; i != NumElems; ++i)
3189 // If this is the insertion idx, put the low elt of V2 here.
3190 MaskVec.push_back(i == Idx ? NumElems : i);
3191 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3194 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3195 /// a shuffle that is zero.
3197 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3198 bool Low, SelectionDAG &DAG) {
3199 unsigned NumZeros = 0;
3200 for (int i = 0; i < NumElems; ++i) {
3201 unsigned Index = Low ? i : NumElems-i-1;
3202 int Idx = SVOp->getMaskElt(Index);
3207 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3208 if (Elt.getNode() && X86::isZeroNode(Elt))
3216 /// isVectorShift - Returns true if the shuffle can be implemented as a
3217 /// logical left or right shift of a vector.
3218 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3219 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3220 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3221 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3224 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3227 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3231 bool SeenV1 = false;
3232 bool SeenV2 = false;
3233 for (int i = NumZeros; i < NumElems; ++i) {
3234 int Val = isLeft ? (i - NumZeros) : i;
3235 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3247 if (SeenV1 && SeenV2)
3250 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3256 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3258 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3259 unsigned NumNonZero, unsigned NumZero,
3260 SelectionDAG &DAG, TargetLowering &TLI) {
3264 DebugLoc dl = Op.getDebugLoc();
3267 for (unsigned i = 0; i < 16; ++i) {
3268 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3269 if (ThisIsNonZero && First) {
3271 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3273 V = DAG.getUNDEF(MVT::v8i16);
3278 SDValue ThisElt(0, 0), LastElt(0, 0);
3279 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3280 if (LastIsNonZero) {
3281 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3282 MVT::i16, Op.getOperand(i-1));
3284 if (ThisIsNonZero) {
3285 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3286 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3287 ThisElt, DAG.getConstant(8, MVT::i8));
3289 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3293 if (ThisElt.getNode())
3294 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3295 DAG.getIntPtrConstant(i/2));
3299 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3302 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3304 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3305 unsigned NumNonZero, unsigned NumZero,
3306 SelectionDAG &DAG, TargetLowering &TLI) {
3310 DebugLoc dl = Op.getDebugLoc();
3313 for (unsigned i = 0; i < 8; ++i) {
3314 bool isNonZero = (NonZeros & (1 << i)) != 0;
3318 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3320 V = DAG.getUNDEF(MVT::v8i16);
3323 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3324 MVT::v8i16, V, Op.getOperand(i),
3325 DAG.getIntPtrConstant(i));
3332 /// getVShift - Return a vector logical shift node.
3334 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3335 unsigned NumBits, SelectionDAG &DAG,
3336 const TargetLowering &TLI, DebugLoc dl) {
3337 bool isMMX = VT.getSizeInBits() == 64;
3338 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3339 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3340 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3341 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3342 DAG.getNode(Opc, dl, ShVT, SrcOp,
3343 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3347 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3348 DebugLoc dl = Op.getDebugLoc();
3349 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3350 if (ISD::isBuildVectorAllZeros(Op.getNode())
3351 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3352 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3353 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3354 // eliminated on x86-32 hosts.
3355 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3358 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3359 return getOnesVector(Op.getValueType(), DAG, dl);
3360 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3363 EVT VT = Op.getValueType();
3364 EVT ExtVT = VT.getVectorElementType();
3365 unsigned EVTBits = ExtVT.getSizeInBits();
3367 unsigned NumElems = Op.getNumOperands();
3368 unsigned NumZero = 0;
3369 unsigned NumNonZero = 0;
3370 unsigned NonZeros = 0;
3371 bool IsAllConstants = true;
3372 SmallSet<SDValue, 8> Values;
3373 for (unsigned i = 0; i < NumElems; ++i) {
3374 SDValue Elt = Op.getOperand(i);
3375 if (Elt.getOpcode() == ISD::UNDEF)
3378 if (Elt.getOpcode() != ISD::Constant &&
3379 Elt.getOpcode() != ISD::ConstantFP)
3380 IsAllConstants = false;
3381 if (X86::isZeroNode(Elt))
3384 NonZeros |= (1 << i);
3389 if (NumNonZero == 0) {
3390 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3391 return DAG.getUNDEF(VT);
3394 // Special case for single non-zero, non-undef, element.
3395 if (NumNonZero == 1) {
3396 unsigned Idx = CountTrailingZeros_32(NonZeros);
3397 SDValue Item = Op.getOperand(Idx);
3399 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3400 // the value are obviously zero, truncate the value to i32 and do the
3401 // insertion that way. Only do this if the value is non-constant or if the
3402 // value is a constant being inserted into element 0. It is cheaper to do
3403 // a constant pool load than it is to do a movd + shuffle.
3404 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3405 (!IsAllConstants || Idx == 0)) {
3406 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3407 // Handle MMX and SSE both.
3408 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3409 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3411 // Truncate the value (which may itself be a constant) to i32, and
3412 // convert it to a vector with movd (S2V+shuffle to zero extend).
3413 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3414 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3415 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3416 Subtarget->hasSSE2(), DAG);
3418 // Now we have our 32-bit value zero extended in the low element of
3419 // a vector. If Idx != 0, swizzle it into place.
3421 SmallVector<int, 4> Mask;
3422 Mask.push_back(Idx);
3423 for (unsigned i = 1; i != VecElts; ++i)
3425 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3426 DAG.getUNDEF(Item.getValueType()),
3429 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3433 // If we have a constant or non-constant insertion into the low element of
3434 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3435 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3436 // depending on what the source datatype is.
3439 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3440 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3441 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3442 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3443 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3444 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3446 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3447 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3448 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3449 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3450 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3451 Subtarget->hasSSE2(), DAG);
3452 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3456 // Is it a vector logical left shift?
3457 if (NumElems == 2 && Idx == 1 &&
3458 X86::isZeroNode(Op.getOperand(0)) &&
3459 !X86::isZeroNode(Op.getOperand(1))) {
3460 unsigned NumBits = VT.getSizeInBits();
3461 return getVShift(true, VT,
3462 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3463 VT, Op.getOperand(1)),
3464 NumBits/2, DAG, *this, dl);
3467 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3470 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3471 // is a non-constant being inserted into an element other than the low one,
3472 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3473 // movd/movss) to move this into the low element, then shuffle it into
3475 if (EVTBits == 32) {
3476 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3478 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3479 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3480 Subtarget->hasSSE2(), DAG);
3481 SmallVector<int, 8> MaskVec;
3482 for (unsigned i = 0; i < NumElems; i++)
3483 MaskVec.push_back(i == Idx ? 0 : 1);
3484 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3488 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3489 if (Values.size() == 1)
3492 // A vector full of immediates; various special cases are already
3493 // handled, so this is best done with a single constant-pool load.
3497 // Let legalizer expand 2-wide build_vectors.
3498 if (EVTBits == 64) {
3499 if (NumNonZero == 1) {
3500 // One half is zero or undef.
3501 unsigned Idx = CountTrailingZeros_32(NonZeros);
3502 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3503 Op.getOperand(Idx));
3504 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3505 Subtarget->hasSSE2(), DAG);
3510 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3511 if (EVTBits == 8 && NumElems == 16) {
3512 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3514 if (V.getNode()) return V;
3517 if (EVTBits == 16 && NumElems == 8) {
3518 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3520 if (V.getNode()) return V;
3523 // If element VT is == 32 bits, turn it into a number of shuffles.
3524 SmallVector<SDValue, 8> V;
3526 if (NumElems == 4 && NumZero > 0) {
3527 for (unsigned i = 0; i < 4; ++i) {
3528 bool isZero = !(NonZeros & (1 << i));
3530 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3532 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3535 for (unsigned i = 0; i < 2; ++i) {
3536 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3539 V[i] = V[i*2]; // Must be a zero vector.
3542 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3545 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3548 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3553 SmallVector<int, 8> MaskVec;
3554 bool Reverse = (NonZeros & 0x3) == 2;
3555 for (unsigned i = 0; i < 2; ++i)
3556 MaskVec.push_back(Reverse ? 1-i : i);
3557 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3558 for (unsigned i = 0; i < 2; ++i)
3559 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3560 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3563 if (Values.size() > 2) {
3564 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3565 // values to be inserted is equal to the number of elements, in which case
3566 // use the unpack code below in the hopes of matching the consecutive elts
3567 // load merge pattern for shuffles.
3568 // FIXME: We could probably just check that here directly.
3569 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3570 getSubtarget()->hasSSE41()) {
3571 V[0] = DAG.getUNDEF(VT);
3572 for (unsigned i = 0; i < NumElems; ++i)
3573 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3574 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3575 Op.getOperand(i), DAG.getIntPtrConstant(i));
3578 // Expand into a number of unpckl*.
3580 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3581 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3582 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3583 for (unsigned i = 0; i < NumElems; ++i)
3584 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3586 while (NumElems != 0) {
3587 for (unsigned i = 0; i < NumElems; ++i)
3588 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3597 // v8i16 shuffles - Prefer shuffles in the following order:
3598 // 1. [all] pshuflw, pshufhw, optional move
3599 // 2. [ssse3] 1 x pshufb
3600 // 3. [ssse3] 2 x pshufb + 1 x por
3601 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3603 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3604 SelectionDAG &DAG, X86TargetLowering &TLI) {
3605 SDValue V1 = SVOp->getOperand(0);
3606 SDValue V2 = SVOp->getOperand(1);
3607 DebugLoc dl = SVOp->getDebugLoc();
3608 SmallVector<int, 8> MaskVals;
3610 // Determine if more than 1 of the words in each of the low and high quadwords
3611 // of the result come from the same quadword of one of the two inputs. Undef
3612 // mask values count as coming from any quadword, for better codegen.
3613 SmallVector<unsigned, 4> LoQuad(4);
3614 SmallVector<unsigned, 4> HiQuad(4);
3615 BitVector InputQuads(4);
3616 for (unsigned i = 0; i < 8; ++i) {
3617 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3618 int EltIdx = SVOp->getMaskElt(i);
3619 MaskVals.push_back(EltIdx);
3628 InputQuads.set(EltIdx / 4);
3631 int BestLoQuad = -1;
3632 unsigned MaxQuad = 1;
3633 for (unsigned i = 0; i < 4; ++i) {
3634 if (LoQuad[i] > MaxQuad) {
3636 MaxQuad = LoQuad[i];
3640 int BestHiQuad = -1;
3642 for (unsigned i = 0; i < 4; ++i) {
3643 if (HiQuad[i] > MaxQuad) {
3645 MaxQuad = HiQuad[i];
3649 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3650 // of the two input vectors, shuffle them into one input vector so only a
3651 // single pshufb instruction is necessary. If There are more than 2 input
3652 // quads, disable the next transformation since it does not help SSSE3.
3653 bool V1Used = InputQuads[0] || InputQuads[1];
3654 bool V2Used = InputQuads[2] || InputQuads[3];
3655 if (TLI.getSubtarget()->hasSSSE3()) {
3656 if (InputQuads.count() == 2 && V1Used && V2Used) {
3657 BestLoQuad = InputQuads.find_first();
3658 BestHiQuad = InputQuads.find_next(BestLoQuad);
3660 if (InputQuads.count() > 2) {
3666 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3667 // the shuffle mask. If a quad is scored as -1, that means that it contains
3668 // words from all 4 input quadwords.
3670 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3671 SmallVector<int, 8> MaskV;
3672 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3673 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3674 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3675 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3676 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3677 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3679 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3680 // source words for the shuffle, to aid later transformations.
3681 bool AllWordsInNewV = true;
3682 bool InOrder[2] = { true, true };
3683 for (unsigned i = 0; i != 8; ++i) {
3684 int idx = MaskVals[i];
3686 InOrder[i/4] = false;
3687 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3689 AllWordsInNewV = false;
3693 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3694 if (AllWordsInNewV) {
3695 for (int i = 0; i != 8; ++i) {
3696 int idx = MaskVals[i];
3699 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3700 if ((idx != i) && idx < 4)
3702 if ((idx != i) && idx > 3)
3711 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3712 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3713 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3714 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3715 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3719 // If we have SSSE3, and all words of the result are from 1 input vector,
3720 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3721 // is present, fall back to case 4.
3722 if (TLI.getSubtarget()->hasSSSE3()) {
3723 SmallVector<SDValue,16> pshufbMask;
3725 // If we have elements from both input vectors, set the high bit of the
3726 // shuffle mask element to zero out elements that come from V2 in the V1
3727 // mask, and elements that come from V1 in the V2 mask, so that the two
3728 // results can be OR'd together.
3729 bool TwoInputs = V1Used && V2Used;
3730 for (unsigned i = 0; i != 8; ++i) {
3731 int EltIdx = MaskVals[i] * 2;
3732 if (TwoInputs && (EltIdx >= 16)) {
3733 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3734 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3737 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3738 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3740 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3741 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3742 DAG.getNode(ISD::BUILD_VECTOR, dl,
3743 MVT::v16i8, &pshufbMask[0], 16));
3745 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3747 // Calculate the shuffle mask for the second input, shuffle it, and
3748 // OR it with the first shuffled input.
3750 for (unsigned i = 0; i != 8; ++i) {
3751 int EltIdx = MaskVals[i] * 2;
3753 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3754 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3757 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3758 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3760 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3761 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3762 DAG.getNode(ISD::BUILD_VECTOR, dl,
3763 MVT::v16i8, &pshufbMask[0], 16));
3764 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3765 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3768 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3769 // and update MaskVals with new element order.
3770 BitVector InOrder(8);
3771 if (BestLoQuad >= 0) {
3772 SmallVector<int, 8> MaskV;
3773 for (int i = 0; i != 4; ++i) {
3774 int idx = MaskVals[i];
3776 MaskV.push_back(-1);
3778 } else if ((idx / 4) == BestLoQuad) {
3779 MaskV.push_back(idx & 3);
3782 MaskV.push_back(-1);
3785 for (unsigned i = 4; i != 8; ++i)
3787 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3791 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3792 // and update MaskVals with the new element order.
3793 if (BestHiQuad >= 0) {
3794 SmallVector<int, 8> MaskV;
3795 for (unsigned i = 0; i != 4; ++i)
3797 for (unsigned i = 4; i != 8; ++i) {
3798 int idx = MaskVals[i];
3800 MaskV.push_back(-1);
3802 } else if ((idx / 4) == BestHiQuad) {
3803 MaskV.push_back((idx & 3) + 4);
3806 MaskV.push_back(-1);
3809 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3813 // In case BestHi & BestLo were both -1, which means each quadword has a word
3814 // from each of the four input quadwords, calculate the InOrder bitvector now
3815 // before falling through to the insert/extract cleanup.
3816 if (BestLoQuad == -1 && BestHiQuad == -1) {
3818 for (int i = 0; i != 8; ++i)
3819 if (MaskVals[i] < 0 || MaskVals[i] == i)
3823 // The other elements are put in the right place using pextrw and pinsrw.
3824 for (unsigned i = 0; i != 8; ++i) {
3827 int EltIdx = MaskVals[i];
3830 SDValue ExtOp = (EltIdx < 8)
3831 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3832 DAG.getIntPtrConstant(EltIdx))
3833 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3834 DAG.getIntPtrConstant(EltIdx - 8));
3835 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3836 DAG.getIntPtrConstant(i));
3841 // v16i8 shuffles - Prefer shuffles in the following order:
3842 // 1. [ssse3] 1 x pshufb
3843 // 2. [ssse3] 2 x pshufb + 1 x por
3844 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3846 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3847 SelectionDAG &DAG, X86TargetLowering &TLI) {
3848 SDValue V1 = SVOp->getOperand(0);
3849 SDValue V2 = SVOp->getOperand(1);
3850 DebugLoc dl = SVOp->getDebugLoc();
3851 SmallVector<int, 16> MaskVals;
3852 SVOp->getMask(MaskVals);
3854 // If we have SSSE3, case 1 is generated when all result bytes come from
3855 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3856 // present, fall back to case 3.
3857 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3860 for (unsigned i = 0; i < 16; ++i) {
3861 int EltIdx = MaskVals[i];
3870 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3871 if (TLI.getSubtarget()->hasSSSE3()) {
3872 SmallVector<SDValue,16> pshufbMask;
3874 // If all result elements are from one input vector, then only translate
3875 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3877 // Otherwise, we have elements from both input vectors, and must zero out
3878 // elements that come from V2 in the first mask, and V1 in the second mask
3879 // so that we can OR them together.
3880 bool TwoInputs = !(V1Only || V2Only);
3881 for (unsigned i = 0; i != 16; ++i) {
3882 int EltIdx = MaskVals[i];
3883 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3884 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3887 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3889 // If all the elements are from V2, assign it to V1 and return after
3890 // building the first pshufb.
3893 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3894 DAG.getNode(ISD::BUILD_VECTOR, dl,
3895 MVT::v16i8, &pshufbMask[0], 16));
3899 // Calculate the shuffle mask for the second input, shuffle it, and
3900 // OR it with the first shuffled input.
3902 for (unsigned i = 0; i != 16; ++i) {
3903 int EltIdx = MaskVals[i];
3905 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3908 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3910 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3911 DAG.getNode(ISD::BUILD_VECTOR, dl,
3912 MVT::v16i8, &pshufbMask[0], 16));
3913 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3916 // No SSSE3 - Calculate in place words and then fix all out of place words
3917 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3918 // the 16 different words that comprise the two doublequadword input vectors.
3919 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3920 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3921 SDValue NewV = V2Only ? V2 : V1;
3922 for (int i = 0; i != 8; ++i) {
3923 int Elt0 = MaskVals[i*2];
3924 int Elt1 = MaskVals[i*2+1];
3926 // This word of the result is all undef, skip it.
3927 if (Elt0 < 0 && Elt1 < 0)
3930 // This word of the result is already in the correct place, skip it.
3931 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3933 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3936 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3937 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3940 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3941 // using a single extract together, load it and store it.
3942 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3943 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3944 DAG.getIntPtrConstant(Elt1 / 2));
3945 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3946 DAG.getIntPtrConstant(i));
3950 // If Elt1 is defined, extract it from the appropriate source. If the
3951 // source byte is not also odd, shift the extracted word left 8 bits
3952 // otherwise clear the bottom 8 bits if we need to do an or.
3954 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3955 DAG.getIntPtrConstant(Elt1 / 2));
3956 if ((Elt1 & 1) == 0)
3957 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3958 DAG.getConstant(8, TLI.getShiftAmountTy()));
3960 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3961 DAG.getConstant(0xFF00, MVT::i16));
3963 // If Elt0 is defined, extract it from the appropriate source. If the
3964 // source byte is not also even, shift the extracted word right 8 bits. If
3965 // Elt1 was also defined, OR the extracted values together before
3966 // inserting them in the result.
3968 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3969 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3970 if ((Elt0 & 1) != 0)
3971 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3972 DAG.getConstant(8, TLI.getShiftAmountTy()));
3974 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3975 DAG.getConstant(0x00FF, MVT::i16));
3976 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3979 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3980 DAG.getIntPtrConstant(i));
3982 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3985 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3986 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3987 /// done when every pair / quad of shuffle mask elements point to elements in
3988 /// the right sequence. e.g.
3989 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3991 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3993 TargetLowering &TLI, DebugLoc dl) {
3994 EVT VT = SVOp->getValueType(0);
3995 SDValue V1 = SVOp->getOperand(0);
3996 SDValue V2 = SVOp->getOperand(1);
3997 unsigned NumElems = VT.getVectorNumElements();
3998 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3999 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4000 EVT MaskEltVT = MaskVT.getVectorElementType();
4002 switch (VT.getSimpleVT().SimpleTy) {
4003 default: assert(false && "Unexpected!");
4004 case MVT::v4f32: NewVT = MVT::v2f64; break;
4005 case MVT::v4i32: NewVT = MVT::v2i64; break;
4006 case MVT::v8i16: NewVT = MVT::v4i32; break;
4007 case MVT::v16i8: NewVT = MVT::v4i32; break;
4010 if (NewWidth == 2) {
4016 int Scale = NumElems / NewWidth;
4017 SmallVector<int, 8> MaskVec;
4018 for (unsigned i = 0; i < NumElems; i += Scale) {
4020 for (int j = 0; j < Scale; ++j) {
4021 int EltIdx = SVOp->getMaskElt(i+j);
4025 StartIdx = EltIdx - (EltIdx % Scale);
4026 if (EltIdx != StartIdx + j)
4030 MaskVec.push_back(-1);
4032 MaskVec.push_back(StartIdx / Scale);
4035 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4036 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4037 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4040 /// getVZextMovL - Return a zero-extending vector move low node.
4042 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4043 SDValue SrcOp, SelectionDAG &DAG,
4044 const X86Subtarget *Subtarget, DebugLoc dl) {
4045 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4046 LoadSDNode *LD = NULL;
4047 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4048 LD = dyn_cast<LoadSDNode>(SrcOp);
4050 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4052 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4053 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4054 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4055 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4056 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4058 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4059 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4060 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4061 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4069 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4070 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4071 DAG.getNode(ISD::BIT_CONVERT, dl,
4075 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4078 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4079 SDValue V1 = SVOp->getOperand(0);
4080 SDValue V2 = SVOp->getOperand(1);
4081 DebugLoc dl = SVOp->getDebugLoc();
4082 EVT VT = SVOp->getValueType(0);
4084 SmallVector<std::pair<int, int>, 8> Locs;
4086 SmallVector<int, 8> Mask1(4U, -1);
4087 SmallVector<int, 8> PermMask;
4088 SVOp->getMask(PermMask);
4092 for (unsigned i = 0; i != 4; ++i) {
4093 int Idx = PermMask[i];
4095 Locs[i] = std::make_pair(-1, -1);
4097 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4099 Locs[i] = std::make_pair(0, NumLo);
4103 Locs[i] = std::make_pair(1, NumHi);
4105 Mask1[2+NumHi] = Idx;
4111 if (NumLo <= 2 && NumHi <= 2) {
4112 // If no more than two elements come from either vector. This can be
4113 // implemented with two shuffles. First shuffle gather the elements.
4114 // The second shuffle, which takes the first shuffle as both of its
4115 // vector operands, put the elements into the right order.
4116 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4118 SmallVector<int, 8> Mask2(4U, -1);
4120 for (unsigned i = 0; i != 4; ++i) {
4121 if (Locs[i].first == -1)
4124 unsigned Idx = (i < 2) ? 0 : 4;
4125 Idx += Locs[i].first * 2 + Locs[i].second;
4130 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4131 } else if (NumLo == 3 || NumHi == 3) {
4132 // Otherwise, we must have three elements from one vector, call it X, and
4133 // one element from the other, call it Y. First, use a shufps to build an
4134 // intermediate vector with the one element from Y and the element from X
4135 // that will be in the same half in the final destination (the indexes don't
4136 // matter). Then, use a shufps to build the final vector, taking the half
4137 // containing the element from Y from the intermediate, and the other half
4140 // Normalize it so the 3 elements come from V1.
4141 CommuteVectorShuffleMask(PermMask, VT);
4145 // Find the element from V2.
4147 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4148 int Val = PermMask[HiIndex];
4155 Mask1[0] = PermMask[HiIndex];
4157 Mask1[2] = PermMask[HiIndex^1];
4159 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4162 Mask1[0] = PermMask[0];
4163 Mask1[1] = PermMask[1];
4164 Mask1[2] = HiIndex & 1 ? 6 : 4;
4165 Mask1[3] = HiIndex & 1 ? 4 : 6;
4166 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4168 Mask1[0] = HiIndex & 1 ? 2 : 0;
4169 Mask1[1] = HiIndex & 1 ? 0 : 2;
4170 Mask1[2] = PermMask[2];
4171 Mask1[3] = PermMask[3];
4176 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4180 // Break it into (shuffle shuffle_hi, shuffle_lo).
4182 SmallVector<int,8> LoMask(4U, -1);
4183 SmallVector<int,8> HiMask(4U, -1);
4185 SmallVector<int,8> *MaskPtr = &LoMask;
4186 unsigned MaskIdx = 0;
4189 for (unsigned i = 0; i != 4; ++i) {
4196 int Idx = PermMask[i];
4198 Locs[i] = std::make_pair(-1, -1);
4199 } else if (Idx < 4) {
4200 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4201 (*MaskPtr)[LoIdx] = Idx;
4204 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4205 (*MaskPtr)[HiIdx] = Idx;
4210 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4211 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4212 SmallVector<int, 8> MaskOps;
4213 for (unsigned i = 0; i != 4; ++i) {
4214 if (Locs[i].first == -1) {
4215 MaskOps.push_back(-1);
4217 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4218 MaskOps.push_back(Idx);
4221 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4225 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4226 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4227 SDValue V1 = Op.getOperand(0);
4228 SDValue V2 = Op.getOperand(1);
4229 EVT VT = Op.getValueType();
4230 DebugLoc dl = Op.getDebugLoc();
4231 unsigned NumElems = VT.getVectorNumElements();
4232 bool isMMX = VT.getSizeInBits() == 64;
4233 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4234 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4235 bool V1IsSplat = false;
4236 bool V2IsSplat = false;
4238 if (isZeroShuffle(SVOp))
4239 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4241 // Promote splats to v4f32.
4242 if (SVOp->isSplat()) {
4243 if (isMMX || NumElems < 4)
4245 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4248 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4250 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4251 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4252 if (NewOp.getNode())
4253 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4254 LowerVECTOR_SHUFFLE(NewOp, DAG));
4255 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4256 // FIXME: Figure out a cleaner way to do this.
4257 // Try to make use of movq to zero out the top part.
4258 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4259 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4260 if (NewOp.getNode()) {
4261 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4262 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4263 DAG, Subtarget, dl);
4265 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4266 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4267 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4268 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4269 DAG, Subtarget, dl);
4273 if (X86::isPSHUFDMask(SVOp))
4276 // Check if this can be converted into a logical shift.
4277 bool isLeft = false;
4280 bool isShift = getSubtarget()->hasSSE2() &&
4281 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4282 if (isShift && ShVal.hasOneUse()) {
4283 // If the shifted value has multiple uses, it may be cheaper to use
4284 // v_set0 + movlhps or movhlps, etc.
4285 EVT EltVT = VT.getVectorElementType();
4286 ShAmt *= EltVT.getSizeInBits();
4287 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4290 if (X86::isMOVLMask(SVOp)) {
4293 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4294 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4299 // FIXME: fold these into legal mask.
4300 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4301 X86::isMOVSLDUPMask(SVOp) ||
4302 X86::isMOVHLPSMask(SVOp) ||
4303 X86::isMOVLHPSMask(SVOp) ||
4304 X86::isMOVLPMask(SVOp)))
4307 if (ShouldXformToMOVHLPS(SVOp) ||
4308 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4309 return CommuteVectorShuffle(SVOp, DAG);
4312 // No better options. Use a vshl / vsrl.
4313 EVT EltVT = VT.getVectorElementType();
4314 ShAmt *= EltVT.getSizeInBits();
4315 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4318 bool Commuted = false;
4319 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4320 // 1,1,1,1 -> v8i16 though.
4321 V1IsSplat = isSplatVector(V1.getNode());
4322 V2IsSplat = isSplatVector(V2.getNode());
4324 // Canonicalize the splat or undef, if present, to be on the RHS.
4325 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4326 Op = CommuteVectorShuffle(SVOp, DAG);
4327 SVOp = cast<ShuffleVectorSDNode>(Op);
4328 V1 = SVOp->getOperand(0);
4329 V2 = SVOp->getOperand(1);
4330 std::swap(V1IsSplat, V2IsSplat);
4331 std::swap(V1IsUndef, V2IsUndef);
4335 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4336 // Shuffling low element of v1 into undef, just return v1.
4339 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4340 // the instruction selector will not match, so get a canonical MOVL with
4341 // swapped operands to undo the commute.
4342 return getMOVL(DAG, dl, VT, V2, V1);
4345 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4346 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4347 X86::isUNPCKLMask(SVOp) ||
4348 X86::isUNPCKHMask(SVOp))
4352 // Normalize mask so all entries that point to V2 points to its first
4353 // element then try to match unpck{h|l} again. If match, return a
4354 // new vector_shuffle with the corrected mask.
4355 SDValue NewMask = NormalizeMask(SVOp, DAG);
4356 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4357 if (NSVOp != SVOp) {
4358 if (X86::isUNPCKLMask(NSVOp, true)) {
4360 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4367 // Commute is back and try unpck* again.
4368 // FIXME: this seems wrong.
4369 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4370 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4371 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4372 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4373 X86::isUNPCKLMask(NewSVOp) ||
4374 X86::isUNPCKHMask(NewSVOp))
4378 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4380 // Normalize the node to match x86 shuffle ops if needed
4381 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4382 return CommuteVectorShuffle(SVOp, DAG);
4384 // Check for legal shuffle and return?
4385 SmallVector<int, 16> PermMask;
4386 SVOp->getMask(PermMask);
4387 if (isShuffleMaskLegal(PermMask, VT))
4390 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4391 if (VT == MVT::v8i16) {
4392 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4393 if (NewOp.getNode())
4397 if (VT == MVT::v16i8) {
4398 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4399 if (NewOp.getNode())
4403 // Handle all 4 wide cases with a number of shuffles except for MMX.
4404 if (NumElems == 4 && !isMMX)
4405 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4411 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4412 SelectionDAG &DAG) {
4413 EVT VT = Op.getValueType();
4414 DebugLoc dl = Op.getDebugLoc();
4415 if (VT.getSizeInBits() == 8) {
4416 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4417 Op.getOperand(0), Op.getOperand(1));
4418 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4419 DAG.getValueType(VT));
4420 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4421 } else if (VT.getSizeInBits() == 16) {
4422 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4423 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4425 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4426 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4427 DAG.getNode(ISD::BIT_CONVERT, dl,
4431 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4432 Op.getOperand(0), Op.getOperand(1));
4433 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4434 DAG.getValueType(VT));
4435 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4436 } else if (VT == MVT::f32) {
4437 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4438 // the result back to FR32 register. It's only worth matching if the
4439 // result has a single use which is a store or a bitcast to i32. And in
4440 // the case of a store, it's not worth it if the index is a constant 0,
4441 // because a MOVSSmr can be used instead, which is smaller and faster.
4442 if (!Op.hasOneUse())
4444 SDNode *User = *Op.getNode()->use_begin();
4445 if ((User->getOpcode() != ISD::STORE ||
4446 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4447 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4448 (User->getOpcode() != ISD::BIT_CONVERT ||
4449 User->getValueType(0) != MVT::i32))
4451 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4452 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4455 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4456 } else if (VT == MVT::i32) {
4457 // ExtractPS works with constant index.
4458 if (isa<ConstantSDNode>(Op.getOperand(1)))
4466 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4467 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4470 if (Subtarget->hasSSE41()) {
4471 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4476 EVT VT = Op.getValueType();
4477 DebugLoc dl = Op.getDebugLoc();
4478 // TODO: handle v16i8.
4479 if (VT.getSizeInBits() == 16) {
4480 SDValue Vec = Op.getOperand(0);
4481 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4483 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4484 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4485 DAG.getNode(ISD::BIT_CONVERT, dl,
4488 // Transform it so it match pextrw which produces a 32-bit result.
4489 EVT EltVT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy+1);
4490 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4491 Op.getOperand(0), Op.getOperand(1));
4492 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4493 DAG.getValueType(VT));
4494 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4495 } else if (VT.getSizeInBits() == 32) {
4496 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4500 // SHUFPS the element to the lowest double word, then movss.
4501 int Mask[4] = { Idx, -1, -1, -1 };
4502 EVT VVT = Op.getOperand(0).getValueType();
4503 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4504 DAG.getUNDEF(VVT), Mask);
4505 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4506 DAG.getIntPtrConstant(0));
4507 } else if (VT.getSizeInBits() == 64) {
4508 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4509 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4510 // to match extract_elt for f64.
4511 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4515 // UNPCKHPD the element to the lowest double word, then movsd.
4516 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4517 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4518 int Mask[2] = { 1, -1 };
4519 EVT VVT = Op.getOperand(0).getValueType();
4520 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4521 DAG.getUNDEF(VVT), Mask);
4522 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4523 DAG.getIntPtrConstant(0));
4530 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4531 EVT VT = Op.getValueType();
4532 EVT EltVT = VT.getVectorElementType();
4533 DebugLoc dl = Op.getDebugLoc();
4535 SDValue N0 = Op.getOperand(0);
4536 SDValue N1 = Op.getOperand(1);
4537 SDValue N2 = Op.getOperand(2);
4539 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4540 isa<ConstantSDNode>(N2)) {
4541 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4543 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4545 if (N1.getValueType() != MVT::i32)
4546 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4547 if (N2.getValueType() != MVT::i32)
4548 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4549 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4550 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4551 // Bits [7:6] of the constant are the source select. This will always be
4552 // zero here. The DAG Combiner may combine an extract_elt index into these
4553 // bits. For example (insert (extract, 3), 2) could be matched by putting
4554 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4555 // Bits [5:4] of the constant are the destination select. This is the
4556 // value of the incoming immediate.
4557 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4558 // combine either bitwise AND or insert of float 0.0 to set these bits.
4559 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4560 // Create this as a scalar to vector..
4561 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4562 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4563 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4564 // PINSR* works with constant index.
4571 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4572 EVT VT = Op.getValueType();
4573 EVT EltVT = VT.getVectorElementType();
4575 if (Subtarget->hasSSE41())
4576 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4578 if (EltVT == MVT::i8)
4581 DebugLoc dl = Op.getDebugLoc();
4582 SDValue N0 = Op.getOperand(0);
4583 SDValue N1 = Op.getOperand(1);
4584 SDValue N2 = Op.getOperand(2);
4586 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4587 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4588 // as its second argument.
4589 if (N1.getValueType() != MVT::i32)
4590 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4591 if (N2.getValueType() != MVT::i32)
4592 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4593 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4599 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4600 DebugLoc dl = Op.getDebugLoc();
4601 if (Op.getValueType() == MVT::v2f32)
4602 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4603 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4604 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4605 Op.getOperand(0))));
4607 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4608 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4610 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4611 EVT VT = MVT::v2i32;
4612 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4619 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4620 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4623 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4624 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4625 // one of the above mentioned nodes. It has to be wrapped because otherwise
4626 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4627 // be used to form addressing mode. These wrapped nodes will be selected
4630 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4631 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4633 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4635 unsigned char OpFlag = 0;
4636 unsigned WrapperKind = X86ISD::Wrapper;
4637 CodeModel::Model M = getTargetMachine().getCodeModel();
4639 if (Subtarget->isPICStyleRIPRel() &&
4640 (M == CodeModel::Small || M == CodeModel::Kernel))
4641 WrapperKind = X86ISD::WrapperRIP;
4642 else if (Subtarget->isPICStyleGOT())
4643 OpFlag = X86II::MO_GOTOFF;
4644 else if (Subtarget->isPICStyleStubPIC())
4645 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4647 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4649 CP->getOffset(), OpFlag);
4650 DebugLoc DL = CP->getDebugLoc();
4651 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4652 // With PIC, the address is actually $g + Offset.
4654 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4655 DAG.getNode(X86ISD::GlobalBaseReg,
4656 DebugLoc::getUnknownLoc(), getPointerTy()),
4663 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4664 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4666 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4668 unsigned char OpFlag = 0;
4669 unsigned WrapperKind = X86ISD::Wrapper;
4670 CodeModel::Model M = getTargetMachine().getCodeModel();
4672 if (Subtarget->isPICStyleRIPRel() &&
4673 (M == CodeModel::Small || M == CodeModel::Kernel))
4674 WrapperKind = X86ISD::WrapperRIP;
4675 else if (Subtarget->isPICStyleGOT())
4676 OpFlag = X86II::MO_GOTOFF;
4677 else if (Subtarget->isPICStyleStubPIC())
4678 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4680 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4682 DebugLoc DL = JT->getDebugLoc();
4683 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4685 // With PIC, the address is actually $g + Offset.
4687 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4688 DAG.getNode(X86ISD::GlobalBaseReg,
4689 DebugLoc::getUnknownLoc(), getPointerTy()),
4697 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4698 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4700 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4702 unsigned char OpFlag = 0;
4703 unsigned WrapperKind = X86ISD::Wrapper;
4704 CodeModel::Model M = getTargetMachine().getCodeModel();
4706 if (Subtarget->isPICStyleRIPRel() &&
4707 (M == CodeModel::Small || M == CodeModel::Kernel))
4708 WrapperKind = X86ISD::WrapperRIP;
4709 else if (Subtarget->isPICStyleGOT())
4710 OpFlag = X86II::MO_GOTOFF;
4711 else if (Subtarget->isPICStyleStubPIC())
4712 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4714 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4716 DebugLoc DL = Op.getDebugLoc();
4717 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4720 // With PIC, the address is actually $g + Offset.
4721 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4722 !Subtarget->is64Bit()) {
4723 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4724 DAG.getNode(X86ISD::GlobalBaseReg,
4725 DebugLoc::getUnknownLoc(),
4734 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4735 // Create the TargetBlockAddressAddress node.
4736 unsigned char OpFlags =
4737 Subtarget->ClassifyBlockAddressReference();
4738 CodeModel::Model M = getTargetMachine().getCodeModel();
4739 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4740 DebugLoc dl = Op.getDebugLoc();
4741 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4742 /*isTarget=*/true, OpFlags);
4744 if (Subtarget->isPICStyleRIPRel() &&
4745 (M == CodeModel::Small || M == CodeModel::Kernel))
4746 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4748 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4750 // With PIC, the address is actually $g + Offset.
4751 if (isGlobalRelativeToPICBase(OpFlags)) {
4752 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4753 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4761 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4763 SelectionDAG &DAG) const {
4764 // Create the TargetGlobalAddress node, folding in the constant
4765 // offset if it is legal.
4766 unsigned char OpFlags =
4767 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4768 CodeModel::Model M = getTargetMachine().getCodeModel();
4770 if (OpFlags == X86II::MO_NO_FLAG &&
4771 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4772 // A direct static reference to a global.
4773 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4776 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4779 if (Subtarget->isPICStyleRIPRel() &&
4780 (M == CodeModel::Small || M == CodeModel::Kernel))
4781 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4783 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4785 // With PIC, the address is actually $g + Offset.
4786 if (isGlobalRelativeToPICBase(OpFlags)) {
4787 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4788 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4792 // For globals that require a load from a stub to get the address, emit the
4794 if (isGlobalStubReference(OpFlags))
4795 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4796 PseudoSourceValue::getGOT(), 0);
4798 // If there was a non-zero offset that we didn't fold, create an explicit
4801 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4802 DAG.getConstant(Offset, getPointerTy()));
4808 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4809 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4810 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4811 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4815 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4816 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4817 unsigned char OperandFlags) {
4818 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4819 DebugLoc dl = GA->getDebugLoc();
4820 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4821 GA->getValueType(0),
4825 SDValue Ops[] = { Chain, TGA, *InFlag };
4826 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4828 SDValue Ops[] = { Chain, TGA };
4829 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4831 SDValue Flag = Chain.getValue(1);
4832 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4835 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4837 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4840 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4841 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4842 DAG.getNode(X86ISD::GlobalBaseReg,
4843 DebugLoc::getUnknownLoc(),
4845 InFlag = Chain.getValue(1);
4847 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4850 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4852 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4854 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4855 X86::RAX, X86II::MO_TLSGD);
4858 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4859 // "local exec" model.
4860 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4861 const EVT PtrVT, TLSModel::Model model,
4863 DebugLoc dl = GA->getDebugLoc();
4864 // Get the Thread Pointer
4865 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4866 DebugLoc::getUnknownLoc(), PtrVT,
4867 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4870 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4873 unsigned char OperandFlags = 0;
4874 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4876 unsigned WrapperKind = X86ISD::Wrapper;
4877 if (model == TLSModel::LocalExec) {
4878 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4879 } else if (is64Bit) {
4880 assert(model == TLSModel::InitialExec);
4881 OperandFlags = X86II::MO_GOTTPOFF;
4882 WrapperKind = X86ISD::WrapperRIP;
4884 assert(model == TLSModel::InitialExec);
4885 OperandFlags = X86II::MO_INDNTPOFF;
4888 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4890 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4891 GA->getOffset(), OperandFlags);
4892 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4894 if (model == TLSModel::InitialExec)
4895 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4896 PseudoSourceValue::getGOT(), 0);
4898 // The address of the thread local variable is the add of the thread
4899 // pointer with the offset of the variable.
4900 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4904 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4905 // TODO: implement the "local dynamic" model
4906 // TODO: implement the "initial exec"model for pic executables
4907 assert(Subtarget->isTargetELF() &&
4908 "TLS not implemented for non-ELF targets");
4909 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4910 const GlobalValue *GV = GA->getGlobal();
4912 // If GV is an alias then use the aliasee for determining
4913 // thread-localness.
4914 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4915 GV = GA->resolveAliasedGlobal(false);
4917 TLSModel::Model model = getTLSModel(GV,
4918 getTargetMachine().getRelocationModel());
4921 case TLSModel::GeneralDynamic:
4922 case TLSModel::LocalDynamic: // not implemented
4923 if (Subtarget->is64Bit())
4924 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4925 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4927 case TLSModel::InitialExec:
4928 case TLSModel::LocalExec:
4929 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4930 Subtarget->is64Bit());
4933 llvm_unreachable("Unreachable");
4938 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4939 /// take a 2 x i32 value to shift plus a shift amount.
4940 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4941 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4942 EVT VT = Op.getValueType();
4943 unsigned VTBits = VT.getSizeInBits();
4944 DebugLoc dl = Op.getDebugLoc();
4945 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4946 SDValue ShOpLo = Op.getOperand(0);
4947 SDValue ShOpHi = Op.getOperand(1);
4948 SDValue ShAmt = Op.getOperand(2);
4949 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4950 DAG.getConstant(VTBits - 1, MVT::i8))
4951 : DAG.getConstant(0, VT);
4954 if (Op.getOpcode() == ISD::SHL_PARTS) {
4955 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4956 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4958 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4959 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4962 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4963 DAG.getConstant(VTBits, MVT::i8));
4964 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4965 AndNode, DAG.getConstant(0, MVT::i8));
4968 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4969 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4970 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4972 if (Op.getOpcode() == ISD::SHL_PARTS) {
4973 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4974 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4976 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4977 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4980 SDValue Ops[2] = { Lo, Hi };
4981 return DAG.getMergeValues(Ops, 2, dl);
4984 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4985 EVT SrcVT = Op.getOperand(0).getValueType();
4987 if (SrcVT.isVector()) {
4988 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4994 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4995 "Unknown SINT_TO_FP to lower!");
4997 // These are really Legal; return the operand so the caller accepts it as
4999 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5001 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5002 Subtarget->is64Bit()) {
5006 DebugLoc dl = Op.getDebugLoc();
5007 unsigned Size = SrcVT.getSizeInBits()/8;
5008 MachineFunction &MF = DAG.getMachineFunction();
5009 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5010 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5011 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5013 PseudoSourceValue::getFixedStack(SSFI), 0);
5014 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5017 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5019 SelectionDAG &DAG) {
5021 DebugLoc dl = Op.getDebugLoc();
5023 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5025 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5027 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5028 SmallVector<SDValue, 8> Ops;
5029 Ops.push_back(Chain);
5030 Ops.push_back(StackSlot);
5031 Ops.push_back(DAG.getValueType(SrcVT));
5032 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5033 Tys, &Ops[0], Ops.size());
5036 Chain = Result.getValue(1);
5037 SDValue InFlag = Result.getValue(2);
5039 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5040 // shouldn't be necessary except that RFP cannot be live across
5041 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5042 MachineFunction &MF = DAG.getMachineFunction();
5043 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5044 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5045 Tys = DAG.getVTList(MVT::Other);
5046 SmallVector<SDValue, 8> Ops;
5047 Ops.push_back(Chain);
5048 Ops.push_back(Result);
5049 Ops.push_back(StackSlot);
5050 Ops.push_back(DAG.getValueType(Op.getValueType()));
5051 Ops.push_back(InFlag);
5052 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5053 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5054 PseudoSourceValue::getFixedStack(SSFI), 0);
5060 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5061 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5062 // This algorithm is not obvious. Here it is in C code, more or less:
5064 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5065 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5066 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5068 // Copy ints to xmm registers.
5069 __m128i xh = _mm_cvtsi32_si128( hi );
5070 __m128i xl = _mm_cvtsi32_si128( lo );
5072 // Combine into low half of a single xmm register.
5073 __m128i x = _mm_unpacklo_epi32( xh, xl );
5077 // Merge in appropriate exponents to give the integer bits the right
5079 x = _mm_unpacklo_epi32( x, exp );
5081 // Subtract away the biases to deal with the IEEE-754 double precision
5083 d = _mm_sub_pd( (__m128d) x, bias );
5085 // All conversions up to here are exact. The correctly rounded result is
5086 // calculated using the current rounding mode using the following
5088 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5089 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5090 // store doesn't really need to be here (except
5091 // maybe to zero the other double)
5096 DebugLoc dl = Op.getDebugLoc();
5097 LLVMContext *Context = DAG.getContext();
5099 // Build some magic constants.
5100 std::vector<Constant*> CV0;
5101 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5102 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5103 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5104 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5105 Constant *C0 = ConstantVector::get(CV0);
5106 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5108 std::vector<Constant*> CV1;
5110 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5112 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5113 Constant *C1 = ConstantVector::get(CV1);
5114 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5116 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5117 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5119 DAG.getIntPtrConstant(1)));
5120 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5121 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5123 DAG.getIntPtrConstant(0)));
5124 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5125 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5126 PseudoSourceValue::getConstantPool(), 0,
5128 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5129 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5130 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5131 PseudoSourceValue::getConstantPool(), 0,
5133 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5135 // Add the halves; easiest way is to swap them into another reg first.
5136 int ShufMask[2] = { 1, -1 };
5137 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5138 DAG.getUNDEF(MVT::v2f64), ShufMask);
5139 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5140 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5141 DAG.getIntPtrConstant(0));
5144 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5145 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5146 DebugLoc dl = Op.getDebugLoc();
5147 // FP constant to bias correct the final result.
5148 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5151 // Load the 32-bit value into an XMM register.
5152 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5153 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5155 DAG.getIntPtrConstant(0)));
5157 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5158 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5159 DAG.getIntPtrConstant(0));
5161 // Or the load with the bias.
5162 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5163 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5164 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5166 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5167 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5168 MVT::v2f64, Bias)));
5169 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5170 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5171 DAG.getIntPtrConstant(0));
5173 // Subtract the bias.
5174 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5176 // Handle final rounding.
5177 EVT DestVT = Op.getValueType();
5179 if (DestVT.bitsLT(MVT::f64)) {
5180 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5181 DAG.getIntPtrConstant(0));
5182 } else if (DestVT.bitsGT(MVT::f64)) {
5183 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5186 // Handle final rounding.
5190 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5191 SDValue N0 = Op.getOperand(0);
5192 DebugLoc dl = Op.getDebugLoc();
5194 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5195 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5196 // the optimization here.
5197 if (DAG.SignBitIsZero(N0))
5198 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5200 EVT SrcVT = N0.getValueType();
5201 if (SrcVT == MVT::i64) {
5202 // We only handle SSE2 f64 target here; caller can expand the rest.
5203 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5206 return LowerUINT_TO_FP_i64(Op, DAG);
5207 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5208 return LowerUINT_TO_FP_i32(Op, DAG);
5211 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5213 // Make a 64-bit buffer, and use it to build an FILD.
5214 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5215 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5216 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5217 getPointerTy(), StackSlot, WordOff);
5218 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5219 StackSlot, NULL, 0);
5220 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5221 OffsetSlot, NULL, 0);
5222 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5225 std::pair<SDValue,SDValue> X86TargetLowering::
5226 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5227 DebugLoc dl = Op.getDebugLoc();
5229 EVT DstTy = Op.getValueType();
5232 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5236 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5237 DstTy.getSimpleVT() >= MVT::i16 &&
5238 "Unknown FP_TO_SINT to lower!");
5240 // These are really Legal.
5241 if (DstTy == MVT::i32 &&
5242 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5243 return std::make_pair(SDValue(), SDValue());
5244 if (Subtarget->is64Bit() &&
5245 DstTy == MVT::i64 &&
5246 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5247 return std::make_pair(SDValue(), SDValue());
5249 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5251 MachineFunction &MF = DAG.getMachineFunction();
5252 unsigned MemSize = DstTy.getSizeInBits()/8;
5253 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5254 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5257 switch (DstTy.getSimpleVT().SimpleTy) {
5258 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5259 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5260 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5261 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5264 SDValue Chain = DAG.getEntryNode();
5265 SDValue Value = Op.getOperand(0);
5266 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5267 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5268 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5269 PseudoSourceValue::getFixedStack(SSFI), 0);
5270 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5272 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5274 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5275 Chain = Value.getValue(1);
5276 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5277 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5280 // Build the FP_TO_INT*_IN_MEM
5281 SDValue Ops[] = { Chain, Value, StackSlot };
5282 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5284 return std::make_pair(FIST, StackSlot);
5287 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5288 if (Op.getValueType().isVector()) {
5289 if (Op.getValueType() == MVT::v2i32 &&
5290 Op.getOperand(0).getValueType() == MVT::v2f64) {
5296 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5297 SDValue FIST = Vals.first, StackSlot = Vals.second;
5298 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5299 if (FIST.getNode() == 0) return Op;
5302 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5303 FIST, StackSlot, NULL, 0);
5306 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5307 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5308 SDValue FIST = Vals.first, StackSlot = Vals.second;
5309 assert(FIST.getNode() && "Unexpected failure");
5312 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5313 FIST, StackSlot, NULL, 0);
5316 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5317 LLVMContext *Context = DAG.getContext();
5318 DebugLoc dl = Op.getDebugLoc();
5319 EVT VT = Op.getValueType();
5322 EltVT = VT.getVectorElementType();
5323 std::vector<Constant*> CV;
5324 if (EltVT == MVT::f64) {
5325 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5329 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5335 Constant *C = ConstantVector::get(CV);
5336 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5337 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5338 PseudoSourceValue::getConstantPool(), 0,
5340 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5343 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5344 LLVMContext *Context = DAG.getContext();
5345 DebugLoc dl = Op.getDebugLoc();
5346 EVT VT = Op.getValueType();
5349 EltVT = VT.getVectorElementType();
5350 std::vector<Constant*> CV;
5351 if (EltVT == MVT::f64) {
5352 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5356 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5362 Constant *C = ConstantVector::get(CV);
5363 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5364 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5365 PseudoSourceValue::getConstantPool(), 0,
5367 if (VT.isVector()) {
5368 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5369 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5370 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5372 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5374 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5378 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5379 LLVMContext *Context = DAG.getContext();
5380 SDValue Op0 = Op.getOperand(0);
5381 SDValue Op1 = Op.getOperand(1);
5382 DebugLoc dl = Op.getDebugLoc();
5383 EVT VT = Op.getValueType();
5384 EVT SrcVT = Op1.getValueType();
5386 // If second operand is smaller, extend it first.
5387 if (SrcVT.bitsLT(VT)) {
5388 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5391 // And if it is bigger, shrink it first.
5392 if (SrcVT.bitsGT(VT)) {
5393 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5397 // At this point the operands and the result should have the same
5398 // type, and that won't be f80 since that is not custom lowered.
5400 // First get the sign bit of second operand.
5401 std::vector<Constant*> CV;
5402 if (SrcVT == MVT::f64) {
5403 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5404 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5406 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5407 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5408 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5409 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5411 Constant *C = ConstantVector::get(CV);
5412 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5413 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5414 PseudoSourceValue::getConstantPool(), 0,
5416 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5418 // Shift sign bit right or left if the two operands have different types.
5419 if (SrcVT.bitsGT(VT)) {
5420 // Op0 is MVT::f32, Op1 is MVT::f64.
5421 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5422 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5423 DAG.getConstant(32, MVT::i32));
5424 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5425 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5426 DAG.getIntPtrConstant(0));
5429 // Clear first operand sign bit.
5431 if (VT == MVT::f64) {
5432 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5433 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5435 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5436 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5437 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5438 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5440 C = ConstantVector::get(CV);
5441 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5442 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5443 PseudoSourceValue::getConstantPool(), 0,
5445 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5447 // Or the value with the sign bit.
5448 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5451 /// Emit nodes that will be selected as "test Op0,Op0", or something
5453 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5454 SelectionDAG &DAG) {
5455 DebugLoc dl = Op.getDebugLoc();
5457 // CF and OF aren't always set the way we want. Determine which
5458 // of these we need.
5459 bool NeedCF = false;
5460 bool NeedOF = false;
5462 case X86::COND_A: case X86::COND_AE:
5463 case X86::COND_B: case X86::COND_BE:
5466 case X86::COND_G: case X86::COND_GE:
5467 case X86::COND_L: case X86::COND_LE:
5468 case X86::COND_O: case X86::COND_NO:
5474 // See if we can use the EFLAGS value from the operand instead of
5475 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5476 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5477 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5478 unsigned Opcode = 0;
5479 unsigned NumOperands = 0;
5480 switch (Op.getNode()->getOpcode()) {
5482 // Due to an isel shortcoming, be conservative if this add is likely to
5483 // be selected as part of a load-modify-store instruction. When the root
5484 // node in a match is a store, isel doesn't know how to remap non-chain
5485 // non-flag uses of other nodes in the match, such as the ADD in this
5486 // case. This leads to the ADD being left around and reselected, with
5487 // the result being two adds in the output.
5488 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5489 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5490 if (UI->getOpcode() == ISD::STORE)
5492 if (ConstantSDNode *C =
5493 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5494 // An add of one will be selected as an INC.
5495 if (C->getAPIntValue() == 1) {
5496 Opcode = X86ISD::INC;
5500 // An add of negative one (subtract of one) will be selected as a DEC.
5501 if (C->getAPIntValue().isAllOnesValue()) {
5502 Opcode = X86ISD::DEC;
5507 // Otherwise use a regular EFLAGS-setting add.
5508 Opcode = X86ISD::ADD;
5512 // If the primary and result isn't used, don't bother using X86ISD::AND,
5513 // because a TEST instruction will be better.
5514 bool NonFlagUse = false;
5515 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5516 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5517 if (UI->getOpcode() != ISD::BRCOND &&
5518 UI->getOpcode() != ISD::SELECT &&
5519 UI->getOpcode() != ISD::SETCC) {
5530 // Due to the ISEL shortcoming noted above, be conservative if this op is
5531 // likely to be selected as part of a load-modify-store instruction.
5532 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5533 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5534 if (UI->getOpcode() == ISD::STORE)
5536 // Otherwise use a regular EFLAGS-setting instruction.
5537 switch (Op.getNode()->getOpcode()) {
5538 case ISD::SUB: Opcode = X86ISD::SUB; break;
5539 case ISD::OR: Opcode = X86ISD::OR; break;
5540 case ISD::XOR: Opcode = X86ISD::XOR; break;
5541 case ISD::AND: Opcode = X86ISD::AND; break;
5542 default: llvm_unreachable("unexpected operator!");
5553 return SDValue(Op.getNode(), 1);
5559 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5560 SmallVector<SDValue, 4> Ops;
5561 for (unsigned i = 0; i != NumOperands; ++i)
5562 Ops.push_back(Op.getOperand(i));
5563 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5564 DAG.ReplaceAllUsesWith(Op, New);
5565 return SDValue(New.getNode(), 1);
5569 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5570 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5571 DAG.getConstant(0, Op.getValueType()));
5574 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5576 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5577 SelectionDAG &DAG) {
5578 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5579 if (C->getAPIntValue() == 0)
5580 return EmitTest(Op0, X86CC, DAG);
5582 DebugLoc dl = Op0.getDebugLoc();
5583 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5586 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5587 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5588 SDValue Op0 = Op.getOperand(0);
5589 SDValue Op1 = Op.getOperand(1);
5590 DebugLoc dl = Op.getDebugLoc();
5591 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5593 // Lower (X & (1 << N)) == 0 to BT(X, N).
5594 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5595 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5596 if (Op0.getOpcode() == ISD::AND &&
5598 Op1.getOpcode() == ISD::Constant &&
5599 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5600 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5602 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5603 if (ConstantSDNode *Op010C =
5604 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5605 if (Op010C->getZExtValue() == 1) {
5606 LHS = Op0.getOperand(0);
5607 RHS = Op0.getOperand(1).getOperand(1);
5609 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5610 if (ConstantSDNode *Op000C =
5611 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5612 if (Op000C->getZExtValue() == 1) {
5613 LHS = Op0.getOperand(1);
5614 RHS = Op0.getOperand(0).getOperand(1);
5616 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5617 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5618 SDValue AndLHS = Op0.getOperand(0);
5619 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5620 LHS = AndLHS.getOperand(0);
5621 RHS = AndLHS.getOperand(1);
5625 if (LHS.getNode()) {
5626 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5627 // instruction. Since the shift amount is in-range-or-undefined, we know
5628 // that doing a bittest on the i16 value is ok. We extend to i32 because
5629 // the encoding for the i16 version is larger than the i32 version.
5630 if (LHS.getValueType() == MVT::i8)
5631 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5633 // If the operand types disagree, extend the shift amount to match. Since
5634 // BT ignores high bits (like shifts) we can use anyextend.
5635 if (LHS.getValueType() != RHS.getValueType())
5636 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5638 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5639 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5640 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5641 DAG.getConstant(Cond, MVT::i8), BT);
5645 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5646 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5647 if (X86CC == X86::COND_INVALID)
5650 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5651 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5652 DAG.getConstant(X86CC, MVT::i8), Cond);
5655 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5657 SDValue Op0 = Op.getOperand(0);
5658 SDValue Op1 = Op.getOperand(1);
5659 SDValue CC = Op.getOperand(2);
5660 EVT VT = Op.getValueType();
5661 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5662 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5663 DebugLoc dl = Op.getDebugLoc();
5667 EVT VT0 = Op0.getValueType();
5668 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5669 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5672 switch (SetCCOpcode) {
5675 case ISD::SETEQ: SSECC = 0; break;
5677 case ISD::SETGT: Swap = true; // Fallthrough
5679 case ISD::SETOLT: SSECC = 1; break;
5681 case ISD::SETGE: Swap = true; // Fallthrough
5683 case ISD::SETOLE: SSECC = 2; break;
5684 case ISD::SETUO: SSECC = 3; break;
5686 case ISD::SETNE: SSECC = 4; break;
5687 case ISD::SETULE: Swap = true;
5688 case ISD::SETUGE: SSECC = 5; break;
5689 case ISD::SETULT: Swap = true;
5690 case ISD::SETUGT: SSECC = 6; break;
5691 case ISD::SETO: SSECC = 7; break;
5694 std::swap(Op0, Op1);
5696 // In the two special cases we can't handle, emit two comparisons.
5698 if (SetCCOpcode == ISD::SETUEQ) {
5700 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5701 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5702 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5704 else if (SetCCOpcode == ISD::SETONE) {
5706 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5707 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5708 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5710 llvm_unreachable("Illegal FP comparison");
5712 // Handle all other FP comparisons here.
5713 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5716 // We are handling one of the integer comparisons here. Since SSE only has
5717 // GT and EQ comparisons for integer, swapping operands and multiple
5718 // operations may be required for some comparisons.
5719 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5720 bool Swap = false, Invert = false, FlipSigns = false;
5722 switch (VT.getSimpleVT().SimpleTy) {
5725 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5727 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5729 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5730 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5733 switch (SetCCOpcode) {
5735 case ISD::SETNE: Invert = true;
5736 case ISD::SETEQ: Opc = EQOpc; break;
5737 case ISD::SETLT: Swap = true;
5738 case ISD::SETGT: Opc = GTOpc; break;
5739 case ISD::SETGE: Swap = true;
5740 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5741 case ISD::SETULT: Swap = true;
5742 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5743 case ISD::SETUGE: Swap = true;
5744 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5747 std::swap(Op0, Op1);
5749 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5750 // bits of the inputs before performing those operations.
5752 EVT EltVT = VT.getVectorElementType();
5753 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5755 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5756 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5758 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5759 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5762 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5764 // If the logical-not of the result is required, perform that now.
5766 Result = DAG.getNOT(dl, Result, VT);
5771 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5772 static bool isX86LogicalCmp(SDValue Op) {
5773 unsigned Opc = Op.getNode()->getOpcode();
5774 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5776 if (Op.getResNo() == 1 &&
5777 (Opc == X86ISD::ADD ||
5778 Opc == X86ISD::SUB ||
5779 Opc == X86ISD::SMUL ||
5780 Opc == X86ISD::UMUL ||
5781 Opc == X86ISD::INC ||
5782 Opc == X86ISD::DEC ||
5783 Opc == X86ISD::OR ||
5784 Opc == X86ISD::XOR ||
5785 Opc == X86ISD::AND))
5791 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5792 bool addTest = true;
5793 SDValue Cond = Op.getOperand(0);
5794 DebugLoc dl = Op.getDebugLoc();
5797 if (Cond.getOpcode() == ISD::SETCC) {
5798 SDValue NewCond = LowerSETCC(Cond, DAG);
5799 if (NewCond.getNode())
5803 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5804 // setting operand in place of the X86ISD::SETCC.
5805 if (Cond.getOpcode() == X86ISD::SETCC) {
5806 CC = Cond.getOperand(0);
5808 SDValue Cmp = Cond.getOperand(1);
5809 unsigned Opc = Cmp.getOpcode();
5810 EVT VT = Op.getValueType();
5812 bool IllegalFPCMov = false;
5813 if (VT.isFloatingPoint() && !VT.isVector() &&
5814 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5815 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5817 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5818 Opc == X86ISD::BT) { // FIXME
5825 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5826 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5829 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5830 SmallVector<SDValue, 4> Ops;
5831 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5832 // condition is true.
5833 Ops.push_back(Op.getOperand(2));
5834 Ops.push_back(Op.getOperand(1));
5836 Ops.push_back(Cond);
5837 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5840 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5841 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5842 // from the AND / OR.
5843 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5844 Opc = Op.getOpcode();
5845 if (Opc != ISD::OR && Opc != ISD::AND)
5847 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5848 Op.getOperand(0).hasOneUse() &&
5849 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5850 Op.getOperand(1).hasOneUse());
5853 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5854 // 1 and that the SETCC node has a single use.
5855 static bool isXor1OfSetCC(SDValue Op) {
5856 if (Op.getOpcode() != ISD::XOR)
5858 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5859 if (N1C && N1C->getAPIntValue() == 1) {
5860 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5861 Op.getOperand(0).hasOneUse();
5866 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5867 bool addTest = true;
5868 SDValue Chain = Op.getOperand(0);
5869 SDValue Cond = Op.getOperand(1);
5870 SDValue Dest = Op.getOperand(2);
5871 DebugLoc dl = Op.getDebugLoc();
5874 if (Cond.getOpcode() == ISD::SETCC) {
5875 SDValue NewCond = LowerSETCC(Cond, DAG);
5876 if (NewCond.getNode())
5880 // FIXME: LowerXALUO doesn't handle these!!
5881 else if (Cond.getOpcode() == X86ISD::ADD ||
5882 Cond.getOpcode() == X86ISD::SUB ||
5883 Cond.getOpcode() == X86ISD::SMUL ||
5884 Cond.getOpcode() == X86ISD::UMUL)
5885 Cond = LowerXALUO(Cond, DAG);
5888 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5889 // setting operand in place of the X86ISD::SETCC.
5890 if (Cond.getOpcode() == X86ISD::SETCC) {
5891 CC = Cond.getOperand(0);
5893 SDValue Cmp = Cond.getOperand(1);
5894 unsigned Opc = Cmp.getOpcode();
5895 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5896 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5900 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5904 // These can only come from an arithmetic instruction with overflow,
5905 // e.g. SADDO, UADDO.
5906 Cond = Cond.getNode()->getOperand(1);
5913 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5914 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5915 if (CondOpc == ISD::OR) {
5916 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5917 // two branches instead of an explicit OR instruction with a
5919 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5920 isX86LogicalCmp(Cmp)) {
5921 CC = Cond.getOperand(0).getOperand(0);
5922 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5923 Chain, Dest, CC, Cmp);
5924 CC = Cond.getOperand(1).getOperand(0);
5928 } else { // ISD::AND
5929 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5930 // two branches instead of an explicit AND instruction with a
5931 // separate test. However, we only do this if this block doesn't
5932 // have a fall-through edge, because this requires an explicit
5933 // jmp when the condition is false.
5934 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5935 isX86LogicalCmp(Cmp) &&
5936 Op.getNode()->hasOneUse()) {
5937 X86::CondCode CCode =
5938 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5939 CCode = X86::GetOppositeBranchCondition(CCode);
5940 CC = DAG.getConstant(CCode, MVT::i8);
5941 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5942 // Look for an unconditional branch following this conditional branch.
5943 // We need this because we need to reverse the successors in order
5944 // to implement FCMP_OEQ.
5945 if (User.getOpcode() == ISD::BR) {
5946 SDValue FalseBB = User.getOperand(1);
5948 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5949 assert(NewBR == User);
5952 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5953 Chain, Dest, CC, Cmp);
5954 X86::CondCode CCode =
5955 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5956 CCode = X86::GetOppositeBranchCondition(CCode);
5957 CC = DAG.getConstant(CCode, MVT::i8);
5963 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5964 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5965 // It should be transformed during dag combiner except when the condition
5966 // is set by a arithmetics with overflow node.
5967 X86::CondCode CCode =
5968 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5969 CCode = X86::GetOppositeBranchCondition(CCode);
5970 CC = DAG.getConstant(CCode, MVT::i8);
5971 Cond = Cond.getOperand(0).getOperand(1);
5977 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5978 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5980 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5981 Chain, Dest, CC, Cond);
5985 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5986 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5987 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5988 // that the guard pages used by the OS virtual memory manager are allocated in
5989 // correct sequence.
5991 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5992 SelectionDAG &DAG) {
5993 assert(Subtarget->isTargetCygMing() &&
5994 "This should be used only on Cygwin/Mingw targets");
5995 DebugLoc dl = Op.getDebugLoc();
5998 SDValue Chain = Op.getOperand(0);
5999 SDValue Size = Op.getOperand(1);
6000 // FIXME: Ensure alignment here
6004 EVT IntPtr = getPointerTy();
6005 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6007 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6009 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6010 Flag = Chain.getValue(1);
6012 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6013 SDValue Ops[] = { Chain,
6014 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6015 DAG.getRegister(X86::EAX, IntPtr),
6016 DAG.getRegister(X86StackPtr, SPTy),
6018 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6019 Flag = Chain.getValue(1);
6021 Chain = DAG.getCALLSEQ_END(Chain,
6022 DAG.getIntPtrConstant(0, true),
6023 DAG.getIntPtrConstant(0, true),
6026 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6028 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6029 return DAG.getMergeValues(Ops1, 2, dl);
6033 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6035 SDValue Dst, SDValue Src,
6036 SDValue Size, unsigned Align,
6038 uint64_t DstSVOff) {
6039 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6041 // If not DWORD aligned or size is more than the threshold, call the library.
6042 // The libc version is likely to be faster for these cases. It can use the
6043 // address value and run time information about the CPU.
6044 if ((Align & 3) != 0 ||
6046 ConstantSize->getZExtValue() >
6047 getSubtarget()->getMaxInlineSizeThreshold()) {
6048 SDValue InFlag(0, 0);
6050 // Check to see if there is a specialized entry-point for memory zeroing.
6051 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6053 if (const char *bzeroEntry = V &&
6054 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6055 EVT IntPtr = getPointerTy();
6056 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6057 TargetLowering::ArgListTy Args;
6058 TargetLowering::ArgListEntry Entry;
6060 Entry.Ty = IntPtrTy;
6061 Args.push_back(Entry);
6063 Args.push_back(Entry);
6064 std::pair<SDValue,SDValue> CallResult =
6065 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6066 false, false, false, false,
6067 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6068 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6069 return CallResult.second;
6072 // Otherwise have the target-independent code call memset.
6076 uint64_t SizeVal = ConstantSize->getZExtValue();
6077 SDValue InFlag(0, 0);
6080 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6081 unsigned BytesLeft = 0;
6082 bool TwoRepStos = false;
6085 uint64_t Val = ValC->getZExtValue() & 255;
6087 // If the value is a constant, then we can potentially use larger sets.
6088 switch (Align & 3) {
6089 case 2: // WORD aligned
6092 Val = (Val << 8) | Val;
6094 case 0: // DWORD aligned
6097 Val = (Val << 8) | Val;
6098 Val = (Val << 16) | Val;
6099 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6102 Val = (Val << 32) | Val;
6105 default: // Byte aligned
6108 Count = DAG.getIntPtrConstant(SizeVal);
6112 if (AVT.bitsGT(MVT::i8)) {
6113 unsigned UBytes = AVT.getSizeInBits() / 8;
6114 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6115 BytesLeft = SizeVal % UBytes;
6118 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6120 InFlag = Chain.getValue(1);
6123 Count = DAG.getIntPtrConstant(SizeVal);
6124 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6125 InFlag = Chain.getValue(1);
6128 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6131 InFlag = Chain.getValue(1);
6132 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6135 InFlag = Chain.getValue(1);
6137 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6138 SmallVector<SDValue, 8> Ops;
6139 Ops.push_back(Chain);
6140 Ops.push_back(DAG.getValueType(AVT));
6141 Ops.push_back(InFlag);
6142 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6145 InFlag = Chain.getValue(1);
6147 EVT CVT = Count.getValueType();
6148 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6149 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6150 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6153 InFlag = Chain.getValue(1);
6154 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6156 Ops.push_back(Chain);
6157 Ops.push_back(DAG.getValueType(MVT::i8));
6158 Ops.push_back(InFlag);
6159 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6160 } else if (BytesLeft) {
6161 // Handle the last 1 - 7 bytes.
6162 unsigned Offset = SizeVal - BytesLeft;
6163 EVT AddrVT = Dst.getValueType();
6164 EVT SizeVT = Size.getValueType();
6166 Chain = DAG.getMemset(Chain, dl,
6167 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6168 DAG.getConstant(Offset, AddrVT)),
6170 DAG.getConstant(BytesLeft, SizeVT),
6171 Align, DstSV, DstSVOff + Offset);
6174 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6179 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6180 SDValue Chain, SDValue Dst, SDValue Src,
6181 SDValue Size, unsigned Align,
6183 const Value *DstSV, uint64_t DstSVOff,
6184 const Value *SrcSV, uint64_t SrcSVOff) {
6185 // This requires the copy size to be a constant, preferrably
6186 // within a subtarget-specific limit.
6187 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6190 uint64_t SizeVal = ConstantSize->getZExtValue();
6191 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6194 /// If not DWORD aligned, call the library.
6195 if ((Align & 3) != 0)
6200 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6203 unsigned UBytes = AVT.getSizeInBits() / 8;
6204 unsigned CountVal = SizeVal / UBytes;
6205 SDValue Count = DAG.getIntPtrConstant(CountVal);
6206 unsigned BytesLeft = SizeVal % UBytes;
6208 SDValue InFlag(0, 0);
6209 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6212 InFlag = Chain.getValue(1);
6213 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6216 InFlag = Chain.getValue(1);
6217 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6220 InFlag = Chain.getValue(1);
6222 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6223 SmallVector<SDValue, 8> Ops;
6224 Ops.push_back(Chain);
6225 Ops.push_back(DAG.getValueType(AVT));
6226 Ops.push_back(InFlag);
6227 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6229 SmallVector<SDValue, 4> Results;
6230 Results.push_back(RepMovs);
6232 // Handle the last 1 - 7 bytes.
6233 unsigned Offset = SizeVal - BytesLeft;
6234 EVT DstVT = Dst.getValueType();
6235 EVT SrcVT = Src.getValueType();
6236 EVT SizeVT = Size.getValueType();
6237 Results.push_back(DAG.getMemcpy(Chain, dl,
6238 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6239 DAG.getConstant(Offset, DstVT)),
6240 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6241 DAG.getConstant(Offset, SrcVT)),
6242 DAG.getConstant(BytesLeft, SizeVT),
6243 Align, AlwaysInline,
6244 DstSV, DstSVOff + Offset,
6245 SrcSV, SrcSVOff + Offset));
6248 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6249 &Results[0], Results.size());
6252 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6253 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6254 DebugLoc dl = Op.getDebugLoc();
6256 if (!Subtarget->is64Bit()) {
6257 // vastart just stores the address of the VarArgsFrameIndex slot into the
6258 // memory location argument.
6259 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6260 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6264 // gp_offset (0 - 6 * 8)
6265 // fp_offset (48 - 48 + 8 * 16)
6266 // overflow_arg_area (point to parameters coming in memory).
6268 SmallVector<SDValue, 8> MemOps;
6269 SDValue FIN = Op.getOperand(1);
6271 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6272 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6274 MemOps.push_back(Store);
6277 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6278 FIN, DAG.getIntPtrConstant(4));
6279 Store = DAG.getStore(Op.getOperand(0), dl,
6280 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6282 MemOps.push_back(Store);
6284 // Store ptr to overflow_arg_area
6285 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6286 FIN, DAG.getIntPtrConstant(4));
6287 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6288 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6289 MemOps.push_back(Store);
6291 // Store ptr to reg_save_area.
6292 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6293 FIN, DAG.getIntPtrConstant(8));
6294 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6295 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6296 MemOps.push_back(Store);
6297 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6298 &MemOps[0], MemOps.size());
6301 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6302 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6303 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6304 SDValue Chain = Op.getOperand(0);
6305 SDValue SrcPtr = Op.getOperand(1);
6306 SDValue SrcSV = Op.getOperand(2);
6308 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6312 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6313 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6314 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6315 SDValue Chain = Op.getOperand(0);
6316 SDValue DstPtr = Op.getOperand(1);
6317 SDValue SrcPtr = Op.getOperand(2);
6318 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6319 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6320 DebugLoc dl = Op.getDebugLoc();
6322 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6323 DAG.getIntPtrConstant(24), 8, false,
6324 DstSV, 0, SrcSV, 0);
6328 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6329 DebugLoc dl = Op.getDebugLoc();
6330 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6332 default: return SDValue(); // Don't custom lower most intrinsics.
6333 // Comparison intrinsics.
6334 case Intrinsic::x86_sse_comieq_ss:
6335 case Intrinsic::x86_sse_comilt_ss:
6336 case Intrinsic::x86_sse_comile_ss:
6337 case Intrinsic::x86_sse_comigt_ss:
6338 case Intrinsic::x86_sse_comige_ss:
6339 case Intrinsic::x86_sse_comineq_ss:
6340 case Intrinsic::x86_sse_ucomieq_ss:
6341 case Intrinsic::x86_sse_ucomilt_ss:
6342 case Intrinsic::x86_sse_ucomile_ss:
6343 case Intrinsic::x86_sse_ucomigt_ss:
6344 case Intrinsic::x86_sse_ucomige_ss:
6345 case Intrinsic::x86_sse_ucomineq_ss:
6346 case Intrinsic::x86_sse2_comieq_sd:
6347 case Intrinsic::x86_sse2_comilt_sd:
6348 case Intrinsic::x86_sse2_comile_sd:
6349 case Intrinsic::x86_sse2_comigt_sd:
6350 case Intrinsic::x86_sse2_comige_sd:
6351 case Intrinsic::x86_sse2_comineq_sd:
6352 case Intrinsic::x86_sse2_ucomieq_sd:
6353 case Intrinsic::x86_sse2_ucomilt_sd:
6354 case Intrinsic::x86_sse2_ucomile_sd:
6355 case Intrinsic::x86_sse2_ucomigt_sd:
6356 case Intrinsic::x86_sse2_ucomige_sd:
6357 case Intrinsic::x86_sse2_ucomineq_sd: {
6359 ISD::CondCode CC = ISD::SETCC_INVALID;
6362 case Intrinsic::x86_sse_comieq_ss:
6363 case Intrinsic::x86_sse2_comieq_sd:
6367 case Intrinsic::x86_sse_comilt_ss:
6368 case Intrinsic::x86_sse2_comilt_sd:
6372 case Intrinsic::x86_sse_comile_ss:
6373 case Intrinsic::x86_sse2_comile_sd:
6377 case Intrinsic::x86_sse_comigt_ss:
6378 case Intrinsic::x86_sse2_comigt_sd:
6382 case Intrinsic::x86_sse_comige_ss:
6383 case Intrinsic::x86_sse2_comige_sd:
6387 case Intrinsic::x86_sse_comineq_ss:
6388 case Intrinsic::x86_sse2_comineq_sd:
6392 case Intrinsic::x86_sse_ucomieq_ss:
6393 case Intrinsic::x86_sse2_ucomieq_sd:
6394 Opc = X86ISD::UCOMI;
6397 case Intrinsic::x86_sse_ucomilt_ss:
6398 case Intrinsic::x86_sse2_ucomilt_sd:
6399 Opc = X86ISD::UCOMI;
6402 case Intrinsic::x86_sse_ucomile_ss:
6403 case Intrinsic::x86_sse2_ucomile_sd:
6404 Opc = X86ISD::UCOMI;
6407 case Intrinsic::x86_sse_ucomigt_ss:
6408 case Intrinsic::x86_sse2_ucomigt_sd:
6409 Opc = X86ISD::UCOMI;
6412 case Intrinsic::x86_sse_ucomige_ss:
6413 case Intrinsic::x86_sse2_ucomige_sd:
6414 Opc = X86ISD::UCOMI;
6417 case Intrinsic::x86_sse_ucomineq_ss:
6418 case Intrinsic::x86_sse2_ucomineq_sd:
6419 Opc = X86ISD::UCOMI;
6424 SDValue LHS = Op.getOperand(1);
6425 SDValue RHS = Op.getOperand(2);
6426 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6427 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6428 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6429 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6430 DAG.getConstant(X86CC, MVT::i8), Cond);
6431 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6433 // ptest intrinsics. The intrinsic these come from are designed to return
6434 // an integer value, not just an instruction so lower it to the ptest
6435 // pattern and a setcc for the result.
6436 case Intrinsic::x86_sse41_ptestz:
6437 case Intrinsic::x86_sse41_ptestc:
6438 case Intrinsic::x86_sse41_ptestnzc:{
6441 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6442 case Intrinsic::x86_sse41_ptestz:
6444 X86CC = X86::COND_E;
6446 case Intrinsic::x86_sse41_ptestc:
6448 X86CC = X86::COND_B;
6450 case Intrinsic::x86_sse41_ptestnzc:
6452 X86CC = X86::COND_A;
6456 SDValue LHS = Op.getOperand(1);
6457 SDValue RHS = Op.getOperand(2);
6458 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6459 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6460 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6461 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6464 // Fix vector shift instructions where the last operand is a non-immediate
6466 case Intrinsic::x86_sse2_pslli_w:
6467 case Intrinsic::x86_sse2_pslli_d:
6468 case Intrinsic::x86_sse2_pslli_q:
6469 case Intrinsic::x86_sse2_psrli_w:
6470 case Intrinsic::x86_sse2_psrli_d:
6471 case Intrinsic::x86_sse2_psrli_q:
6472 case Intrinsic::x86_sse2_psrai_w:
6473 case Intrinsic::x86_sse2_psrai_d:
6474 case Intrinsic::x86_mmx_pslli_w:
6475 case Intrinsic::x86_mmx_pslli_d:
6476 case Intrinsic::x86_mmx_pslli_q:
6477 case Intrinsic::x86_mmx_psrli_w:
6478 case Intrinsic::x86_mmx_psrli_d:
6479 case Intrinsic::x86_mmx_psrli_q:
6480 case Intrinsic::x86_mmx_psrai_w:
6481 case Intrinsic::x86_mmx_psrai_d: {
6482 SDValue ShAmt = Op.getOperand(2);
6483 if (isa<ConstantSDNode>(ShAmt))
6486 unsigned NewIntNo = 0;
6487 EVT ShAmtVT = MVT::v4i32;
6489 case Intrinsic::x86_sse2_pslli_w:
6490 NewIntNo = Intrinsic::x86_sse2_psll_w;
6492 case Intrinsic::x86_sse2_pslli_d:
6493 NewIntNo = Intrinsic::x86_sse2_psll_d;
6495 case Intrinsic::x86_sse2_pslli_q:
6496 NewIntNo = Intrinsic::x86_sse2_psll_q;
6498 case Intrinsic::x86_sse2_psrli_w:
6499 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6501 case Intrinsic::x86_sse2_psrli_d:
6502 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6504 case Intrinsic::x86_sse2_psrli_q:
6505 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6507 case Intrinsic::x86_sse2_psrai_w:
6508 NewIntNo = Intrinsic::x86_sse2_psra_w;
6510 case Intrinsic::x86_sse2_psrai_d:
6511 NewIntNo = Intrinsic::x86_sse2_psra_d;
6514 ShAmtVT = MVT::v2i32;
6516 case Intrinsic::x86_mmx_pslli_w:
6517 NewIntNo = Intrinsic::x86_mmx_psll_w;
6519 case Intrinsic::x86_mmx_pslli_d:
6520 NewIntNo = Intrinsic::x86_mmx_psll_d;
6522 case Intrinsic::x86_mmx_pslli_q:
6523 NewIntNo = Intrinsic::x86_mmx_psll_q;
6525 case Intrinsic::x86_mmx_psrli_w:
6526 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6528 case Intrinsic::x86_mmx_psrli_d:
6529 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6531 case Intrinsic::x86_mmx_psrli_q:
6532 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6534 case Intrinsic::x86_mmx_psrai_w:
6535 NewIntNo = Intrinsic::x86_mmx_psra_w;
6537 case Intrinsic::x86_mmx_psrai_d:
6538 NewIntNo = Intrinsic::x86_mmx_psra_d;
6540 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6546 // The vector shift intrinsics with scalars uses 32b shift amounts but
6547 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6551 ShOps[1] = DAG.getConstant(0, MVT::i32);
6552 if (ShAmtVT == MVT::v4i32) {
6553 ShOps[2] = DAG.getUNDEF(MVT::i32);
6554 ShOps[3] = DAG.getUNDEF(MVT::i32);
6555 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6557 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6560 EVT VT = Op.getValueType();
6561 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6562 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6563 DAG.getConstant(NewIntNo, MVT::i32),
6564 Op.getOperand(1), ShAmt);
6569 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6570 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6571 DebugLoc dl = Op.getDebugLoc();
6574 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6576 DAG.getConstant(TD->getPointerSize(),
6577 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6578 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6579 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6584 // Just load the return address.
6585 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6586 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6587 RetAddrFI, NULL, 0);
6590 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6591 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6592 MFI->setFrameAddressIsTaken(true);
6593 EVT VT = Op.getValueType();
6594 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6595 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6596 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6597 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6599 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6603 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6604 SelectionDAG &DAG) {
6605 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6608 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6610 MachineFunction &MF = DAG.getMachineFunction();
6611 SDValue Chain = Op.getOperand(0);
6612 SDValue Offset = Op.getOperand(1);
6613 SDValue Handler = Op.getOperand(2);
6614 DebugLoc dl = Op.getDebugLoc();
6616 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6618 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6620 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6621 DAG.getIntPtrConstant(-TD->getPointerSize()));
6622 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6623 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6624 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6625 MF.getRegInfo().addLiveOut(StoreAddrReg);
6627 return DAG.getNode(X86ISD::EH_RETURN, dl,
6629 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6632 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6633 SelectionDAG &DAG) {
6634 SDValue Root = Op.getOperand(0);
6635 SDValue Trmp = Op.getOperand(1); // trampoline
6636 SDValue FPtr = Op.getOperand(2); // nested function
6637 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6638 DebugLoc dl = Op.getDebugLoc();
6640 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6642 const X86InstrInfo *TII =
6643 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6645 if (Subtarget->is64Bit()) {
6646 SDValue OutChains[6];
6648 // Large code-model.
6650 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6651 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6653 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6654 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6656 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6658 // Load the pointer to the nested function into R11.
6659 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6660 SDValue Addr = Trmp;
6661 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6664 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6665 DAG.getConstant(2, MVT::i64));
6666 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6668 // Load the 'nest' parameter value into R10.
6669 // R10 is specified in X86CallingConv.td
6670 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6671 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6672 DAG.getConstant(10, MVT::i64));
6673 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6674 Addr, TrmpAddr, 10);
6676 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6677 DAG.getConstant(12, MVT::i64));
6678 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6680 // Jump to the nested function.
6681 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6682 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6683 DAG.getConstant(20, MVT::i64));
6684 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6685 Addr, TrmpAddr, 20);
6687 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6688 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6689 DAG.getConstant(22, MVT::i64));
6690 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6694 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6695 return DAG.getMergeValues(Ops, 2, dl);
6697 const Function *Func =
6698 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6699 CallingConv::ID CC = Func->getCallingConv();
6704 llvm_unreachable("Unsupported calling convention");
6705 case CallingConv::C:
6706 case CallingConv::X86_StdCall: {
6707 // Pass 'nest' parameter in ECX.
6708 // Must be kept in sync with X86CallingConv.td
6711 // Check that ECX wasn't needed by an 'inreg' parameter.
6712 const FunctionType *FTy = Func->getFunctionType();
6713 const AttrListPtr &Attrs = Func->getAttributes();
6715 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6716 unsigned InRegCount = 0;
6719 for (FunctionType::param_iterator I = FTy->param_begin(),
6720 E = FTy->param_end(); I != E; ++I, ++Idx)
6721 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6722 // FIXME: should only count parameters that are lowered to integers.
6723 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6725 if (InRegCount > 2) {
6726 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6731 case CallingConv::X86_FastCall:
6732 case CallingConv::Fast:
6733 // Pass 'nest' parameter in EAX.
6734 // Must be kept in sync with X86CallingConv.td
6739 SDValue OutChains[4];
6742 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6743 DAG.getConstant(10, MVT::i32));
6744 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6746 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6747 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6748 OutChains[0] = DAG.getStore(Root, dl,
6749 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6752 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6753 DAG.getConstant(1, MVT::i32));
6754 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6756 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6757 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6758 DAG.getConstant(5, MVT::i32));
6759 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6760 TrmpAddr, 5, false, 1);
6762 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6763 DAG.getConstant(6, MVT::i32));
6764 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6767 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6768 return DAG.getMergeValues(Ops, 2, dl);
6772 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6774 The rounding mode is in bits 11:10 of FPSR, and has the following
6781 FLT_ROUNDS, on the other hand, expects the following:
6788 To perform the conversion, we do:
6789 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6792 MachineFunction &MF = DAG.getMachineFunction();
6793 const TargetMachine &TM = MF.getTarget();
6794 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6795 unsigned StackAlignment = TFI.getStackAlignment();
6796 EVT VT = Op.getValueType();
6797 DebugLoc dl = Op.getDebugLoc();
6799 // Save FP Control Word to stack slot
6800 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
6801 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6803 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6804 DAG.getEntryNode(), StackSlot);
6806 // Load FP Control Word from stack slot
6807 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6809 // Transform as necessary
6811 DAG.getNode(ISD::SRL, dl, MVT::i16,
6812 DAG.getNode(ISD::AND, dl, MVT::i16,
6813 CWD, DAG.getConstant(0x800, MVT::i16)),
6814 DAG.getConstant(11, MVT::i8));
6816 DAG.getNode(ISD::SRL, dl, MVT::i16,
6817 DAG.getNode(ISD::AND, dl, MVT::i16,
6818 CWD, DAG.getConstant(0x400, MVT::i16)),
6819 DAG.getConstant(9, MVT::i8));
6822 DAG.getNode(ISD::AND, dl, MVT::i16,
6823 DAG.getNode(ISD::ADD, dl, MVT::i16,
6824 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6825 DAG.getConstant(1, MVT::i16)),
6826 DAG.getConstant(3, MVT::i16));
6829 return DAG.getNode((VT.getSizeInBits() < 16 ?
6830 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6833 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6834 EVT VT = Op.getValueType();
6836 unsigned NumBits = VT.getSizeInBits();
6837 DebugLoc dl = Op.getDebugLoc();
6839 Op = Op.getOperand(0);
6840 if (VT == MVT::i8) {
6841 // Zero extend to i32 since there is not an i8 bsr.
6843 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6846 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6847 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6848 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6850 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6851 SmallVector<SDValue, 4> Ops;
6853 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6854 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6855 Ops.push_back(Op.getValue(1));
6856 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6858 // Finally xor with NumBits-1.
6859 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6862 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6866 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6867 EVT VT = Op.getValueType();
6869 unsigned NumBits = VT.getSizeInBits();
6870 DebugLoc dl = Op.getDebugLoc();
6872 Op = Op.getOperand(0);
6873 if (VT == MVT::i8) {
6875 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6878 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6879 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6880 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6882 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6883 SmallVector<SDValue, 4> Ops;
6885 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6886 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6887 Ops.push_back(Op.getValue(1));
6888 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6891 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6895 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6896 EVT VT = Op.getValueType();
6897 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6898 DebugLoc dl = Op.getDebugLoc();
6900 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6901 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6902 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6903 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6904 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6906 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6907 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6908 // return AloBlo + AloBhi + AhiBlo;
6910 SDValue A = Op.getOperand(0);
6911 SDValue B = Op.getOperand(1);
6913 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6914 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6915 A, DAG.getConstant(32, MVT::i32));
6916 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6917 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6918 B, DAG.getConstant(32, MVT::i32));
6919 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6920 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6922 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6923 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6925 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6926 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6928 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6929 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6930 AloBhi, DAG.getConstant(32, MVT::i32));
6931 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6932 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6933 AhiBlo, DAG.getConstant(32, MVT::i32));
6934 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6935 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6940 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6941 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6942 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6943 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6944 // has only one use.
6945 SDNode *N = Op.getNode();
6946 SDValue LHS = N->getOperand(0);
6947 SDValue RHS = N->getOperand(1);
6948 unsigned BaseOp = 0;
6950 DebugLoc dl = Op.getDebugLoc();
6952 switch (Op.getOpcode()) {
6953 default: llvm_unreachable("Unknown ovf instruction!");
6955 // A subtract of one will be selected as a INC. Note that INC doesn't
6956 // set CF, so we can't do this for UADDO.
6957 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6958 if (C->getAPIntValue() == 1) {
6959 BaseOp = X86ISD::INC;
6963 BaseOp = X86ISD::ADD;
6967 BaseOp = X86ISD::ADD;
6971 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6972 // set CF, so we can't do this for USUBO.
6973 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6974 if (C->getAPIntValue() == 1) {
6975 BaseOp = X86ISD::DEC;
6979 BaseOp = X86ISD::SUB;
6983 BaseOp = X86ISD::SUB;
6987 BaseOp = X86ISD::SMUL;
6991 BaseOp = X86ISD::UMUL;
6996 // Also sets EFLAGS.
6997 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6998 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7001 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7002 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7004 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7008 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7009 EVT T = Op.getValueType();
7010 DebugLoc dl = Op.getDebugLoc();
7013 switch(T.getSimpleVT().SimpleTy) {
7015 assert(false && "Invalid value type!");
7016 case MVT::i8: Reg = X86::AL; size = 1; break;
7017 case MVT::i16: Reg = X86::AX; size = 2; break;
7018 case MVT::i32: Reg = X86::EAX; size = 4; break;
7020 assert(Subtarget->is64Bit() && "Node not type legal!");
7021 Reg = X86::RAX; size = 8;
7024 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7025 Op.getOperand(2), SDValue());
7026 SDValue Ops[] = { cpIn.getValue(0),
7029 DAG.getTargetConstant(size, MVT::i8),
7031 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7032 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7034 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7038 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7039 SelectionDAG &DAG) {
7040 assert(Subtarget->is64Bit() && "Result not type legalized?");
7041 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7042 SDValue TheChain = Op.getOperand(0);
7043 DebugLoc dl = Op.getDebugLoc();
7044 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7045 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7046 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7048 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7049 DAG.getConstant(32, MVT::i8));
7051 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7054 return DAG.getMergeValues(Ops, 2, dl);
7057 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7058 SDNode *Node = Op.getNode();
7059 DebugLoc dl = Node->getDebugLoc();
7060 EVT T = Node->getValueType(0);
7061 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7062 DAG.getConstant(0, T), Node->getOperand(2));
7063 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7064 cast<AtomicSDNode>(Node)->getMemoryVT(),
7065 Node->getOperand(0),
7066 Node->getOperand(1), negOp,
7067 cast<AtomicSDNode>(Node)->getSrcValue(),
7068 cast<AtomicSDNode>(Node)->getAlignment());
7071 /// LowerOperation - Provide custom lowering hooks for some operations.
7073 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7074 switch (Op.getOpcode()) {
7075 default: llvm_unreachable("Should not custom lower this!");
7076 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7077 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7078 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7079 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7080 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7081 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7082 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7083 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7084 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7085 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7086 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7087 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7088 case ISD::SHL_PARTS:
7089 case ISD::SRA_PARTS:
7090 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7091 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7092 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7093 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7094 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7095 case ISD::FABS: return LowerFABS(Op, DAG);
7096 case ISD::FNEG: return LowerFNEG(Op, DAG);
7097 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7098 case ISD::SETCC: return LowerSETCC(Op, DAG);
7099 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7100 case ISD::SELECT: return LowerSELECT(Op, DAG);
7101 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7102 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7103 case ISD::VASTART: return LowerVASTART(Op, DAG);
7104 case ISD::VAARG: return LowerVAARG(Op, DAG);
7105 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7106 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7107 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7108 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7109 case ISD::FRAME_TO_ARGS_OFFSET:
7110 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7111 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7112 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7113 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7114 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7115 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7116 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7117 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7123 case ISD::UMULO: return LowerXALUO(Op, DAG);
7124 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7128 void X86TargetLowering::
7129 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7130 SelectionDAG &DAG, unsigned NewOp) {
7131 EVT T = Node->getValueType(0);
7132 DebugLoc dl = Node->getDebugLoc();
7133 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7135 SDValue Chain = Node->getOperand(0);
7136 SDValue In1 = Node->getOperand(1);
7137 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7138 Node->getOperand(2), DAG.getIntPtrConstant(0));
7139 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7140 Node->getOperand(2), DAG.getIntPtrConstant(1));
7141 SDValue Ops[] = { Chain, In1, In2L, In2H };
7142 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7144 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7145 cast<MemSDNode>(Node)->getMemOperand());
7146 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7147 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7148 Results.push_back(Result.getValue(2));
7151 /// ReplaceNodeResults - Replace a node with an illegal result type
7152 /// with a new node built out of custom code.
7153 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7154 SmallVectorImpl<SDValue>&Results,
7155 SelectionDAG &DAG) {
7156 DebugLoc dl = N->getDebugLoc();
7157 switch (N->getOpcode()) {
7159 assert(false && "Do not know how to custom type legalize this operation!");
7161 case ISD::FP_TO_SINT: {
7162 std::pair<SDValue,SDValue> Vals =
7163 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7164 SDValue FIST = Vals.first, StackSlot = Vals.second;
7165 if (FIST.getNode() != 0) {
7166 EVT VT = N->getValueType(0);
7167 // Return a load from the stack slot.
7168 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7172 case ISD::READCYCLECOUNTER: {
7173 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7174 SDValue TheChain = N->getOperand(0);
7175 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7176 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7178 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7180 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7181 SDValue Ops[] = { eax, edx };
7182 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7183 Results.push_back(edx.getValue(1));
7190 EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7191 Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7194 case ISD::ATOMIC_CMP_SWAP: {
7195 EVT T = N->getValueType(0);
7196 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7197 SDValue cpInL, cpInH;
7198 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7199 DAG.getConstant(0, MVT::i32));
7200 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7201 DAG.getConstant(1, MVT::i32));
7202 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7203 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7205 SDValue swapInL, swapInH;
7206 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7207 DAG.getConstant(0, MVT::i32));
7208 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7209 DAG.getConstant(1, MVT::i32));
7210 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7212 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7213 swapInL.getValue(1));
7214 SDValue Ops[] = { swapInH.getValue(0),
7216 swapInH.getValue(1) };
7217 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7218 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7219 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7220 MVT::i32, Result.getValue(1));
7221 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7222 MVT::i32, cpOutL.getValue(2));
7223 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7224 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7225 Results.push_back(cpOutH.getValue(1));
7228 case ISD::ATOMIC_LOAD_ADD:
7229 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7231 case ISD::ATOMIC_LOAD_AND:
7232 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7234 case ISD::ATOMIC_LOAD_NAND:
7235 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7237 case ISD::ATOMIC_LOAD_OR:
7238 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7240 case ISD::ATOMIC_LOAD_SUB:
7241 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7243 case ISD::ATOMIC_LOAD_XOR:
7244 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7246 case ISD::ATOMIC_SWAP:
7247 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7252 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7254 default: return NULL;
7255 case X86ISD::BSF: return "X86ISD::BSF";
7256 case X86ISD::BSR: return "X86ISD::BSR";
7257 case X86ISD::SHLD: return "X86ISD::SHLD";
7258 case X86ISD::SHRD: return "X86ISD::SHRD";
7259 case X86ISD::FAND: return "X86ISD::FAND";
7260 case X86ISD::FOR: return "X86ISD::FOR";
7261 case X86ISD::FXOR: return "X86ISD::FXOR";
7262 case X86ISD::FSRL: return "X86ISD::FSRL";
7263 case X86ISD::FILD: return "X86ISD::FILD";
7264 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7265 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7266 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7267 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7268 case X86ISD::FLD: return "X86ISD::FLD";
7269 case X86ISD::FST: return "X86ISD::FST";
7270 case X86ISD::CALL: return "X86ISD::CALL";
7271 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7272 case X86ISD::BT: return "X86ISD::BT";
7273 case X86ISD::CMP: return "X86ISD::CMP";
7274 case X86ISD::COMI: return "X86ISD::COMI";
7275 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7276 case X86ISD::SETCC: return "X86ISD::SETCC";
7277 case X86ISD::CMOV: return "X86ISD::CMOV";
7278 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7279 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7280 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7281 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7282 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7283 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7284 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7285 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7286 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7287 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7288 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7289 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7290 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7291 case X86ISD::FMAX: return "X86ISD::FMAX";
7292 case X86ISD::FMIN: return "X86ISD::FMIN";
7293 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7294 case X86ISD::FRCP: return "X86ISD::FRCP";
7295 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7296 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7297 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7298 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7299 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7300 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7301 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7302 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7303 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7304 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7305 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7306 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7307 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7308 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7309 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7310 case X86ISD::VSHL: return "X86ISD::VSHL";
7311 case X86ISD::VSRL: return "X86ISD::VSRL";
7312 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7313 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7314 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7315 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7316 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7317 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7318 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7319 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7320 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7321 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7322 case X86ISD::ADD: return "X86ISD::ADD";
7323 case X86ISD::SUB: return "X86ISD::SUB";
7324 case X86ISD::SMUL: return "X86ISD::SMUL";
7325 case X86ISD::UMUL: return "X86ISD::UMUL";
7326 case X86ISD::INC: return "X86ISD::INC";
7327 case X86ISD::DEC: return "X86ISD::DEC";
7328 case X86ISD::OR: return "X86ISD::OR";
7329 case X86ISD::XOR: return "X86ISD::XOR";
7330 case X86ISD::AND: return "X86ISD::AND";
7331 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7332 case X86ISD::PTEST: return "X86ISD::PTEST";
7333 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7337 // isLegalAddressingMode - Return true if the addressing mode represented
7338 // by AM is legal for this target, for a load/store of the specified type.
7339 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7340 const Type *Ty) const {
7341 // X86 supports extremely general addressing modes.
7342 CodeModel::Model M = getTargetMachine().getCodeModel();
7344 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7345 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7350 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7352 // If a reference to this global requires an extra load, we can't fold it.
7353 if (isGlobalStubReference(GVFlags))
7356 // If BaseGV requires a register for the PIC base, we cannot also have a
7357 // BaseReg specified.
7358 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7361 // If lower 4G is not available, then we must use rip-relative addressing.
7362 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7372 // These scales always work.
7377 // These scales are formed with basereg+scalereg. Only accept if there is
7382 default: // Other stuff never works.
7390 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7391 if (!Ty1->isInteger() || !Ty2->isInteger())
7393 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7394 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7395 if (NumBits1 <= NumBits2)
7397 return Subtarget->is64Bit() || NumBits1 < 64;
7400 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7401 if (!VT1.isInteger() || !VT2.isInteger())
7403 unsigned NumBits1 = VT1.getSizeInBits();
7404 unsigned NumBits2 = VT2.getSizeInBits();
7405 if (NumBits1 <= NumBits2)
7407 return Subtarget->is64Bit() || NumBits1 < 64;
7410 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7411 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7412 return Ty1 == Type::getInt32Ty(Ty1->getContext()) &&
7413 Ty2 == Type::getInt64Ty(Ty1->getContext()) && Subtarget->is64Bit();
7416 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7417 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7418 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7421 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7422 // i16 instructions are longer (0x66 prefix) and potentially slower.
7423 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7426 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7427 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7428 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7429 /// are assumed to be legal.
7431 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7433 // Only do shuffles on 128-bit vector types for now.
7434 if (VT.getSizeInBits() == 64)
7437 // FIXME: pshufb, blends, shifts.
7438 return (VT.getVectorNumElements() == 2 ||
7439 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7440 isMOVLMask(M, VT) ||
7441 isSHUFPMask(M, VT) ||
7442 isPSHUFDMask(M, VT) ||
7443 isPSHUFHWMask(M, VT) ||
7444 isPSHUFLWMask(M, VT) ||
7445 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7446 isUNPCKLMask(M, VT) ||
7447 isUNPCKHMask(M, VT) ||
7448 isUNPCKL_v_undef_Mask(M, VT) ||
7449 isUNPCKH_v_undef_Mask(M, VT));
7453 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7455 unsigned NumElts = VT.getVectorNumElements();
7456 // FIXME: This collection of masks seems suspect.
7459 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7460 return (isMOVLMask(Mask, VT) ||
7461 isCommutedMOVLMask(Mask, VT, true) ||
7462 isSHUFPMask(Mask, VT) ||
7463 isCommutedSHUFPMask(Mask, VT));
7468 //===----------------------------------------------------------------------===//
7469 // X86 Scheduler Hooks
7470 //===----------------------------------------------------------------------===//
7472 // private utility function
7474 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7475 MachineBasicBlock *MBB,
7483 TargetRegisterClass *RC,
7484 bool invSrc) const {
7485 // For the atomic bitwise operator, we generate
7488 // ld t1 = [bitinstr.addr]
7489 // op t2 = t1, [bitinstr.val]
7491 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7493 // fallthrough -->nextMBB
7494 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7495 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7496 MachineFunction::iterator MBBIter = MBB;
7499 /// First build the CFG
7500 MachineFunction *F = MBB->getParent();
7501 MachineBasicBlock *thisMBB = MBB;
7502 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7503 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7504 F->insert(MBBIter, newMBB);
7505 F->insert(MBBIter, nextMBB);
7507 // Move all successors to thisMBB to nextMBB
7508 nextMBB->transferSuccessors(thisMBB);
7510 // Update thisMBB to fall through to newMBB
7511 thisMBB->addSuccessor(newMBB);
7513 // newMBB jumps to itself and fall through to nextMBB
7514 newMBB->addSuccessor(nextMBB);
7515 newMBB->addSuccessor(newMBB);
7517 // Insert instructions into newMBB based on incoming instruction
7518 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7519 "unexpected number of operands");
7520 DebugLoc dl = bInstr->getDebugLoc();
7521 MachineOperand& destOper = bInstr->getOperand(0);
7522 MachineOperand* argOpers[2 + X86AddrNumOperands];
7523 int numArgs = bInstr->getNumOperands() - 1;
7524 for (int i=0; i < numArgs; ++i)
7525 argOpers[i] = &bInstr->getOperand(i+1);
7527 // x86 address has 4 operands: base, index, scale, and displacement
7528 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7529 int valArgIndx = lastAddrIndx + 1;
7531 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7532 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7533 for (int i=0; i <= lastAddrIndx; ++i)
7534 (*MIB).addOperand(*argOpers[i]);
7536 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7538 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7543 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7544 assert((argOpers[valArgIndx]->isReg() ||
7545 argOpers[valArgIndx]->isImm()) &&
7547 if (argOpers[valArgIndx]->isReg())
7548 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7550 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7552 (*MIB).addOperand(*argOpers[valArgIndx]);
7554 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7557 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7558 for (int i=0; i <= lastAddrIndx; ++i)
7559 (*MIB).addOperand(*argOpers[i]);
7561 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7562 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7563 bInstr->memoperands_end());
7565 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7569 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7571 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7575 // private utility function: 64 bit atomics on 32 bit host.
7577 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7578 MachineBasicBlock *MBB,
7583 bool invSrc) const {
7584 // For the atomic bitwise operator, we generate
7585 // thisMBB (instructions are in pairs, except cmpxchg8b)
7586 // ld t1,t2 = [bitinstr.addr]
7588 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7589 // op t5, t6 <- out1, out2, [bitinstr.val]
7590 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7591 // mov ECX, EBX <- t5, t6
7592 // mov EAX, EDX <- t1, t2
7593 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7594 // mov t3, t4 <- EAX, EDX
7596 // result in out1, out2
7597 // fallthrough -->nextMBB
7599 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7600 const unsigned LoadOpc = X86::MOV32rm;
7601 const unsigned copyOpc = X86::MOV32rr;
7602 const unsigned NotOpc = X86::NOT32r;
7603 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7604 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7605 MachineFunction::iterator MBBIter = MBB;
7608 /// First build the CFG
7609 MachineFunction *F = MBB->getParent();
7610 MachineBasicBlock *thisMBB = MBB;
7611 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7612 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7613 F->insert(MBBIter, newMBB);
7614 F->insert(MBBIter, nextMBB);
7616 // Move all successors to thisMBB to nextMBB
7617 nextMBB->transferSuccessors(thisMBB);
7619 // Update thisMBB to fall through to newMBB
7620 thisMBB->addSuccessor(newMBB);
7622 // newMBB jumps to itself and fall through to nextMBB
7623 newMBB->addSuccessor(nextMBB);
7624 newMBB->addSuccessor(newMBB);
7626 DebugLoc dl = bInstr->getDebugLoc();
7627 // Insert instructions into newMBB based on incoming instruction
7628 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7629 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7630 "unexpected number of operands");
7631 MachineOperand& dest1Oper = bInstr->getOperand(0);
7632 MachineOperand& dest2Oper = bInstr->getOperand(1);
7633 MachineOperand* argOpers[2 + X86AddrNumOperands];
7634 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7635 argOpers[i] = &bInstr->getOperand(i+2);
7637 // x86 address has 4 operands: base, index, scale, and displacement
7638 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7640 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7641 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7642 for (int i=0; i <= lastAddrIndx; ++i)
7643 (*MIB).addOperand(*argOpers[i]);
7644 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7645 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7646 // add 4 to displacement.
7647 for (int i=0; i <= lastAddrIndx-2; ++i)
7648 (*MIB).addOperand(*argOpers[i]);
7649 MachineOperand newOp3 = *(argOpers[3]);
7651 newOp3.setImm(newOp3.getImm()+4);
7653 newOp3.setOffset(newOp3.getOffset()+4);
7654 (*MIB).addOperand(newOp3);
7655 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7657 // t3/4 are defined later, at the bottom of the loop
7658 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7659 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7660 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7661 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7662 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7663 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7665 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7666 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7668 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7669 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7675 int valArgIndx = lastAddrIndx + 1;
7676 assert((argOpers[valArgIndx]->isReg() ||
7677 argOpers[valArgIndx]->isImm()) &&
7679 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7680 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7681 if (argOpers[valArgIndx]->isReg())
7682 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7684 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7685 if (regOpcL != X86::MOV32rr)
7687 (*MIB).addOperand(*argOpers[valArgIndx]);
7688 assert(argOpers[valArgIndx + 1]->isReg() ==
7689 argOpers[valArgIndx]->isReg());
7690 assert(argOpers[valArgIndx + 1]->isImm() ==
7691 argOpers[valArgIndx]->isImm());
7692 if (argOpers[valArgIndx + 1]->isReg())
7693 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7695 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7696 if (regOpcH != X86::MOV32rr)
7698 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7700 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7702 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7705 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7707 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7710 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7711 for (int i=0; i <= lastAddrIndx; ++i)
7712 (*MIB).addOperand(*argOpers[i]);
7714 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7715 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7716 bInstr->memoperands_end());
7718 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7719 MIB.addReg(X86::EAX);
7720 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7721 MIB.addReg(X86::EDX);
7724 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7726 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7730 // private utility function
7732 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7733 MachineBasicBlock *MBB,
7734 unsigned cmovOpc) const {
7735 // For the atomic min/max operator, we generate
7738 // ld t1 = [min/max.addr]
7739 // mov t2 = [min/max.val]
7741 // cmov[cond] t2 = t1
7743 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7745 // fallthrough -->nextMBB
7747 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7748 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7749 MachineFunction::iterator MBBIter = MBB;
7752 /// First build the CFG
7753 MachineFunction *F = MBB->getParent();
7754 MachineBasicBlock *thisMBB = MBB;
7755 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7756 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7757 F->insert(MBBIter, newMBB);
7758 F->insert(MBBIter, nextMBB);
7760 // Move all successors of thisMBB to nextMBB
7761 nextMBB->transferSuccessors(thisMBB);
7763 // Update thisMBB to fall through to newMBB
7764 thisMBB->addSuccessor(newMBB);
7766 // newMBB jumps to newMBB and fall through to nextMBB
7767 newMBB->addSuccessor(nextMBB);
7768 newMBB->addSuccessor(newMBB);
7770 DebugLoc dl = mInstr->getDebugLoc();
7771 // Insert instructions into newMBB based on incoming instruction
7772 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7773 "unexpected number of operands");
7774 MachineOperand& destOper = mInstr->getOperand(0);
7775 MachineOperand* argOpers[2 + X86AddrNumOperands];
7776 int numArgs = mInstr->getNumOperands() - 1;
7777 for (int i=0; i < numArgs; ++i)
7778 argOpers[i] = &mInstr->getOperand(i+1);
7780 // x86 address has 4 operands: base, index, scale, and displacement
7781 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7782 int valArgIndx = lastAddrIndx + 1;
7784 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7785 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7786 for (int i=0; i <= lastAddrIndx; ++i)
7787 (*MIB).addOperand(*argOpers[i]);
7789 // We only support register and immediate values
7790 assert((argOpers[valArgIndx]->isReg() ||
7791 argOpers[valArgIndx]->isImm()) &&
7794 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7795 if (argOpers[valArgIndx]->isReg())
7796 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7798 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7799 (*MIB).addOperand(*argOpers[valArgIndx]);
7801 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7804 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7809 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7810 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7814 // Cmp and exchange if none has modified the memory location
7815 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7816 for (int i=0; i <= lastAddrIndx; ++i)
7817 (*MIB).addOperand(*argOpers[i]);
7819 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7820 (*MIB).setMemRefs(mInstr->memoperands_begin(),
7821 mInstr->memoperands_end());
7823 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7824 MIB.addReg(X86::EAX);
7827 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7829 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7833 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
7834 // all of this code can be replaced with that in the .td file.
7836 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
7837 unsigned numArgs, bool memArg) const {
7839 MachineFunction *F = BB->getParent();
7840 DebugLoc dl = MI->getDebugLoc();
7841 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7845 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
7847 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
7849 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
7851 for (unsigned i = 0; i < numArgs; ++i) {
7852 MachineOperand &Op = MI->getOperand(i+1);
7854 if (!(Op.isReg() && Op.isImplicit()))
7858 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
7861 F->DeleteMachineInstr(MI);
7867 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
7869 MachineBasicBlock *MBB) const {
7870 // Emit code to save XMM registers to the stack. The ABI says that the
7871 // number of registers to save is given in %al, so it's theoretically
7872 // possible to do an indirect jump trick to avoid saving all of them,
7873 // however this code takes a simpler approach and just executes all
7874 // of the stores if %al is non-zero. It's less code, and it's probably
7875 // easier on the hardware branch predictor, and stores aren't all that
7876 // expensive anyway.
7878 // Create the new basic blocks. One block contains all the XMM stores,
7879 // and one block is the final destination regardless of whether any
7880 // stores were performed.
7881 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7882 MachineFunction *F = MBB->getParent();
7883 MachineFunction::iterator MBBIter = MBB;
7885 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
7886 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
7887 F->insert(MBBIter, XMMSaveMBB);
7888 F->insert(MBBIter, EndMBB);
7891 // Move any original successors of MBB to the end block.
7892 EndMBB->transferSuccessors(MBB);
7893 // The original block will now fall through to the XMM save block.
7894 MBB->addSuccessor(XMMSaveMBB);
7895 // The XMMSaveMBB will fall through to the end block.
7896 XMMSaveMBB->addSuccessor(EndMBB);
7898 // Now add the instructions.
7899 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7900 DebugLoc DL = MI->getDebugLoc();
7902 unsigned CountReg = MI->getOperand(0).getReg();
7903 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
7904 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
7906 if (!Subtarget->isTargetWin64()) {
7907 // If %al is 0, branch around the XMM save block.
7908 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
7909 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
7910 MBB->addSuccessor(EndMBB);
7913 // In the XMM save block, save all the XMM argument registers.
7914 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
7915 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
7916 MachineMemOperand *MMO =
7917 F->getMachineMemOperand(
7918 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
7919 MachineMemOperand::MOStore, Offset,
7920 /*Size=*/16, /*Align=*/16);
7921 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
7922 .addFrameIndex(RegSaveFrameIndex)
7923 .addImm(/*Scale=*/1)
7924 .addReg(/*IndexReg=*/0)
7925 .addImm(/*Disp=*/Offset)
7926 .addReg(/*Segment=*/0)
7927 .addReg(MI->getOperand(i).getReg())
7928 .addMemOperand(MMO);
7931 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7937 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
7938 MachineBasicBlock *BB,
7939 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
7940 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7941 DebugLoc DL = MI->getDebugLoc();
7943 // To "insert" a SELECT_CC instruction, we actually have to insert the
7944 // diamond control-flow pattern. The incoming instruction knows the
7945 // destination vreg to set, the condition code register to branch on, the
7946 // true/false values to select between, and a branch opcode to use.
7947 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7948 MachineFunction::iterator It = BB;
7954 // cmpTY ccX, r1, r2
7956 // fallthrough --> copy0MBB
7957 MachineBasicBlock *thisMBB = BB;
7958 MachineFunction *F = BB->getParent();
7959 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7960 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7962 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7963 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
7964 F->insert(It, copy0MBB);
7965 F->insert(It, sinkMBB);
7966 // Update machine-CFG edges by first adding all successors of the current
7967 // block to the new block which will contain the Phi node for the select.
7968 // Also inform sdisel of the edge changes.
7969 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
7970 E = BB->succ_end(); I != E; ++I) {
7971 EM->insert(std::make_pair(*I, sinkMBB));
7972 sinkMBB->addSuccessor(*I);
7974 // Next, remove all successors of the current block, and add the true
7975 // and fallthrough blocks as its successors.
7976 while (!BB->succ_empty())
7977 BB->removeSuccessor(BB->succ_begin());
7978 // Add the true and fallthrough blocks as its successors.
7979 BB->addSuccessor(copy0MBB);
7980 BB->addSuccessor(sinkMBB);
7983 // %FalseValue = ...
7984 // # fallthrough to sinkMBB
7987 // Update machine-CFG edges
7988 BB->addSuccessor(sinkMBB);
7991 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7994 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
7995 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7996 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7998 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8004 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8005 MachineBasicBlock *BB,
8006 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8007 switch (MI->getOpcode()) {
8008 default: assert(false && "Unexpected instr type to insert");
8010 case X86::CMOV_V1I64:
8011 case X86::CMOV_FR32:
8012 case X86::CMOV_FR64:
8013 case X86::CMOV_V4F32:
8014 case X86::CMOV_V2F64:
8015 case X86::CMOV_V2I64:
8016 return EmitLoweredSelect(MI, BB, EM);
8018 case X86::FP32_TO_INT16_IN_MEM:
8019 case X86::FP32_TO_INT32_IN_MEM:
8020 case X86::FP32_TO_INT64_IN_MEM:
8021 case X86::FP64_TO_INT16_IN_MEM:
8022 case X86::FP64_TO_INT32_IN_MEM:
8023 case X86::FP64_TO_INT64_IN_MEM:
8024 case X86::FP80_TO_INT16_IN_MEM:
8025 case X86::FP80_TO_INT32_IN_MEM:
8026 case X86::FP80_TO_INT64_IN_MEM: {
8027 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8028 DebugLoc DL = MI->getDebugLoc();
8030 // Change the floating point control register to use "round towards zero"
8031 // mode when truncating to an integer value.
8032 MachineFunction *F = BB->getParent();
8033 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8034 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8036 // Load the old value of the high byte of the control word...
8038 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8039 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8042 // Set the high part to be round to zero...
8043 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8046 // Reload the modified control word now...
8047 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8049 // Restore the memory image of control word to original value
8050 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8053 // Get the X86 opcode to use.
8055 switch (MI->getOpcode()) {
8056 default: llvm_unreachable("illegal opcode!");
8057 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8058 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8059 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8060 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8061 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8062 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8063 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8064 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8065 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8069 MachineOperand &Op = MI->getOperand(0);
8071 AM.BaseType = X86AddressMode::RegBase;
8072 AM.Base.Reg = Op.getReg();
8074 AM.BaseType = X86AddressMode::FrameIndexBase;
8075 AM.Base.FrameIndex = Op.getIndex();
8077 Op = MI->getOperand(1);
8079 AM.Scale = Op.getImm();
8080 Op = MI->getOperand(2);
8082 AM.IndexReg = Op.getImm();
8083 Op = MI->getOperand(3);
8084 if (Op.isGlobal()) {
8085 AM.GV = Op.getGlobal();
8087 AM.Disp = Op.getImm();
8089 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8090 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8092 // Reload the original control word now.
8093 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8095 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8098 // String/text processing lowering.
8099 case X86::PCMPISTRM128REG:
8100 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8101 case X86::PCMPISTRM128MEM:
8102 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8103 case X86::PCMPESTRM128REG:
8104 return EmitPCMP(MI, BB, 5, false /* in mem */);
8105 case X86::PCMPESTRM128MEM:
8106 return EmitPCMP(MI, BB, 5, true /* in mem */);
8109 case X86::ATOMAND32:
8110 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8111 X86::AND32ri, X86::MOV32rm,
8112 X86::LCMPXCHG32, X86::MOV32rr,
8113 X86::NOT32r, X86::EAX,
8114 X86::GR32RegisterClass);
8116 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8117 X86::OR32ri, X86::MOV32rm,
8118 X86::LCMPXCHG32, X86::MOV32rr,
8119 X86::NOT32r, X86::EAX,
8120 X86::GR32RegisterClass);
8121 case X86::ATOMXOR32:
8122 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8123 X86::XOR32ri, X86::MOV32rm,
8124 X86::LCMPXCHG32, X86::MOV32rr,
8125 X86::NOT32r, X86::EAX,
8126 X86::GR32RegisterClass);
8127 case X86::ATOMNAND32:
8128 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8129 X86::AND32ri, X86::MOV32rm,
8130 X86::LCMPXCHG32, X86::MOV32rr,
8131 X86::NOT32r, X86::EAX,
8132 X86::GR32RegisterClass, true);
8133 case X86::ATOMMIN32:
8134 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8135 case X86::ATOMMAX32:
8136 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8137 case X86::ATOMUMIN32:
8138 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8139 case X86::ATOMUMAX32:
8140 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8142 case X86::ATOMAND16:
8143 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8144 X86::AND16ri, X86::MOV16rm,
8145 X86::LCMPXCHG16, X86::MOV16rr,
8146 X86::NOT16r, X86::AX,
8147 X86::GR16RegisterClass);
8149 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8150 X86::OR16ri, X86::MOV16rm,
8151 X86::LCMPXCHG16, X86::MOV16rr,
8152 X86::NOT16r, X86::AX,
8153 X86::GR16RegisterClass);
8154 case X86::ATOMXOR16:
8155 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8156 X86::XOR16ri, X86::MOV16rm,
8157 X86::LCMPXCHG16, X86::MOV16rr,
8158 X86::NOT16r, X86::AX,
8159 X86::GR16RegisterClass);
8160 case X86::ATOMNAND16:
8161 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8162 X86::AND16ri, X86::MOV16rm,
8163 X86::LCMPXCHG16, X86::MOV16rr,
8164 X86::NOT16r, X86::AX,
8165 X86::GR16RegisterClass, true);
8166 case X86::ATOMMIN16:
8167 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8168 case X86::ATOMMAX16:
8169 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8170 case X86::ATOMUMIN16:
8171 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8172 case X86::ATOMUMAX16:
8173 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8176 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8177 X86::AND8ri, X86::MOV8rm,
8178 X86::LCMPXCHG8, X86::MOV8rr,
8179 X86::NOT8r, X86::AL,
8180 X86::GR8RegisterClass);
8182 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8183 X86::OR8ri, X86::MOV8rm,
8184 X86::LCMPXCHG8, X86::MOV8rr,
8185 X86::NOT8r, X86::AL,
8186 X86::GR8RegisterClass);
8188 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8189 X86::XOR8ri, X86::MOV8rm,
8190 X86::LCMPXCHG8, X86::MOV8rr,
8191 X86::NOT8r, X86::AL,
8192 X86::GR8RegisterClass);
8193 case X86::ATOMNAND8:
8194 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8195 X86::AND8ri, X86::MOV8rm,
8196 X86::LCMPXCHG8, X86::MOV8rr,
8197 X86::NOT8r, X86::AL,
8198 X86::GR8RegisterClass, true);
8199 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8200 // This group is for 64-bit host.
8201 case X86::ATOMAND64:
8202 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8203 X86::AND64ri32, X86::MOV64rm,
8204 X86::LCMPXCHG64, X86::MOV64rr,
8205 X86::NOT64r, X86::RAX,
8206 X86::GR64RegisterClass);
8208 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8209 X86::OR64ri32, X86::MOV64rm,
8210 X86::LCMPXCHG64, X86::MOV64rr,
8211 X86::NOT64r, X86::RAX,
8212 X86::GR64RegisterClass);
8213 case X86::ATOMXOR64:
8214 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8215 X86::XOR64ri32, X86::MOV64rm,
8216 X86::LCMPXCHG64, X86::MOV64rr,
8217 X86::NOT64r, X86::RAX,
8218 X86::GR64RegisterClass);
8219 case X86::ATOMNAND64:
8220 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8221 X86::AND64ri32, X86::MOV64rm,
8222 X86::LCMPXCHG64, X86::MOV64rr,
8223 X86::NOT64r, X86::RAX,
8224 X86::GR64RegisterClass, true);
8225 case X86::ATOMMIN64:
8226 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8227 case X86::ATOMMAX64:
8228 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8229 case X86::ATOMUMIN64:
8230 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8231 case X86::ATOMUMAX64:
8232 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8234 // This group does 64-bit operations on a 32-bit host.
8235 case X86::ATOMAND6432:
8236 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8237 X86::AND32rr, X86::AND32rr,
8238 X86::AND32ri, X86::AND32ri,
8240 case X86::ATOMOR6432:
8241 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8242 X86::OR32rr, X86::OR32rr,
8243 X86::OR32ri, X86::OR32ri,
8245 case X86::ATOMXOR6432:
8246 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8247 X86::XOR32rr, X86::XOR32rr,
8248 X86::XOR32ri, X86::XOR32ri,
8250 case X86::ATOMNAND6432:
8251 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8252 X86::AND32rr, X86::AND32rr,
8253 X86::AND32ri, X86::AND32ri,
8255 case X86::ATOMADD6432:
8256 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8257 X86::ADD32rr, X86::ADC32rr,
8258 X86::ADD32ri, X86::ADC32ri,
8260 case X86::ATOMSUB6432:
8261 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8262 X86::SUB32rr, X86::SBB32rr,
8263 X86::SUB32ri, X86::SBB32ri,
8265 case X86::ATOMSWAP6432:
8266 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8267 X86::MOV32rr, X86::MOV32rr,
8268 X86::MOV32ri, X86::MOV32ri,
8270 case X86::VASTART_SAVE_XMM_REGS:
8271 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8275 //===----------------------------------------------------------------------===//
8276 // X86 Optimization Hooks
8277 //===----------------------------------------------------------------------===//
8279 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8283 const SelectionDAG &DAG,
8284 unsigned Depth) const {
8285 unsigned Opc = Op.getOpcode();
8286 assert((Opc >= ISD::BUILTIN_OP_END ||
8287 Opc == ISD::INTRINSIC_WO_CHAIN ||
8288 Opc == ISD::INTRINSIC_W_CHAIN ||
8289 Opc == ISD::INTRINSIC_VOID) &&
8290 "Should use MaskedValueIsZero if you don't know whether Op"
8291 " is a target node!");
8293 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8305 // These nodes' second result is a boolean.
8306 if (Op.getResNo() == 0)
8310 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8311 Mask.getBitWidth() - 1);
8316 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8317 /// node is a GlobalAddress + offset.
8318 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8319 GlobalValue* &GA, int64_t &Offset) const{
8320 if (N->getOpcode() == X86ISD::Wrapper) {
8321 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8322 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8323 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8327 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8330 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8331 const TargetLowering &TLI) {
8334 if (TLI.isGAPlusOffset(Base, GV, Offset))
8335 return (GV->getAlignment() >= N && (Offset % N) == 0);
8336 // DAG combine handles the stack object case.
8340 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8341 EVT EltVT, LoadSDNode *&LDBase,
8342 unsigned &LastLoadedElt,
8343 SelectionDAG &DAG, MachineFrameInfo *MFI,
8344 const TargetLowering &TLI) {
8346 LastLoadedElt = -1U;
8347 for (unsigned i = 0; i < NumElems; ++i) {
8348 if (N->getMaskElt(i) < 0) {
8354 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8355 if (!Elt.getNode() ||
8356 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8359 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8361 LDBase = cast<LoadSDNode>(Elt.getNode());
8365 if (Elt.getOpcode() == ISD::UNDEF)
8368 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8369 if (!TLI.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i, MFI))
8376 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8377 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8378 /// if the load addresses are consecutive, non-overlapping, and in the right
8379 /// order. In the case of v2i64, it will see if it can rewrite the
8380 /// shuffle to be an appropriate build vector so it can take advantage of
8381 // performBuildVectorCombine.
8382 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8383 const TargetLowering &TLI) {
8384 DebugLoc dl = N->getDebugLoc();
8385 EVT VT = N->getValueType(0);
8386 EVT EltVT = VT.getVectorElementType();
8387 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8388 unsigned NumElems = VT.getVectorNumElements();
8390 if (VT.getSizeInBits() != 128)
8393 // Try to combine a vector_shuffle into a 128-bit load.
8394 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8395 LoadSDNode *LD = NULL;
8396 unsigned LastLoadedElt;
8397 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8401 if (LastLoadedElt == NumElems - 1) {
8402 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
8403 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8404 LD->getSrcValue(), LD->getSrcValueOffset(),
8406 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8407 LD->getSrcValue(), LD->getSrcValueOffset(),
8408 LD->isVolatile(), LD->getAlignment());
8409 } else if (NumElems == 4 && LastLoadedElt == 1) {
8410 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8411 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8412 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8413 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8418 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8419 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8420 const X86Subtarget *Subtarget) {
8421 DebugLoc DL = N->getDebugLoc();
8422 SDValue Cond = N->getOperand(0);
8423 // Get the LHS/RHS of the select.
8424 SDValue LHS = N->getOperand(1);
8425 SDValue RHS = N->getOperand(2);
8427 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8428 // instructions have the peculiarity that if either operand is a NaN,
8429 // they chose what we call the RHS operand (and as such are not symmetric).
8430 // It happens that this matches the semantics of the common C idiom
8431 // x<y?x:y and related forms, so we can recognize these cases.
8432 if (Subtarget->hasSSE2() &&
8433 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8434 Cond.getOpcode() == ISD::SETCC) {
8435 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8437 unsigned Opcode = 0;
8438 // Check for x CC y ? x : y.
8439 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8443 // This can be a min if we can prove that at least one of the operands
8445 if (!FiniteOnlyFPMath()) {
8446 if (DAG.isKnownNeverNaN(RHS)) {
8447 // Put the potential NaN in the RHS so that SSE will preserve it.
8448 std::swap(LHS, RHS);
8449 } else if (!DAG.isKnownNeverNaN(LHS))
8452 Opcode = X86ISD::FMIN;
8455 // This can be a min if we can prove that at least one of the operands
8457 if (!FiniteOnlyFPMath()) {
8458 if (DAG.isKnownNeverNaN(LHS)) {
8459 // Put the potential NaN in the RHS so that SSE will preserve it.
8460 std::swap(LHS, RHS);
8461 } else if (!DAG.isKnownNeverNaN(RHS))
8464 Opcode = X86ISD::FMIN;
8467 // This can be a min, but if either operand is a NaN we need it to
8468 // preserve the original LHS.
8469 std::swap(LHS, RHS);
8473 Opcode = X86ISD::FMIN;
8477 // This can be a max if we can prove that at least one of the operands
8479 if (!FiniteOnlyFPMath()) {
8480 if (DAG.isKnownNeverNaN(LHS)) {
8481 // Put the potential NaN in the RHS so that SSE will preserve it.
8482 std::swap(LHS, RHS);
8483 } else if (!DAG.isKnownNeverNaN(RHS))
8486 Opcode = X86ISD::FMAX;
8489 // This can be a max if we can prove that at least one of the operands
8491 if (!FiniteOnlyFPMath()) {
8492 if (DAG.isKnownNeverNaN(RHS)) {
8493 // Put the potential NaN in the RHS so that SSE will preserve it.
8494 std::swap(LHS, RHS);
8495 } else if (!DAG.isKnownNeverNaN(LHS))
8498 Opcode = X86ISD::FMAX;
8501 // This can be a max, but if either operand is a NaN we need it to
8502 // preserve the original LHS.
8503 std::swap(LHS, RHS);
8507 Opcode = X86ISD::FMAX;
8510 // Check for x CC y ? y : x -- a min/max with reversed arms.
8511 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8515 // This can be a min if we can prove that at least one of the operands
8517 if (!FiniteOnlyFPMath()) {
8518 if (DAG.isKnownNeverNaN(RHS)) {
8519 // Put the potential NaN in the RHS so that SSE will preserve it.
8520 std::swap(LHS, RHS);
8521 } else if (!DAG.isKnownNeverNaN(LHS))
8524 Opcode = X86ISD::FMIN;
8527 // This can be a min if we can prove that at least one of the operands
8529 if (!FiniteOnlyFPMath()) {
8530 if (DAG.isKnownNeverNaN(LHS)) {
8531 // Put the potential NaN in the RHS so that SSE will preserve it.
8532 std::swap(LHS, RHS);
8533 } else if (!DAG.isKnownNeverNaN(RHS))
8536 Opcode = X86ISD::FMIN;
8539 // This can be a min, but if either operand is a NaN we need it to
8540 // preserve the original LHS.
8541 std::swap(LHS, RHS);
8545 Opcode = X86ISD::FMIN;
8549 // This can be a max if we can prove that at least one of the operands
8551 if (!FiniteOnlyFPMath()) {
8552 if (DAG.isKnownNeverNaN(LHS)) {
8553 // Put the potential NaN in the RHS so that SSE will preserve it.
8554 std::swap(LHS, RHS);
8555 } else if (!DAG.isKnownNeverNaN(RHS))
8558 Opcode = X86ISD::FMAX;
8561 // This can be a max if we can prove that at least one of the operands
8563 if (!FiniteOnlyFPMath()) {
8564 if (DAG.isKnownNeverNaN(RHS)) {
8565 // Put the potential NaN in the RHS so that SSE will preserve it.
8566 std::swap(LHS, RHS);
8567 } else if (!DAG.isKnownNeverNaN(LHS))
8570 Opcode = X86ISD::FMAX;
8573 // This can be a max, but if either operand is a NaN we need it to
8574 // preserve the original LHS.
8575 std::swap(LHS, RHS);
8579 Opcode = X86ISD::FMAX;
8585 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8588 // If this is a select between two integer constants, try to do some
8590 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8591 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8592 // Don't do this for crazy integer types.
8593 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8594 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8595 // so that TrueC (the true value) is larger than FalseC.
8596 bool NeedsCondInvert = false;
8598 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8599 // Efficiently invertible.
8600 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8601 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8602 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8603 NeedsCondInvert = true;
8604 std::swap(TrueC, FalseC);
8607 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8608 if (FalseC->getAPIntValue() == 0 &&
8609 TrueC->getAPIntValue().isPowerOf2()) {
8610 if (NeedsCondInvert) // Invert the condition if needed.
8611 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8612 DAG.getConstant(1, Cond.getValueType()));
8614 // Zero extend the condition if needed.
8615 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8617 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8618 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8619 DAG.getConstant(ShAmt, MVT::i8));
8622 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8623 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8624 if (NeedsCondInvert) // Invert the condition if needed.
8625 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8626 DAG.getConstant(1, Cond.getValueType()));
8628 // Zero extend the condition if needed.
8629 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8630 FalseC->getValueType(0), Cond);
8631 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8632 SDValue(FalseC, 0));
8635 // Optimize cases that will turn into an LEA instruction. This requires
8636 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8637 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8638 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8639 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8641 bool isFastMultiplier = false;
8643 switch ((unsigned char)Diff) {
8645 case 1: // result = add base, cond
8646 case 2: // result = lea base( , cond*2)
8647 case 3: // result = lea base(cond, cond*2)
8648 case 4: // result = lea base( , cond*4)
8649 case 5: // result = lea base(cond, cond*4)
8650 case 8: // result = lea base( , cond*8)
8651 case 9: // result = lea base(cond, cond*8)
8652 isFastMultiplier = true;
8657 if (isFastMultiplier) {
8658 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8659 if (NeedsCondInvert) // Invert the condition if needed.
8660 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8661 DAG.getConstant(1, Cond.getValueType()));
8663 // Zero extend the condition if needed.
8664 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8666 // Scale the condition by the difference.
8668 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8669 DAG.getConstant(Diff, Cond.getValueType()));
8671 // Add the base if non-zero.
8672 if (FalseC->getAPIntValue() != 0)
8673 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8674 SDValue(FalseC, 0));
8684 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8685 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8686 TargetLowering::DAGCombinerInfo &DCI) {
8687 DebugLoc DL = N->getDebugLoc();
8689 // If the flag operand isn't dead, don't touch this CMOV.
8690 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8693 // If this is a select between two integer constants, try to do some
8694 // optimizations. Note that the operands are ordered the opposite of SELECT
8696 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8697 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8698 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8699 // larger than FalseC (the false value).
8700 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8702 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8703 CC = X86::GetOppositeBranchCondition(CC);
8704 std::swap(TrueC, FalseC);
8707 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8708 // This is efficient for any integer data type (including i8/i16) and
8710 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8711 SDValue Cond = N->getOperand(3);
8712 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8713 DAG.getConstant(CC, MVT::i8), Cond);
8715 // Zero extend the condition if needed.
8716 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8718 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8719 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8720 DAG.getConstant(ShAmt, MVT::i8));
8721 if (N->getNumValues() == 2) // Dead flag value?
8722 return DCI.CombineTo(N, Cond, SDValue());
8726 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8727 // for any integer data type, including i8/i16.
8728 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8729 SDValue Cond = N->getOperand(3);
8730 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8731 DAG.getConstant(CC, MVT::i8), Cond);
8733 // Zero extend the condition if needed.
8734 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8735 FalseC->getValueType(0), Cond);
8736 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8737 SDValue(FalseC, 0));
8739 if (N->getNumValues() == 2) // Dead flag value?
8740 return DCI.CombineTo(N, Cond, SDValue());
8744 // Optimize cases that will turn into an LEA instruction. This requires
8745 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8746 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8747 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8748 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8750 bool isFastMultiplier = false;
8752 switch ((unsigned char)Diff) {
8754 case 1: // result = add base, cond
8755 case 2: // result = lea base( , cond*2)
8756 case 3: // result = lea base(cond, cond*2)
8757 case 4: // result = lea base( , cond*4)
8758 case 5: // result = lea base(cond, cond*4)
8759 case 8: // result = lea base( , cond*8)
8760 case 9: // result = lea base(cond, cond*8)
8761 isFastMultiplier = true;
8766 if (isFastMultiplier) {
8767 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8768 SDValue Cond = N->getOperand(3);
8769 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8770 DAG.getConstant(CC, MVT::i8), Cond);
8771 // Zero extend the condition if needed.
8772 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8774 // Scale the condition by the difference.
8776 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8777 DAG.getConstant(Diff, Cond.getValueType()));
8779 // Add the base if non-zero.
8780 if (FalseC->getAPIntValue() != 0)
8781 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8782 SDValue(FalseC, 0));
8783 if (N->getNumValues() == 2) // Dead flag value?
8784 return DCI.CombineTo(N, Cond, SDValue());
8794 /// PerformMulCombine - Optimize a single multiply with constant into two
8795 /// in order to implement it with two cheaper instructions, e.g.
8796 /// LEA + SHL, LEA + LEA.
8797 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8798 TargetLowering::DAGCombinerInfo &DCI) {
8799 if (DAG.getMachineFunction().
8800 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8803 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8806 EVT VT = N->getValueType(0);
8810 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8813 uint64_t MulAmt = C->getZExtValue();
8814 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8817 uint64_t MulAmt1 = 0;
8818 uint64_t MulAmt2 = 0;
8819 if ((MulAmt % 9) == 0) {
8821 MulAmt2 = MulAmt / 9;
8822 } else if ((MulAmt % 5) == 0) {
8824 MulAmt2 = MulAmt / 5;
8825 } else if ((MulAmt % 3) == 0) {
8827 MulAmt2 = MulAmt / 3;
8830 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8831 DebugLoc DL = N->getDebugLoc();
8833 if (isPowerOf2_64(MulAmt2) &&
8834 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8835 // If second multiplifer is pow2, issue it first. We want the multiply by
8836 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8838 std::swap(MulAmt1, MulAmt2);
8841 if (isPowerOf2_64(MulAmt1))
8842 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8843 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8845 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8846 DAG.getConstant(MulAmt1, VT));
8848 if (isPowerOf2_64(MulAmt2))
8849 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8850 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8852 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8853 DAG.getConstant(MulAmt2, VT));
8855 // Do not add new nodes to DAG combiner worklist.
8856 DCI.CombineTo(N, NewMul, false);
8862 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8864 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8865 const X86Subtarget *Subtarget) {
8866 // On X86 with SSE2 support, we can transform this to a vector shift if
8867 // all elements are shifted by the same amount. We can't do this in legalize
8868 // because the a constant vector is typically transformed to a constant pool
8869 // so we have no knowledge of the shift amount.
8870 if (!Subtarget->hasSSE2())
8873 EVT VT = N->getValueType(0);
8874 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8877 SDValue ShAmtOp = N->getOperand(1);
8878 EVT EltVT = VT.getVectorElementType();
8879 DebugLoc DL = N->getDebugLoc();
8880 SDValue BaseShAmt = SDValue();
8881 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8882 unsigned NumElts = VT.getVectorNumElements();
8884 for (; i != NumElts; ++i) {
8885 SDValue Arg = ShAmtOp.getOperand(i);
8886 if (Arg.getOpcode() == ISD::UNDEF) continue;
8890 for (; i != NumElts; ++i) {
8891 SDValue Arg = ShAmtOp.getOperand(i);
8892 if (Arg.getOpcode() == ISD::UNDEF) continue;
8893 if (Arg != BaseShAmt) {
8897 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8898 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8899 SDValue InVec = ShAmtOp.getOperand(0);
8900 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8901 unsigned NumElts = InVec.getValueType().getVectorNumElements();
8903 for (; i != NumElts; ++i) {
8904 SDValue Arg = InVec.getOperand(i);
8905 if (Arg.getOpcode() == ISD::UNDEF) continue;
8909 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8910 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
8911 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
8912 if (C->getZExtValue() == SplatIdx)
8913 BaseShAmt = InVec.getOperand(1);
8916 if (BaseShAmt.getNode() == 0)
8917 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8918 DAG.getIntPtrConstant(0));
8922 // The shift amount is an i32.
8923 if (EltVT.bitsGT(MVT::i32))
8924 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8925 else if (EltVT.bitsLT(MVT::i32))
8926 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
8928 // The shift amount is identical so we can do a vector shift.
8929 SDValue ValOp = N->getOperand(0);
8930 switch (N->getOpcode()) {
8932 llvm_unreachable("Unknown shift opcode!");
8935 if (VT == MVT::v2i64)
8936 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8937 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8939 if (VT == MVT::v4i32)
8940 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8941 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8943 if (VT == MVT::v8i16)
8944 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8945 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8949 if (VT == MVT::v4i32)
8950 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8951 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8953 if (VT == MVT::v8i16)
8954 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8955 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8959 if (VT == MVT::v2i64)
8960 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8961 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8963 if (VT == MVT::v4i32)
8964 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8965 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8967 if (VT == MVT::v8i16)
8968 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8969 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8976 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8977 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8978 const X86Subtarget *Subtarget) {
8979 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8980 // the FP state in cases where an emms may be missing.
8981 // A preferable solution to the general problem is to figure out the right
8982 // places to insert EMMS. This qualifies as a quick hack.
8984 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8985 StoreSDNode *St = cast<StoreSDNode>(N);
8986 EVT VT = St->getValue().getValueType();
8987 if (VT.getSizeInBits() != 64)
8990 const Function *F = DAG.getMachineFunction().getFunction();
8991 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8992 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8993 && Subtarget->hasSSE2();
8994 if ((VT.isVector() ||
8995 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8996 isa<LoadSDNode>(St->getValue()) &&
8997 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8998 St->getChain().hasOneUse() && !St->isVolatile()) {
8999 SDNode* LdVal = St->getValue().getNode();
9001 int TokenFactorIndex = -1;
9002 SmallVector<SDValue, 8> Ops;
9003 SDNode* ChainVal = St->getChain().getNode();
9004 // Must be a store of a load. We currently handle two cases: the load
9005 // is a direct child, and it's under an intervening TokenFactor. It is
9006 // possible to dig deeper under nested TokenFactors.
9007 if (ChainVal == LdVal)
9008 Ld = cast<LoadSDNode>(St->getChain());
9009 else if (St->getValue().hasOneUse() &&
9010 ChainVal->getOpcode() == ISD::TokenFactor) {
9011 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9012 if (ChainVal->getOperand(i).getNode() == LdVal) {
9013 TokenFactorIndex = i;
9014 Ld = cast<LoadSDNode>(St->getValue());
9016 Ops.push_back(ChainVal->getOperand(i));
9020 if (!Ld || !ISD::isNormalLoad(Ld))
9023 // If this is not the MMX case, i.e. we are just turning i64 load/store
9024 // into f64 load/store, avoid the transformation if there are multiple
9025 // uses of the loaded value.
9026 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9029 DebugLoc LdDL = Ld->getDebugLoc();
9030 DebugLoc StDL = N->getDebugLoc();
9031 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9032 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9034 if (Subtarget->is64Bit() || F64IsLegal) {
9035 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9036 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9037 Ld->getBasePtr(), Ld->getSrcValue(),
9038 Ld->getSrcValueOffset(), Ld->isVolatile(),
9039 Ld->getAlignment());
9040 SDValue NewChain = NewLd.getValue(1);
9041 if (TokenFactorIndex != -1) {
9042 Ops.push_back(NewChain);
9043 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9046 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9047 St->getSrcValue(), St->getSrcValueOffset(),
9048 St->isVolatile(), St->getAlignment());
9051 // Otherwise, lower to two pairs of 32-bit loads / stores.
9052 SDValue LoAddr = Ld->getBasePtr();
9053 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9054 DAG.getConstant(4, MVT::i32));
9056 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9057 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9058 Ld->isVolatile(), Ld->getAlignment());
9059 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9060 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9062 MinAlign(Ld->getAlignment(), 4));
9064 SDValue NewChain = LoLd.getValue(1);
9065 if (TokenFactorIndex != -1) {
9066 Ops.push_back(LoLd);
9067 Ops.push_back(HiLd);
9068 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9072 LoAddr = St->getBasePtr();
9073 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9074 DAG.getConstant(4, MVT::i32));
9076 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9077 St->getSrcValue(), St->getSrcValueOffset(),
9078 St->isVolatile(), St->getAlignment());
9079 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9081 St->getSrcValueOffset() + 4,
9083 MinAlign(St->getAlignment(), 4));
9084 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9089 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9090 /// X86ISD::FXOR nodes.
9091 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9092 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9093 // F[X]OR(0.0, x) -> x
9094 // F[X]OR(x, 0.0) -> x
9095 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9096 if (C->getValueAPF().isPosZero())
9097 return N->getOperand(1);
9098 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9099 if (C->getValueAPF().isPosZero())
9100 return N->getOperand(0);
9104 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9105 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9106 // FAND(0.0, x) -> 0.0
9107 // FAND(x, 0.0) -> 0.0
9108 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9109 if (C->getValueAPF().isPosZero())
9110 return N->getOperand(0);
9111 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9112 if (C->getValueAPF().isPosZero())
9113 return N->getOperand(1);
9117 static SDValue PerformBTCombine(SDNode *N,
9119 TargetLowering::DAGCombinerInfo &DCI) {
9120 // BT ignores high bits in the bit index operand.
9121 SDValue Op1 = N->getOperand(1);
9122 if (Op1.hasOneUse()) {
9123 unsigned BitWidth = Op1.getValueSizeInBits();
9124 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9125 APInt KnownZero, KnownOne;
9126 TargetLowering::TargetLoweringOpt TLO(DAG);
9127 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9128 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9129 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9130 DCI.CommitTargetLoweringOpt(TLO);
9135 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9136 SDValue Op = N->getOperand(0);
9137 if (Op.getOpcode() == ISD::BIT_CONVERT)
9138 Op = Op.getOperand(0);
9139 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9140 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9141 VT.getVectorElementType().getSizeInBits() ==
9142 OpVT.getVectorElementType().getSizeInBits()) {
9143 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9148 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9149 // Locked instructions, in turn, have implicit fence semantics (all memory
9150 // operations are flushed before issuing the locked instruction, and the
9151 // are not buffered), so we can fold away the common pattern of
9152 // fence-atomic-fence.
9153 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9154 SDValue atomic = N->getOperand(0);
9155 switch (atomic.getOpcode()) {
9156 case ISD::ATOMIC_CMP_SWAP:
9157 case ISD::ATOMIC_SWAP:
9158 case ISD::ATOMIC_LOAD_ADD:
9159 case ISD::ATOMIC_LOAD_SUB:
9160 case ISD::ATOMIC_LOAD_AND:
9161 case ISD::ATOMIC_LOAD_OR:
9162 case ISD::ATOMIC_LOAD_XOR:
9163 case ISD::ATOMIC_LOAD_NAND:
9164 case ISD::ATOMIC_LOAD_MIN:
9165 case ISD::ATOMIC_LOAD_MAX:
9166 case ISD::ATOMIC_LOAD_UMIN:
9167 case ISD::ATOMIC_LOAD_UMAX:
9173 SDValue fence = atomic.getOperand(0);
9174 if (fence.getOpcode() != ISD::MEMBARRIER)
9177 switch (atomic.getOpcode()) {
9178 case ISD::ATOMIC_CMP_SWAP:
9179 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9180 atomic.getOperand(1), atomic.getOperand(2),
9181 atomic.getOperand(3));
9182 case ISD::ATOMIC_SWAP:
9183 case ISD::ATOMIC_LOAD_ADD:
9184 case ISD::ATOMIC_LOAD_SUB:
9185 case ISD::ATOMIC_LOAD_AND:
9186 case ISD::ATOMIC_LOAD_OR:
9187 case ISD::ATOMIC_LOAD_XOR:
9188 case ISD::ATOMIC_LOAD_NAND:
9189 case ISD::ATOMIC_LOAD_MIN:
9190 case ISD::ATOMIC_LOAD_MAX:
9191 case ISD::ATOMIC_LOAD_UMIN:
9192 case ISD::ATOMIC_LOAD_UMAX:
9193 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9194 atomic.getOperand(1), atomic.getOperand(2));
9200 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9201 DAGCombinerInfo &DCI) const {
9202 SelectionDAG &DAG = DCI.DAG;
9203 switch (N->getOpcode()) {
9205 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9206 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9207 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9208 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9211 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9212 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9214 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9215 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9216 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9217 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9218 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9224 //===----------------------------------------------------------------------===//
9225 // X86 Inline Assembly Support
9226 //===----------------------------------------------------------------------===//
9228 static bool LowerToBSwap(CallInst *CI) {
9229 // FIXME: this should verify that we are targetting a 486 or better. If not,
9230 // we will turn this bswap into something that will be lowered to logical ops
9231 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9232 // so don't worry about this.
9234 // Verify this is a simple bswap.
9235 if (CI->getNumOperands() != 2 ||
9236 CI->getType() != CI->getOperand(1)->getType() ||
9237 !CI->getType()->isInteger())
9240 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9241 if (!Ty || Ty->getBitWidth() % 16 != 0)
9244 // Okay, we can do this xform, do so now.
9245 const Type *Tys[] = { Ty };
9246 Module *M = CI->getParent()->getParent()->getParent();
9247 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9249 Value *Op = CI->getOperand(1);
9250 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9252 CI->replaceAllUsesWith(Op);
9253 CI->eraseFromParent();
9257 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9258 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9259 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9261 std::string AsmStr = IA->getAsmString();
9263 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9264 std::vector<std::string> AsmPieces;
9265 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9267 switch (AsmPieces.size()) {
9268 default: return false;
9270 AsmStr = AsmPieces[0];
9272 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9275 if (AsmPieces.size() == 2 &&
9276 (AsmPieces[0] == "bswap" ||
9277 AsmPieces[0] == "bswapq" ||
9278 AsmPieces[0] == "bswapl") &&
9279 (AsmPieces[1] == "$0" ||
9280 AsmPieces[1] == "${0:q}")) {
9281 // No need to check constraints, nothing other than the equivalent of
9282 // "=r,0" would be valid here.
9283 return LowerToBSwap(CI);
9285 // rorw $$8, ${0:w} --> llvm.bswap.i16
9286 if (CI->getType() == Type::getInt16Ty(CI->getContext()) &&
9287 AsmPieces.size() == 3 &&
9288 AsmPieces[0] == "rorw" &&
9289 AsmPieces[1] == "$$8," &&
9290 AsmPieces[2] == "${0:w}" &&
9291 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9292 return LowerToBSwap(CI);
9296 if (CI->getType() == Type::getInt64Ty(CI->getContext()) &&
9297 Constraints.size() >= 2 &&
9298 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9299 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9300 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9301 std::vector<std::string> Words;
9302 SplitString(AsmPieces[0], Words, " \t");
9303 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9305 SplitString(AsmPieces[1], Words, " \t");
9306 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9308 SplitString(AsmPieces[2], Words, " \t,");
9309 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9310 Words[2] == "%edx") {
9311 return LowerToBSwap(CI);
9323 /// getConstraintType - Given a constraint letter, return the type of
9324 /// constraint it is for this target.
9325 X86TargetLowering::ConstraintType
9326 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9327 if (Constraint.size() == 1) {
9328 switch (Constraint[0]) {
9340 return C_RegisterClass;
9348 return TargetLowering::getConstraintType(Constraint);
9351 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9352 /// with another that has more specific requirements based on the type of the
9353 /// corresponding operand.
9354 const char *X86TargetLowering::
9355 LowerXConstraint(EVT ConstraintVT) const {
9356 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9357 // 'f' like normal targets.
9358 if (ConstraintVT.isFloatingPoint()) {
9359 if (Subtarget->hasSSE2())
9361 if (Subtarget->hasSSE1())
9365 return TargetLowering::LowerXConstraint(ConstraintVT);
9368 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9369 /// vector. If it is invalid, don't add anything to Ops.
9370 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9373 std::vector<SDValue>&Ops,
9374 SelectionDAG &DAG) const {
9375 SDValue Result(0, 0);
9377 switch (Constraint) {
9380 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9381 if (C->getZExtValue() <= 31) {
9382 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9388 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9389 if (C->getZExtValue() <= 63) {
9390 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9396 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9397 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9398 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9404 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9405 if (C->getZExtValue() <= 255) {
9406 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9412 // 32-bit signed value
9413 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9414 const ConstantInt *CI = C->getConstantIntValue();
9415 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9416 C->getSExtValue())) {
9417 // Widen to 64 bits here to get it sign extended.
9418 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9421 // FIXME gcc accepts some relocatable values here too, but only in certain
9422 // memory models; it's complicated.
9427 // 32-bit unsigned value
9428 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9429 const ConstantInt *CI = C->getConstantIntValue();
9430 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9431 C->getZExtValue())) {
9432 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9436 // FIXME gcc accepts some relocatable values here too, but only in certain
9437 // memory models; it's complicated.
9441 // Literal immediates are always ok.
9442 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9443 // Widen to 64 bits here to get it sign extended.
9444 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9448 // If we are in non-pic codegen mode, we allow the address of a global (with
9449 // an optional displacement) to be used with 'i'.
9450 GlobalAddressSDNode *GA = 0;
9453 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9455 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9456 Offset += GA->getOffset();
9458 } else if (Op.getOpcode() == ISD::ADD) {
9459 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9460 Offset += C->getZExtValue();
9461 Op = Op.getOperand(0);
9464 } else if (Op.getOpcode() == ISD::SUB) {
9465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9466 Offset += -C->getZExtValue();
9467 Op = Op.getOperand(0);
9472 // Otherwise, this isn't something we can handle, reject it.
9476 GlobalValue *GV = GA->getGlobal();
9477 // If we require an extra load to get this address, as in PIC mode, we
9479 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9480 getTargetMachine())))
9484 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9486 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9492 if (Result.getNode()) {
9493 Ops.push_back(Result);
9496 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9500 std::vector<unsigned> X86TargetLowering::
9501 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9503 if (Constraint.size() == 1) {
9504 // FIXME: not handling fp-stack yet!
9505 switch (Constraint[0]) { // GCC X86 Constraint Letters
9506 default: break; // Unknown constraint letter
9507 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9508 if (Subtarget->is64Bit()) {
9510 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9511 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9512 X86::R10D,X86::R11D,X86::R12D,
9513 X86::R13D,X86::R14D,X86::R15D,
9514 X86::EBP, X86::ESP, 0);
9515 else if (VT == MVT::i16)
9516 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9517 X86::SI, X86::DI, X86::R8W,X86::R9W,
9518 X86::R10W,X86::R11W,X86::R12W,
9519 X86::R13W,X86::R14W,X86::R15W,
9520 X86::BP, X86::SP, 0);
9521 else if (VT == MVT::i8)
9522 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9523 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9524 X86::R10B,X86::R11B,X86::R12B,
9525 X86::R13B,X86::R14B,X86::R15B,
9526 X86::BPL, X86::SPL, 0);
9528 else if (VT == MVT::i64)
9529 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9530 X86::RSI, X86::RDI, X86::R8, X86::R9,
9531 X86::R10, X86::R11, X86::R12,
9532 X86::R13, X86::R14, X86::R15,
9533 X86::RBP, X86::RSP, 0);
9537 // 32-bit fallthrough
9540 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9541 else if (VT == MVT::i16)
9542 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9543 else if (VT == MVT::i8)
9544 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9545 else if (VT == MVT::i64)
9546 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9551 return std::vector<unsigned>();
9554 std::pair<unsigned, const TargetRegisterClass*>
9555 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9557 // First, see if this is a constraint that directly corresponds to an LLVM
9559 if (Constraint.size() == 1) {
9560 // GCC Constraint Letters
9561 switch (Constraint[0]) {
9563 case 'r': // GENERAL_REGS
9564 case 'l': // INDEX_REGS
9566 return std::make_pair(0U, X86::GR8RegisterClass);
9568 return std::make_pair(0U, X86::GR16RegisterClass);
9569 if (VT == MVT::i32 || !Subtarget->is64Bit())
9570 return std::make_pair(0U, X86::GR32RegisterClass);
9571 return std::make_pair(0U, X86::GR64RegisterClass);
9572 case 'R': // LEGACY_REGS
9574 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9576 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9577 if (VT == MVT::i32 || !Subtarget->is64Bit())
9578 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9579 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9580 case 'f': // FP Stack registers.
9581 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9582 // value to the correct fpstack register class.
9583 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9584 return std::make_pair(0U, X86::RFP32RegisterClass);
9585 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9586 return std::make_pair(0U, X86::RFP64RegisterClass);
9587 return std::make_pair(0U, X86::RFP80RegisterClass);
9588 case 'y': // MMX_REGS if MMX allowed.
9589 if (!Subtarget->hasMMX()) break;
9590 return std::make_pair(0U, X86::VR64RegisterClass);
9591 case 'Y': // SSE_REGS if SSE2 allowed
9592 if (!Subtarget->hasSSE2()) break;
9594 case 'x': // SSE_REGS if SSE1 allowed
9595 if (!Subtarget->hasSSE1()) break;
9597 switch (VT.getSimpleVT().SimpleTy) {
9599 // Scalar SSE types.
9602 return std::make_pair(0U, X86::FR32RegisterClass);
9605 return std::make_pair(0U, X86::FR64RegisterClass);
9613 return std::make_pair(0U, X86::VR128RegisterClass);
9619 // Use the default implementation in TargetLowering to convert the register
9620 // constraint into a member of a register class.
9621 std::pair<unsigned, const TargetRegisterClass*> Res;
9622 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9624 // Not found as a standard register?
9625 if (Res.second == 0) {
9626 // Map st(0) -> st(7) -> ST0
9627 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9628 tolower(Constraint[1]) == 's' &&
9629 tolower(Constraint[2]) == 't' &&
9630 Constraint[3] == '(' &&
9631 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9632 Constraint[5] == ')' &&
9633 Constraint[6] == '}') {
9635 Res.first = X86::ST0+Constraint[4]-'0';
9636 Res.second = X86::RFP80RegisterClass;
9640 // GCC allows "st(0)" to be called just plain "st".
9641 if (StringRef("{st}").equals_lower(Constraint)) {
9642 Res.first = X86::ST0;
9643 Res.second = X86::RFP80RegisterClass;
9648 if (StringRef("{flags}").equals_lower(Constraint)) {
9649 Res.first = X86::EFLAGS;
9650 Res.second = X86::CCRRegisterClass;
9654 // 'A' means EAX + EDX.
9655 if (Constraint == "A") {
9656 Res.first = X86::EAX;
9657 Res.second = X86::GR32_ADRegisterClass;
9663 // Otherwise, check to see if this is a register class of the wrong value
9664 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9665 // turn into {ax},{dx}.
9666 if (Res.second->hasType(VT))
9667 return Res; // Correct type already, nothing to do.
9669 // All of the single-register GCC register classes map their values onto
9670 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9671 // really want an 8-bit or 32-bit register, map to the appropriate register
9672 // class and return the appropriate register.
9673 if (Res.second == X86::GR16RegisterClass) {
9674 if (VT == MVT::i8) {
9675 unsigned DestReg = 0;
9676 switch (Res.first) {
9678 case X86::AX: DestReg = X86::AL; break;
9679 case X86::DX: DestReg = X86::DL; break;
9680 case X86::CX: DestReg = X86::CL; break;
9681 case X86::BX: DestReg = X86::BL; break;
9684 Res.first = DestReg;
9685 Res.second = X86::GR8RegisterClass;
9687 } else if (VT == MVT::i32) {
9688 unsigned DestReg = 0;
9689 switch (Res.first) {
9691 case X86::AX: DestReg = X86::EAX; break;
9692 case X86::DX: DestReg = X86::EDX; break;
9693 case X86::CX: DestReg = X86::ECX; break;
9694 case X86::BX: DestReg = X86::EBX; break;
9695 case X86::SI: DestReg = X86::ESI; break;
9696 case X86::DI: DestReg = X86::EDI; break;
9697 case X86::BP: DestReg = X86::EBP; break;
9698 case X86::SP: DestReg = X86::ESP; break;
9701 Res.first = DestReg;
9702 Res.second = X86::GR32RegisterClass;
9704 } else if (VT == MVT::i64) {
9705 unsigned DestReg = 0;
9706 switch (Res.first) {
9708 case X86::AX: DestReg = X86::RAX; break;
9709 case X86::DX: DestReg = X86::RDX; break;
9710 case X86::CX: DestReg = X86::RCX; break;
9711 case X86::BX: DestReg = X86::RBX; break;
9712 case X86::SI: DestReg = X86::RSI; break;
9713 case X86::DI: DestReg = X86::RDI; break;
9714 case X86::BP: DestReg = X86::RBP; break;
9715 case X86::SP: DestReg = X86::RSP; break;
9718 Res.first = DestReg;
9719 Res.second = X86::GR64RegisterClass;
9722 } else if (Res.second == X86::FR32RegisterClass ||
9723 Res.second == X86::FR64RegisterClass ||
9724 Res.second == X86::VR128RegisterClass) {
9725 // Handle references to XMM physical registers that got mapped into the
9726 // wrong class. This can happen with constraints like {xmm0} where the
9727 // target independent register mapper will just pick the first match it can
9728 // find, ignoring the required type.
9730 Res.second = X86::FR32RegisterClass;
9731 else if (VT == MVT::f64)
9732 Res.second = X86::FR64RegisterClass;
9733 else if (X86::VR128RegisterClass->hasType(VT))
9734 Res.second = X86::VR128RegisterClass;
9740 //===----------------------------------------------------------------------===//
9741 // X86 Widen vector type
9742 //===----------------------------------------------------------------------===//
9744 /// getWidenVectorType: given a vector type, returns the type to widen
9745 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9746 /// If there is no vector type that we want to widen to, returns MVT::Other
9747 /// When and where to widen is target dependent based on the cost of
9748 /// scalarizing vs using the wider vector type.
9750 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
9751 assert(VT.isVector());
9752 if (isTypeLegal(VT))
9755 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9756 // type based on element type. This would speed up our search (though
9757 // it may not be worth it since the size of the list is relatively
9759 EVT EltVT = VT.getVectorElementType();
9760 unsigned NElts = VT.getVectorNumElements();
9762 // On X86, it make sense to widen any vector wider than 1
9766 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9767 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9768 EVT SVT = (MVT::SimpleValueType)nVT;
9770 if (isTypeLegal(SVT) &&
9771 SVT.getVectorElementType() == EltVT &&
9772 SVT.getVectorNumElements() > NElts)