1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
53 using namespace dwarf;
55 STATISTIC(NumTailCalls, "Number of tail calls");
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60 // Disable16Bit - 16-bit operations typically have a larger encoding than
61 // corresponding 32-bit instructions, and 16-bit code is slow on some
62 // processors. This is an experimental flag to disable 16-bit operations
63 // (which forces them to be Legalized to 32-bit operations).
65 Disable16Bit("disable-16bit", cl::Hidden,
66 cl::desc("Disable use of 16-bit instructions"));
68 // Forward declarations.
69 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
72 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
73 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
74 default: llvm_unreachable("unknown subtarget type");
75 case X86Subtarget::isDarwin:
76 if (TM.getSubtarget<X86Subtarget>().is64Bit())
77 return new X8664_MachoTargetObjectFile();
78 return new TargetLoweringObjectFileMachO();
79 case X86Subtarget::isELF:
80 if (TM.getSubtarget<X86Subtarget>().is64Bit())
81 return new X8664_ELFTargetObjectFile(TM);
82 return new X8632_ELFTargetObjectFile(TM);
83 case X86Subtarget::isMingw:
84 case X86Subtarget::isCygwin:
85 case X86Subtarget::isWindows:
86 return new TargetLoweringObjectFileCOFF();
90 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
91 : TargetLowering(TM, createTLOF(TM)) {
92 Subtarget = &TM.getSubtarget<X86Subtarget>();
93 X86ScalarSSEf64 = Subtarget->hasSSE2();
94 X86ScalarSSEf32 = Subtarget->hasSSE1();
95 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
97 RegInfo = TM.getRegisterInfo();
100 // Set up the TargetLowering object.
102 // X86 is weird, it always uses i8 for shift amounts and setcc results.
103 setShiftAmountType(MVT::i8);
104 setBooleanContents(ZeroOrOneBooleanContent);
105 setSchedulingPreference(SchedulingForRegPressure);
106 setStackPointerRegisterToSaveRestore(X86StackPtr);
108 if (Subtarget->isTargetDarwin()) {
109 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
110 setUseUnderscoreSetJmp(false);
111 setUseUnderscoreLongJmp(false);
112 } else if (Subtarget->isTargetMingw()) {
113 // MS runtime is weird: it exports _setjmp, but longjmp!
114 setUseUnderscoreSetJmp(true);
115 setUseUnderscoreLongJmp(false);
117 setUseUnderscoreSetJmp(true);
118 setUseUnderscoreLongJmp(true);
121 // Set up the register classes.
122 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
124 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
125 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
126 if (Subtarget->is64Bit())
127 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
129 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
131 // We don't accept any truncstore of integer registers.
132 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
134 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
135 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
137 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
141 // SETOEQ and SETUNE require checking two conditions.
142 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
149 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
151 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
152 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
153 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
155 if (Subtarget->is64Bit()) {
156 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
157 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
158 } else if (!UseSoftFloat) {
159 if (X86ScalarSSEf64) {
160 // We have an impenetrably clever algorithm for ui64->double only.
161 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
163 // We have an algorithm for SSE2, and we turn this into a 64-bit
164 // FILD for other targets.
165 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
168 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
170 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
171 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
174 // SSE has no i16 to fp conversion, only i32
175 if (X86ScalarSSEf32) {
176 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
177 // f32 and f64 cases are Legal, f80 case is not
178 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
184 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
188 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
189 // are Legal, f80 is custom lowered.
190 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
191 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
193 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
195 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
196 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
198 if (X86ScalarSSEf32) {
199 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
200 // f32 and f64 cases are Legal, f80 case is not
201 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
203 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
204 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
207 // Handle FP_TO_UINT by promoting the destination to a larger signed
209 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
210 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
211 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
213 if (Subtarget->is64Bit()) {
214 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
215 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
216 } else if (!UseSoftFloat) {
217 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
218 // Expand FP_TO_UINT into a select.
219 // FIXME: We would like to use a Custom expander here eventually to do
220 // the optimal thing for SSE vs. the default expansion in the legalizer.
221 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
223 // With SSE3 we can use fisttpll to convert to a signed i64; without
224 // SSE, we're stuck with a fistpll.
225 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
228 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
229 if (!X86ScalarSSEf64) {
230 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
231 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
234 // Scalar integer divide and remainder are lowered to use operations that
235 // produce two results, to match the available instructions. This exposes
236 // the two-result form to trivial CSE, which is able to combine x/y and x%y
237 // into a single instruction.
239 // Scalar integer multiply-high is also lowered to use two-result
240 // operations, to match the available instructions. However, plain multiply
241 // (low) operations are left as Legal, as there are single-result
242 // instructions for this in x86. Using the two-result multiply instructions
243 // when both high and low results are needed must be arranged by dagcombine.
244 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
245 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
246 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
247 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
248 setOperationAction(ISD::SREM , MVT::i8 , Expand);
249 setOperationAction(ISD::UREM , MVT::i8 , Expand);
250 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
251 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
252 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
253 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
254 setOperationAction(ISD::SREM , MVT::i16 , Expand);
255 setOperationAction(ISD::UREM , MVT::i16 , Expand);
256 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
257 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
258 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
259 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
260 setOperationAction(ISD::SREM , MVT::i32 , Expand);
261 setOperationAction(ISD::UREM , MVT::i32 , Expand);
262 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
263 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
264 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
265 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
266 setOperationAction(ISD::SREM , MVT::i64 , Expand);
267 setOperationAction(ISD::UREM , MVT::i64 , Expand);
269 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
270 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
271 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
272 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
273 if (Subtarget->is64Bit())
274 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
275 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
276 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
277 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
278 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
279 setOperationAction(ISD::FREM , MVT::f32 , Expand);
280 setOperationAction(ISD::FREM , MVT::f64 , Expand);
281 setOperationAction(ISD::FREM , MVT::f80 , Expand);
282 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
284 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
285 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
287 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
290 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
292 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
293 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
295 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
296 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
297 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
298 if (Subtarget->is64Bit()) {
299 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
300 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
301 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
304 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
305 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
307 // These should be promoted to a larger select which is supported.
308 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
309 // X86 wants to expand cmov itself.
310 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
312 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
314 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
315 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
316 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
317 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
318 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
319 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
321 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
323 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
324 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
325 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
326 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
327 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
328 if (Subtarget->is64Bit()) {
329 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
330 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
332 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
335 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
336 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
337 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
338 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
339 if (Subtarget->is64Bit())
340 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
341 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
342 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
343 if (Subtarget->is64Bit()) {
344 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
345 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
346 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
347 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
348 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
350 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
351 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
352 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
353 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
354 if (Subtarget->is64Bit()) {
355 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
356 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
357 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
360 if (Subtarget->hasSSE1())
361 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
363 if (!Subtarget->hasSSE2())
364 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
366 // Expand certain atomics
367 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
368 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
369 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
370 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
375 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
377 if (!Subtarget->is64Bit()) {
378 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
379 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
380 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
381 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
382 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
383 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
384 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
387 // FIXME - use subtarget debug flags
388 if (!Subtarget->isTargetDarwin() &&
389 !Subtarget->isTargetELF() &&
390 !Subtarget->isTargetCygMing()) {
391 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
394 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
395 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
396 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
397 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
398 if (Subtarget->is64Bit()) {
399 setExceptionPointerRegister(X86::RAX);
400 setExceptionSelectorRegister(X86::RDX);
402 setExceptionPointerRegister(X86::EAX);
403 setExceptionSelectorRegister(X86::EDX);
405 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
406 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
408 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
410 setOperationAction(ISD::TRAP, MVT::Other, Legal);
412 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
413 setOperationAction(ISD::VASTART , MVT::Other, Custom);
414 setOperationAction(ISD::VAEND , MVT::Other, Expand);
415 if (Subtarget->is64Bit()) {
416 setOperationAction(ISD::VAARG , MVT::Other, Custom);
417 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
419 setOperationAction(ISD::VAARG , MVT::Other, Expand);
420 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
423 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
424 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
425 if (Subtarget->is64Bit())
426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
427 if (Subtarget->isTargetCygMing())
428 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
430 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
432 if (!UseSoftFloat && X86ScalarSSEf64) {
433 // f32 and f64 use SSE.
434 // Set up the FP register classes.
435 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
436 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
438 // Use ANDPD to simulate FABS.
439 setOperationAction(ISD::FABS , MVT::f64, Custom);
440 setOperationAction(ISD::FABS , MVT::f32, Custom);
442 // Use XORP to simulate FNEG.
443 setOperationAction(ISD::FNEG , MVT::f64, Custom);
444 setOperationAction(ISD::FNEG , MVT::f32, Custom);
446 // Use ANDPD and ORPD to simulate FCOPYSIGN.
447 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
448 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
450 // We don't support sin/cos/fmod
451 setOperationAction(ISD::FSIN , MVT::f64, Expand);
452 setOperationAction(ISD::FCOS , MVT::f64, Expand);
453 setOperationAction(ISD::FSIN , MVT::f32, Expand);
454 setOperationAction(ISD::FCOS , MVT::f32, Expand);
456 // Expand FP immediates into loads from the stack, except for the special
458 addLegalFPImmediate(APFloat(+0.0)); // xorpd
459 addLegalFPImmediate(APFloat(+0.0f)); // xorps
460 } else if (!UseSoftFloat && X86ScalarSSEf32) {
461 // Use SSE for f32, x87 for f64.
462 // Set up the FP register classes.
463 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
466 // Use ANDPS to simulate FABS.
467 setOperationAction(ISD::FABS , MVT::f32, Custom);
469 // Use XORP to simulate FNEG.
470 setOperationAction(ISD::FNEG , MVT::f32, Custom);
472 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
474 // Use ANDPS and ORPS to simulate FCOPYSIGN.
475 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
476 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
478 // We don't support sin/cos/fmod
479 setOperationAction(ISD::FSIN , MVT::f32, Expand);
480 setOperationAction(ISD::FCOS , MVT::f32, Expand);
482 // Special cases we handle for FP constants.
483 addLegalFPImmediate(APFloat(+0.0f)); // xorps
484 addLegalFPImmediate(APFloat(+0.0)); // FLD0
485 addLegalFPImmediate(APFloat(+1.0)); // FLD1
486 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
490 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
491 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
493 } else if (!UseSoftFloat) {
494 // f32 and f64 in x87.
495 // Set up the FP register classes.
496 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
497 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
499 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
500 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
501 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
502 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
505 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
506 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
508 addLegalFPImmediate(APFloat(+0.0)); // FLD0
509 addLegalFPImmediate(APFloat(+1.0)); // FLD1
510 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
511 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
512 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
513 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
514 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
515 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
518 // Long double always uses X87.
520 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
521 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
522 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
525 APFloat TmpFlt(+0.0);
526 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
528 addLegalFPImmediate(TmpFlt); // FLD0
530 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
531 APFloat TmpFlt2(+1.0);
532 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
534 addLegalFPImmediate(TmpFlt2); // FLD1
535 TmpFlt2.changeSign();
536 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
540 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
541 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
545 // Always use a library call for pow.
546 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
547 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
548 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
550 setOperationAction(ISD::FLOG, MVT::f80, Expand);
551 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
552 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
553 setOperationAction(ISD::FEXP, MVT::f80, Expand);
554 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
556 // First set operation action for all vector types to either promote
557 // (for widening) or expand (for scalarization). Then we will selectively
558 // turn on ones that can be effectively codegen'd.
559 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
560 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
561 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
576 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
577 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
610 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
611 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
612 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
613 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
614 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
615 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
616 setTruncStoreAction((MVT::SimpleValueType)VT,
617 (MVT::SimpleValueType)InnerVT, Expand);
618 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
619 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
620 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
623 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
624 // with -msoft-float, disable use of MMX as well.
625 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
626 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
627 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
628 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
629 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
630 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
632 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
633 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
634 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
635 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
637 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
638 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
639 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
640 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
642 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
643 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
645 setOperationAction(ISD::AND, MVT::v8i8, Promote);
646 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
647 setOperationAction(ISD::AND, MVT::v4i16, Promote);
648 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
649 setOperationAction(ISD::AND, MVT::v2i32, Promote);
650 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
651 setOperationAction(ISD::AND, MVT::v1i64, Legal);
653 setOperationAction(ISD::OR, MVT::v8i8, Promote);
654 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
655 setOperationAction(ISD::OR, MVT::v4i16, Promote);
656 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
657 setOperationAction(ISD::OR, MVT::v2i32, Promote);
658 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
659 setOperationAction(ISD::OR, MVT::v1i64, Legal);
661 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
662 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
663 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
664 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
665 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
666 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
667 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
669 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
670 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
671 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
672 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
673 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
674 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
675 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
676 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
677 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
679 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
680 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
681 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
682 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
683 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
685 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
686 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
687 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
688 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
690 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
691 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
692 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
693 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
695 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
697 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
698 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
699 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
700 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
701 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
702 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
703 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
706 if (!UseSoftFloat && Subtarget->hasSSE1()) {
707 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
709 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
710 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
711 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
712 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
713 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
714 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
715 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
716 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
719 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
720 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
723 if (!UseSoftFloat && Subtarget->hasSSE2()) {
724 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
726 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
727 // registers cannot be used even for integer operations.
728 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
729 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
730 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
731 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
733 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
734 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
735 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
736 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
737 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
738 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
739 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
740 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
741 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
742 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
743 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
744 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
745 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
746 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
747 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
748 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
750 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
751 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
752 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
753 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
755 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
756 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
757 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
759 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
761 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
762 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
763 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
764 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
765 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
767 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
768 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
769 EVT VT = (MVT::SimpleValueType)i;
770 // Do not attempt to custom lower non-power-of-2 vectors
771 if (!isPowerOf2_32(VT.getVectorNumElements()))
773 // Do not attempt to custom lower non-128-bit vectors
774 if (!VT.is128BitVector())
776 setOperationAction(ISD::BUILD_VECTOR,
777 VT.getSimpleVT().SimpleTy, Custom);
778 setOperationAction(ISD::VECTOR_SHUFFLE,
779 VT.getSimpleVT().SimpleTy, Custom);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
781 VT.getSimpleVT().SimpleTy, Custom);
784 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
785 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
786 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
787 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
788 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
791 if (Subtarget->is64Bit()) {
792 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
793 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
796 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
797 // FIXME: This produces lots of inefficiencies in isel since
798 // we then need notice that most of our operands have been implicitly
799 // converted to v2i64.
800 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
801 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
804 // Do not attempt to promote non-128-bit vectors
805 if (!VT.is128BitVector()) {
809 setOperationAction(ISD::AND, SVT, Promote);
810 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
811 setOperationAction(ISD::OR, SVT, Promote);
812 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
813 setOperationAction(ISD::XOR, SVT, Promote);
814 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
815 setOperationAction(ISD::LOAD, SVT, Promote);
816 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
817 setOperationAction(ISD::SELECT, SVT, Promote);
818 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
821 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
823 // Custom lower v2i64 and v2f64 selects.
824 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
825 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
826 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
827 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
829 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
830 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
831 if (!DisableMMX && Subtarget->hasMMX()) {
832 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
833 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
837 if (Subtarget->hasSSE41()) {
838 // FIXME: Do we need to handle scalar-to-vector here?
839 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
841 // i8 and i16 vectors are custom , because the source register and source
842 // source memory operand types are not the same width. f32 vectors are
843 // custom since the immediate controlling the insert encodes additional
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
847 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
848 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
850 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
851 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
852 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
853 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
855 if (Subtarget->is64Bit()) {
856 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
861 if (Subtarget->hasSSE42()) {
862 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
865 if (!UseSoftFloat && Subtarget->hasAVX()) {
866 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
867 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
868 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
869 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
871 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
872 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
873 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
874 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
875 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
876 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
877 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
878 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
879 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
880 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
881 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
882 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
883 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
884 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
885 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
887 // Operations to consider commented out -v16i16 v32i8
888 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
889 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
890 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
891 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
892 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
893 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
894 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
895 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
896 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
897 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
898 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
899 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
900 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
901 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
903 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
904 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
905 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
906 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
908 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
909 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
910 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
915 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
917 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
918 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
919 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
922 // Not sure we want to do this since there are no 256-bit integer
925 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
926 // This includes 256-bit vectors
927 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
928 EVT VT = (MVT::SimpleValueType)i;
930 // Do not attempt to custom lower non-power-of-2 vectors
931 if (!isPowerOf2_32(VT.getVectorNumElements()))
934 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
935 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
939 if (Subtarget->is64Bit()) {
940 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
946 // Not sure we want to do this since there are no 256-bit integer
949 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
950 // Including 256-bit vectors
951 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
952 EVT VT = (MVT::SimpleValueType)i;
954 if (!VT.is256BitVector()) {
957 setOperationAction(ISD::AND, VT, Promote);
958 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
959 setOperationAction(ISD::OR, VT, Promote);
960 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
961 setOperationAction(ISD::XOR, VT, Promote);
962 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
963 setOperationAction(ISD::LOAD, VT, Promote);
964 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
965 setOperationAction(ISD::SELECT, VT, Promote);
966 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
969 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
973 // We want to custom lower some of our intrinsics.
974 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
976 // Add/Sub/Mul with overflow operations are custom lowered.
977 setOperationAction(ISD::SADDO, MVT::i32, Custom);
978 setOperationAction(ISD::SADDO, MVT::i64, Custom);
979 setOperationAction(ISD::UADDO, MVT::i32, Custom);
980 setOperationAction(ISD::UADDO, MVT::i64, Custom);
981 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
982 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
983 setOperationAction(ISD::USUBO, MVT::i32, Custom);
984 setOperationAction(ISD::USUBO, MVT::i64, Custom);
985 setOperationAction(ISD::SMULO, MVT::i32, Custom);
986 setOperationAction(ISD::SMULO, MVT::i64, Custom);
988 if (!Subtarget->is64Bit()) {
989 // These libcalls are not available in 32-bit.
990 setLibcallName(RTLIB::SHL_I128, 0);
991 setLibcallName(RTLIB::SRL_I128, 0);
992 setLibcallName(RTLIB::SRA_I128, 0);
995 // We have target-specific dag combine patterns for the following nodes:
996 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
997 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
998 setTargetDAGCombine(ISD::BUILD_VECTOR);
999 setTargetDAGCombine(ISD::SELECT);
1000 setTargetDAGCombine(ISD::SHL);
1001 setTargetDAGCombine(ISD::SRA);
1002 setTargetDAGCombine(ISD::SRL);
1003 setTargetDAGCombine(ISD::OR);
1004 setTargetDAGCombine(ISD::STORE);
1005 setTargetDAGCombine(ISD::MEMBARRIER);
1006 setTargetDAGCombine(ISD::ZERO_EXTEND);
1007 if (Subtarget->is64Bit())
1008 setTargetDAGCombine(ISD::MUL);
1010 computeRegisterProperties();
1012 // FIXME: These should be based on subtarget info. Plus, the values should
1013 // be smaller when we are in optimizing for size mode.
1014 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1015 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1016 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1017 setPrefLoopAlignment(16);
1018 benefitFromCodePlacementOpt = true;
1022 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1027 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1028 /// the desired ByVal argument alignment.
1029 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1032 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1033 if (VTy->getBitWidth() == 128)
1035 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1036 unsigned EltAlign = 0;
1037 getMaxByValAlign(ATy->getElementType(), EltAlign);
1038 if (EltAlign > MaxAlign)
1039 MaxAlign = EltAlign;
1040 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1041 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1042 unsigned EltAlign = 0;
1043 getMaxByValAlign(STy->getElementType(i), EltAlign);
1044 if (EltAlign > MaxAlign)
1045 MaxAlign = EltAlign;
1053 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1054 /// function arguments in the caller parameter area. For X86, aggregates
1055 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1056 /// are at 4-byte boundaries.
1057 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1058 if (Subtarget->is64Bit()) {
1059 // Max of 8 and alignment of type.
1060 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1067 if (Subtarget->hasSSE1())
1068 getMaxByValAlign(Ty, Align);
1072 /// getOptimalMemOpType - Returns the target specific optimal type for load
1073 /// and store operations as a result of memset, memcpy, and memmove lowering.
1074 /// If DstAlign is zero that means it's safe to destination alignment can
1075 /// satisfy any constraint. Similarly if SrcAlign is zero it means there
1076 /// isn't a need to check it against alignment requirement, probably because
1077 /// the source does not need to be loaded. It returns EVT::Other if
1078 /// SelectionDAG should be responsible for determining it.
1080 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1081 unsigned DstAlign, unsigned SrcAlign,
1083 SelectionDAG &DAG) const {
1084 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1085 // linux. This is because the stack realignment code can't handle certain
1086 // cases like PR2962. This should be removed when PR2962 is fixed.
1087 const Function *F = DAG.getMachineFunction().getFunction();
1088 if (!F->hasFnAttr(Attribute::NoImplicitFloat)) {
1090 (Subtarget->isUnalignedMemAccessFast() ||
1091 (DstAlign == 0 || DstAlign >= 16) &&
1092 (SrcAlign == 0 || SrcAlign >= 16)) &&
1093 Subtarget->getStackAlignment() >= 16) {
1094 if (Subtarget->hasSSE2())
1096 if (SafeToUseFP && Subtarget->hasSSE1())
1098 } else if (SafeToUseFP &&
1100 Subtarget->getStackAlignment() >= 8 &&
1101 Subtarget->hasSSE2())
1104 if (Subtarget->is64Bit() && Size >= 8)
1109 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1110 /// current function. The returned value is a member of the
1111 /// MachineJumpTableInfo::JTEntryKind enum.
1112 unsigned X86TargetLowering::getJumpTableEncoding() const {
1113 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1115 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1116 Subtarget->isPICStyleGOT())
1117 return MachineJumpTableInfo::EK_Custom32;
1119 // Otherwise, use the normal jump table encoding heuristics.
1120 return TargetLowering::getJumpTableEncoding();
1123 /// getPICBaseSymbol - Return the X86-32 PIC base.
1125 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1126 MCContext &Ctx) const {
1127 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1128 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1129 Twine(MF->getFunctionNumber())+"$pb");
1134 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1135 const MachineBasicBlock *MBB,
1136 unsigned uid,MCContext &Ctx) const{
1137 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1138 Subtarget->isPICStyleGOT());
1139 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1141 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1142 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1145 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1147 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1148 SelectionDAG &DAG) const {
1149 if (!Subtarget->is64Bit())
1150 // This doesn't have DebugLoc associated with it, but is not really the
1151 // same as a Register.
1152 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1157 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1158 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1160 const MCExpr *X86TargetLowering::
1161 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1162 MCContext &Ctx) const {
1163 // X86-64 uses RIP relative addressing based on the jump table label.
1164 if (Subtarget->isPICStyleRIPRel())
1165 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1167 // Otherwise, the reference is relative to the PIC base.
1168 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1171 /// getFunctionAlignment - Return the Log2 alignment of this function.
1172 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1173 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1176 //===----------------------------------------------------------------------===//
1177 // Return Value Calling Convention Implementation
1178 //===----------------------------------------------------------------------===//
1180 #include "X86GenCallingConv.inc"
1183 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1184 const SmallVectorImpl<EVT> &OutTys,
1185 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1186 SelectionDAG &DAG) {
1187 SmallVector<CCValAssign, 16> RVLocs;
1188 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1189 RVLocs, *DAG.getContext());
1190 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1194 X86TargetLowering::LowerReturn(SDValue Chain,
1195 CallingConv::ID CallConv, bool isVarArg,
1196 const SmallVectorImpl<ISD::OutputArg> &Outs,
1197 DebugLoc dl, SelectionDAG &DAG) {
1199 SmallVector<CCValAssign, 16> RVLocs;
1200 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1201 RVLocs, *DAG.getContext());
1202 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1204 // Add the regs to the liveout set for the function.
1205 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1206 for (unsigned i = 0; i != RVLocs.size(); ++i)
1207 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1208 MRI.addLiveOut(RVLocs[i].getLocReg());
1212 SmallVector<SDValue, 6> RetOps;
1213 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1214 // Operand #1 = Bytes To Pop
1215 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1217 // Copy the result values into the output registers.
1218 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1219 CCValAssign &VA = RVLocs[i];
1220 assert(VA.isRegLoc() && "Can only return in registers!");
1221 SDValue ValToCopy = Outs[i].Val;
1223 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1224 // the RET instruction and handled by the FP Stackifier.
1225 if (VA.getLocReg() == X86::ST0 ||
1226 VA.getLocReg() == X86::ST1) {
1227 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1228 // change the value to the FP stack register class.
1229 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1230 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1231 RetOps.push_back(ValToCopy);
1232 // Don't emit a copytoreg.
1236 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1237 // which is returned in RAX / RDX.
1238 if (Subtarget->is64Bit()) {
1239 EVT ValVT = ValToCopy.getValueType();
1240 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1241 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1242 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1243 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1247 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1248 Flag = Chain.getValue(1);
1251 // The x86-64 ABI for returning structs by value requires that we copy
1252 // the sret argument into %rax for the return. We saved the argument into
1253 // a virtual register in the entry block, so now we copy the value out
1255 if (Subtarget->is64Bit() &&
1256 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1257 MachineFunction &MF = DAG.getMachineFunction();
1258 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1259 unsigned Reg = FuncInfo->getSRetReturnReg();
1261 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1262 FuncInfo->setSRetReturnReg(Reg);
1264 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1266 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1267 Flag = Chain.getValue(1);
1269 // RAX now acts like a return value.
1270 MRI.addLiveOut(X86::RAX);
1273 RetOps[0] = Chain; // Update chain.
1275 // Add the flag if we have it.
1277 RetOps.push_back(Flag);
1279 return DAG.getNode(X86ISD::RET_FLAG, dl,
1280 MVT::Other, &RetOps[0], RetOps.size());
1283 /// LowerCallResult - Lower the result values of a call into the
1284 /// appropriate copies out of appropriate physical registers.
1287 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1288 CallingConv::ID CallConv, bool isVarArg,
1289 const SmallVectorImpl<ISD::InputArg> &Ins,
1290 DebugLoc dl, SelectionDAG &DAG,
1291 SmallVectorImpl<SDValue> &InVals) {
1293 // Assign locations to each value returned by this call.
1294 SmallVector<CCValAssign, 16> RVLocs;
1295 bool Is64Bit = Subtarget->is64Bit();
1296 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1297 RVLocs, *DAG.getContext());
1298 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1300 // Copy all of the result registers out of their specified physreg.
1301 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1302 CCValAssign &VA = RVLocs[i];
1303 EVT CopyVT = VA.getValVT();
1305 // If this is x86-64, and we disabled SSE, we can't return FP values
1306 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1307 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1308 llvm_report_error("SSE register return with SSE disabled");
1311 // If this is a call to a function that returns an fp value on the floating
1312 // point stack, but where we prefer to use the value in xmm registers, copy
1313 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1314 if ((VA.getLocReg() == X86::ST0 ||
1315 VA.getLocReg() == X86::ST1) &&
1316 isScalarFPTypeInSSEReg(VA.getValVT())) {
1321 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1322 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1323 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1324 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1325 MVT::v2i64, InFlag).getValue(1);
1326 Val = Chain.getValue(0);
1327 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1328 Val, DAG.getConstant(0, MVT::i64));
1330 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1331 MVT::i64, InFlag).getValue(1);
1332 Val = Chain.getValue(0);
1334 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1336 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1337 CopyVT, InFlag).getValue(1);
1338 Val = Chain.getValue(0);
1340 InFlag = Chain.getValue(2);
1342 if (CopyVT != VA.getValVT()) {
1343 // Round the F80 the right size, which also moves to the appropriate xmm
1345 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1346 // This truncation won't change the value.
1347 DAG.getIntPtrConstant(1));
1350 InVals.push_back(Val);
1357 //===----------------------------------------------------------------------===//
1358 // C & StdCall & Fast Calling Convention implementation
1359 //===----------------------------------------------------------------------===//
1360 // StdCall calling convention seems to be standard for many Windows' API
1361 // routines and around. It differs from C calling convention just a little:
1362 // callee should clean up the stack, not caller. Symbols should be also
1363 // decorated in some fancy way :) It doesn't support any vector arguments.
1364 // For info on fast calling convention see Fast Calling Convention (tail call)
1365 // implementation LowerX86_32FastCCCallTo.
1367 /// CallIsStructReturn - Determines whether a call uses struct return
1369 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1373 return Outs[0].Flags.isSRet();
1376 /// ArgsAreStructReturn - Determines whether a function uses struct
1377 /// return semantics.
1379 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1383 return Ins[0].Flags.isSRet();
1386 /// IsCalleePop - Determines whether the callee is required to pop its
1387 /// own arguments. Callee pop is necessary to support tail calls.
1388 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1392 switch (CallingConv) {
1395 case CallingConv::X86_StdCall:
1396 return !Subtarget->is64Bit();
1397 case CallingConv::X86_FastCall:
1398 return !Subtarget->is64Bit();
1399 case CallingConv::Fast:
1400 return GuaranteedTailCallOpt;
1401 case CallingConv::GHC:
1402 return GuaranteedTailCallOpt;
1406 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1407 /// given CallingConvention value.
1408 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1409 if (Subtarget->is64Bit()) {
1410 if (CC == CallingConv::GHC)
1411 return CC_X86_64_GHC;
1412 else if (Subtarget->isTargetWin64())
1413 return CC_X86_Win64_C;
1418 if (CC == CallingConv::X86_FastCall)
1419 return CC_X86_32_FastCall;
1420 else if (CC == CallingConv::Fast)
1421 return CC_X86_32_FastCC;
1422 else if (CC == CallingConv::GHC)
1423 return CC_X86_32_GHC;
1428 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1429 /// by "Src" to address "Dst" with size and alignment information specified by
1430 /// the specific parameter attribute. The copy will be passed as a byval
1431 /// function parameter.
1433 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1434 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1436 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1437 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1438 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1441 /// IsTailCallConvention - Return true if the calling convention is one that
1442 /// supports tail call optimization.
1443 static bool IsTailCallConvention(CallingConv::ID CC) {
1444 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1447 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1448 /// a tailcall target by changing its ABI.
1449 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1450 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1454 X86TargetLowering::LowerMemArgument(SDValue Chain,
1455 CallingConv::ID CallConv,
1456 const SmallVectorImpl<ISD::InputArg> &Ins,
1457 DebugLoc dl, SelectionDAG &DAG,
1458 const CCValAssign &VA,
1459 MachineFrameInfo *MFI,
1461 // Create the nodes corresponding to a load from this parameter slot.
1462 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1463 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1464 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1467 // If value is passed by pointer we have address passed instead of the value
1469 if (VA.getLocInfo() == CCValAssign::Indirect)
1470 ValVT = VA.getLocVT();
1472 ValVT = VA.getValVT();
1474 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1475 // changed with more analysis.
1476 // In case of tail call optimization mark all arguments mutable. Since they
1477 // could be overwritten by lowering of arguments in case of a tail call.
1478 if (Flags.isByVal()) {
1479 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1480 VA.getLocMemOffset(), isImmutable, false);
1481 return DAG.getFrameIndex(FI, getPointerTy());
1483 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1484 VA.getLocMemOffset(), isImmutable, false);
1485 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1486 return DAG.getLoad(ValVT, dl, Chain, FIN,
1487 PseudoSourceValue::getFixedStack(FI), 0,
1493 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1494 CallingConv::ID CallConv,
1496 const SmallVectorImpl<ISD::InputArg> &Ins,
1499 SmallVectorImpl<SDValue> &InVals) {
1500 MachineFunction &MF = DAG.getMachineFunction();
1501 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1503 const Function* Fn = MF.getFunction();
1504 if (Fn->hasExternalLinkage() &&
1505 Subtarget->isTargetCygMing() &&
1506 Fn->getName() == "main")
1507 FuncInfo->setForceFramePointer(true);
1509 MachineFrameInfo *MFI = MF.getFrameInfo();
1510 bool Is64Bit = Subtarget->is64Bit();
1511 bool IsWin64 = Subtarget->isTargetWin64();
1513 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1514 "Var args not supported with calling convention fastcc or ghc");
1516 // Assign locations to all of the incoming arguments.
1517 SmallVector<CCValAssign, 16> ArgLocs;
1518 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1519 ArgLocs, *DAG.getContext());
1520 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1522 unsigned LastVal = ~0U;
1524 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1525 CCValAssign &VA = ArgLocs[i];
1526 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1528 assert(VA.getValNo() != LastVal &&
1529 "Don't support value assigned to multiple locs yet");
1530 LastVal = VA.getValNo();
1532 if (VA.isRegLoc()) {
1533 EVT RegVT = VA.getLocVT();
1534 TargetRegisterClass *RC = NULL;
1535 if (RegVT == MVT::i32)
1536 RC = X86::GR32RegisterClass;
1537 else if (Is64Bit && RegVT == MVT::i64)
1538 RC = X86::GR64RegisterClass;
1539 else if (RegVT == MVT::f32)
1540 RC = X86::FR32RegisterClass;
1541 else if (RegVT == MVT::f64)
1542 RC = X86::FR64RegisterClass;
1543 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1544 RC = X86::VR128RegisterClass;
1545 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1546 RC = X86::VR64RegisterClass;
1548 llvm_unreachable("Unknown argument type!");
1550 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1551 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1553 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1554 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1556 if (VA.getLocInfo() == CCValAssign::SExt)
1557 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1558 DAG.getValueType(VA.getValVT()));
1559 else if (VA.getLocInfo() == CCValAssign::ZExt)
1560 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1561 DAG.getValueType(VA.getValVT()));
1562 else if (VA.getLocInfo() == CCValAssign::BCvt)
1563 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1565 if (VA.isExtInLoc()) {
1566 // Handle MMX values passed in XMM regs.
1567 if (RegVT.isVector()) {
1568 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1569 ArgValue, DAG.getConstant(0, MVT::i64));
1570 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1572 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1575 assert(VA.isMemLoc());
1576 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1579 // If value is passed via pointer - do a load.
1580 if (VA.getLocInfo() == CCValAssign::Indirect)
1581 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1584 InVals.push_back(ArgValue);
1587 // The x86-64 ABI for returning structs by value requires that we copy
1588 // the sret argument into %rax for the return. Save the argument into
1589 // a virtual register so that we can access it from the return points.
1590 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1591 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1592 unsigned Reg = FuncInfo->getSRetReturnReg();
1594 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1595 FuncInfo->setSRetReturnReg(Reg);
1597 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1598 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1601 unsigned StackSize = CCInfo.getNextStackOffset();
1602 // Align stack specially for tail calls.
1603 if (FuncIsMadeTailCallSafe(CallConv))
1604 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1606 // If the function takes variable number of arguments, make a frame index for
1607 // the start of the first vararg value... for expansion of llvm.va_start.
1609 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1610 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1613 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1615 // FIXME: We should really autogenerate these arrays
1616 static const unsigned GPR64ArgRegsWin64[] = {
1617 X86::RCX, X86::RDX, X86::R8, X86::R9
1619 static const unsigned XMMArgRegsWin64[] = {
1620 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1622 static const unsigned GPR64ArgRegs64Bit[] = {
1623 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1625 static const unsigned XMMArgRegs64Bit[] = {
1626 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1627 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1629 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1632 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1633 GPR64ArgRegs = GPR64ArgRegsWin64;
1634 XMMArgRegs = XMMArgRegsWin64;
1636 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1637 GPR64ArgRegs = GPR64ArgRegs64Bit;
1638 XMMArgRegs = XMMArgRegs64Bit;
1640 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1642 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1645 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1646 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1647 "SSE register cannot be used when SSE is disabled!");
1648 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1649 "SSE register cannot be used when SSE is disabled!");
1650 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1651 // Kernel mode asks for SSE to be disabled, so don't push them
1653 TotalNumXMMRegs = 0;
1655 // For X86-64, if there are vararg parameters that are passed via
1656 // registers, then we must store them to their spots on the stack so they
1657 // may be loaded by deferencing the result of va_next.
1658 VarArgsGPOffset = NumIntRegs * 8;
1659 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1660 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1661 TotalNumXMMRegs * 16, 16,
1664 // Store the integer parameter registers.
1665 SmallVector<SDValue, 8> MemOps;
1666 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1667 unsigned Offset = VarArgsGPOffset;
1668 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1669 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1670 DAG.getIntPtrConstant(Offset));
1671 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1672 X86::GR64RegisterClass);
1673 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1675 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1676 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1677 Offset, false, false, 0);
1678 MemOps.push_back(Store);
1682 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1683 // Now store the XMM (fp + vector) parameter registers.
1684 SmallVector<SDValue, 11> SaveXMMOps;
1685 SaveXMMOps.push_back(Chain);
1687 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1688 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1689 SaveXMMOps.push_back(ALVal);
1691 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1692 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1694 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1695 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1696 X86::VR128RegisterClass);
1697 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1698 SaveXMMOps.push_back(Val);
1700 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1702 &SaveXMMOps[0], SaveXMMOps.size()));
1705 if (!MemOps.empty())
1706 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1707 &MemOps[0], MemOps.size());
1711 // Some CCs need callee pop.
1712 if (IsCalleePop(isVarArg, CallConv)) {
1713 BytesToPopOnReturn = StackSize; // Callee pops everything.
1715 BytesToPopOnReturn = 0; // Callee pops nothing.
1716 // If this is an sret function, the return should pop the hidden pointer.
1717 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1718 BytesToPopOnReturn = 4;
1722 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1723 if (CallConv == CallingConv::X86_FastCall)
1724 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1727 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1733 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1734 SDValue StackPtr, SDValue Arg,
1735 DebugLoc dl, SelectionDAG &DAG,
1736 const CCValAssign &VA,
1737 ISD::ArgFlagsTy Flags) {
1738 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1739 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1740 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1741 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1742 if (Flags.isByVal()) {
1743 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1745 return DAG.getStore(Chain, dl, Arg, PtrOff,
1746 PseudoSourceValue::getStack(), LocMemOffset,
1750 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1751 /// optimization is performed and it is required.
1753 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1754 SDValue &OutRetAddr, SDValue Chain,
1755 bool IsTailCall, bool Is64Bit,
1756 int FPDiff, DebugLoc dl) {
1757 // Adjust the Return address stack slot.
1758 EVT VT = getPointerTy();
1759 OutRetAddr = getReturnAddressFrameIndex(DAG);
1761 // Load the "old" Return address.
1762 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1763 return SDValue(OutRetAddr.getNode(), 1);
1766 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1767 /// optimization is performed and it is required (FPDiff!=0).
1769 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1770 SDValue Chain, SDValue RetAddrFrIdx,
1771 bool Is64Bit, int FPDiff, DebugLoc dl) {
1772 // Store the return address to the appropriate stack slot.
1773 if (!FPDiff) return Chain;
1774 // Calculate the new stack slot for the return address.
1775 int SlotSize = Is64Bit ? 8 : 4;
1776 int NewReturnAddrFI =
1777 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1778 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1779 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1780 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1781 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1787 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1788 CallingConv::ID CallConv, bool isVarArg,
1790 const SmallVectorImpl<ISD::OutputArg> &Outs,
1791 const SmallVectorImpl<ISD::InputArg> &Ins,
1792 DebugLoc dl, SelectionDAG &DAG,
1793 SmallVectorImpl<SDValue> &InVals) {
1794 MachineFunction &MF = DAG.getMachineFunction();
1795 bool Is64Bit = Subtarget->is64Bit();
1796 bool IsStructRet = CallIsStructReturn(Outs);
1797 bool IsSibcall = false;
1800 // Check if it's really possible to do a tail call.
1801 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1802 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1805 // Sibcalls are automatically detected tailcalls which do not require
1807 if (!GuaranteedTailCallOpt && isTailCall)
1814 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1815 "Var args not supported with calling convention fastcc or ghc");
1817 // Analyze operands of the call, assigning locations to each operand.
1818 SmallVector<CCValAssign, 16> ArgLocs;
1819 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1820 ArgLocs, *DAG.getContext());
1821 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1823 // Get a count of how many bytes are to be pushed on the stack.
1824 unsigned NumBytes = CCInfo.getNextStackOffset();
1826 // This is a sibcall. The memory operands are available in caller's
1827 // own caller's stack.
1829 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1830 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1833 if (isTailCall && !IsSibcall) {
1834 // Lower arguments at fp - stackoffset + fpdiff.
1835 unsigned NumBytesCallerPushed =
1836 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1837 FPDiff = NumBytesCallerPushed - NumBytes;
1839 // Set the delta of movement of the returnaddr stackslot.
1840 // But only set if delta is greater than previous delta.
1841 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1842 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1846 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1848 SDValue RetAddrFrIdx;
1849 // Load return adress for tail calls.
1850 if (isTailCall && FPDiff)
1851 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1852 Is64Bit, FPDiff, dl);
1854 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1855 SmallVector<SDValue, 8> MemOpChains;
1858 // Walk the register/memloc assignments, inserting copies/loads. In the case
1859 // of tail call optimization arguments are handle later.
1860 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1861 CCValAssign &VA = ArgLocs[i];
1862 EVT RegVT = VA.getLocVT();
1863 SDValue Arg = Outs[i].Val;
1864 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1865 bool isByVal = Flags.isByVal();
1867 // Promote the value if needed.
1868 switch (VA.getLocInfo()) {
1869 default: llvm_unreachable("Unknown loc info!");
1870 case CCValAssign::Full: break;
1871 case CCValAssign::SExt:
1872 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1874 case CCValAssign::ZExt:
1875 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1877 case CCValAssign::AExt:
1878 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1879 // Special case: passing MMX values in XMM registers.
1880 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1881 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1882 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1884 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1886 case CCValAssign::BCvt:
1887 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1889 case CCValAssign::Indirect: {
1890 // Store the argument.
1891 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1892 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1893 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1894 PseudoSourceValue::getFixedStack(FI), 0,
1901 if (VA.isRegLoc()) {
1902 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1903 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1904 assert(VA.isMemLoc());
1905 if (StackPtr.getNode() == 0)
1906 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1907 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1908 dl, DAG, VA, Flags));
1912 if (!MemOpChains.empty())
1913 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1914 &MemOpChains[0], MemOpChains.size());
1916 // Build a sequence of copy-to-reg nodes chained together with token chain
1917 // and flag operands which copy the outgoing args into registers.
1919 // Tail call byval lowering might overwrite argument registers so in case of
1920 // tail call optimization the copies to registers are lowered later.
1922 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1923 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1924 RegsToPass[i].second, InFlag);
1925 InFlag = Chain.getValue(1);
1928 if (Subtarget->isPICStyleGOT()) {
1929 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1932 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1933 DAG.getNode(X86ISD::GlobalBaseReg,
1934 DebugLoc::getUnknownLoc(),
1937 InFlag = Chain.getValue(1);
1939 // If we are tail calling and generating PIC/GOT style code load the
1940 // address of the callee into ECX. The value in ecx is used as target of
1941 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1942 // for tail calls on PIC/GOT architectures. Normally we would just put the
1943 // address of GOT into ebx and then call target@PLT. But for tail calls
1944 // ebx would be restored (since ebx is callee saved) before jumping to the
1947 // Note: The actual moving to ECX is done further down.
1948 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1949 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1950 !G->getGlobal()->hasProtectedVisibility())
1951 Callee = LowerGlobalAddress(Callee, DAG);
1952 else if (isa<ExternalSymbolSDNode>(Callee))
1953 Callee = LowerExternalSymbol(Callee, DAG);
1957 if (Is64Bit && isVarArg) {
1958 // From AMD64 ABI document:
1959 // For calls that may call functions that use varargs or stdargs
1960 // (prototype-less calls or calls to functions containing ellipsis (...) in
1961 // the declaration) %al is used as hidden argument to specify the number
1962 // of SSE registers used. The contents of %al do not need to match exactly
1963 // the number of registers, but must be an ubound on the number of SSE
1964 // registers used and is in the range 0 - 8 inclusive.
1966 // FIXME: Verify this on Win64
1967 // Count the number of XMM registers allocated.
1968 static const unsigned XMMArgRegs[] = {
1969 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1970 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1972 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1973 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1974 && "SSE registers cannot be used when SSE is disabled");
1976 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1977 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1978 InFlag = Chain.getValue(1);
1982 // For tail calls lower the arguments to the 'real' stack slot.
1984 // Force all the incoming stack arguments to be loaded from the stack
1985 // before any new outgoing arguments are stored to the stack, because the
1986 // outgoing stack slots may alias the incoming argument stack slots, and
1987 // the alias isn't otherwise explicit. This is slightly more conservative
1988 // than necessary, because it means that each store effectively depends
1989 // on every argument instead of just those arguments it would clobber.
1990 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1992 SmallVector<SDValue, 8> MemOpChains2;
1995 // Do not flag preceeding copytoreg stuff together with the following stuff.
1997 if (GuaranteedTailCallOpt) {
1998 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1999 CCValAssign &VA = ArgLocs[i];
2002 assert(VA.isMemLoc());
2003 SDValue Arg = Outs[i].Val;
2004 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2005 // Create frame index.
2006 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2007 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2008 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2009 FIN = DAG.getFrameIndex(FI, getPointerTy());
2011 if (Flags.isByVal()) {
2012 // Copy relative to framepointer.
2013 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2014 if (StackPtr.getNode() == 0)
2015 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2017 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2019 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2023 // Store relative to framepointer.
2024 MemOpChains2.push_back(
2025 DAG.getStore(ArgChain, dl, Arg, FIN,
2026 PseudoSourceValue::getFixedStack(FI), 0,
2032 if (!MemOpChains2.empty())
2033 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2034 &MemOpChains2[0], MemOpChains2.size());
2036 // Copy arguments to their registers.
2037 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2038 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2039 RegsToPass[i].second, InFlag);
2040 InFlag = Chain.getValue(1);
2044 // Store the return address to the appropriate stack slot.
2045 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2049 bool WasGlobalOrExternal = false;
2050 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2051 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2052 // In the 64-bit large code model, we have to make all calls
2053 // through a register, since the call instruction's 32-bit
2054 // pc-relative offset may not be large enough to hold the whole
2056 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2057 WasGlobalOrExternal = true;
2058 // If the callee is a GlobalAddress node (quite common, every direct call
2059 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2062 // We should use extra load for direct calls to dllimported functions in
2064 GlobalValue *GV = G->getGlobal();
2065 if (!GV->hasDLLImportLinkage()) {
2066 unsigned char OpFlags = 0;
2068 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2069 // external symbols most go through the PLT in PIC mode. If the symbol
2070 // has hidden or protected visibility, or if it is static or local, then
2071 // we don't need to use the PLT - we can directly call it.
2072 if (Subtarget->isTargetELF() &&
2073 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2074 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2075 OpFlags = X86II::MO_PLT;
2076 } else if (Subtarget->isPICStyleStubAny() &&
2077 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2078 Subtarget->getDarwinVers() < 9) {
2079 // PC-relative references to external symbols should go through $stub,
2080 // unless we're building with the leopard linker or later, which
2081 // automatically synthesizes these stubs.
2082 OpFlags = X86II::MO_DARWIN_STUB;
2085 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2086 G->getOffset(), OpFlags);
2088 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2089 WasGlobalOrExternal = true;
2090 unsigned char OpFlags = 0;
2092 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2093 // symbols should go through the PLT.
2094 if (Subtarget->isTargetELF() &&
2095 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2096 OpFlags = X86II::MO_PLT;
2097 } else if (Subtarget->isPICStyleStubAny() &&
2098 Subtarget->getDarwinVers() < 9) {
2099 // PC-relative references to external symbols should go through $stub,
2100 // unless we're building with the leopard linker or later, which
2101 // automatically synthesizes these stubs.
2102 OpFlags = X86II::MO_DARWIN_STUB;
2105 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2109 // Returns a chain & a flag for retval copy to use.
2110 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2111 SmallVector<SDValue, 8> Ops;
2113 if (!IsSibcall && isTailCall) {
2114 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2115 DAG.getIntPtrConstant(0, true), InFlag);
2116 InFlag = Chain.getValue(1);
2119 Ops.push_back(Chain);
2120 Ops.push_back(Callee);
2123 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2125 // Add argument registers to the end of the list so that they are known live
2127 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2128 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2129 RegsToPass[i].second.getValueType()));
2131 // Add an implicit use GOT pointer in EBX.
2132 if (!isTailCall && Subtarget->isPICStyleGOT())
2133 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2135 // Add an implicit use of AL for x86 vararg functions.
2136 if (Is64Bit && isVarArg)
2137 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2139 if (InFlag.getNode())
2140 Ops.push_back(InFlag);
2143 // If this is the first return lowered for this function, add the regs
2144 // to the liveout set for the function.
2145 if (MF.getRegInfo().liveout_empty()) {
2146 SmallVector<CCValAssign, 16> RVLocs;
2147 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2149 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2150 for (unsigned i = 0; i != RVLocs.size(); ++i)
2151 if (RVLocs[i].isRegLoc())
2152 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2154 return DAG.getNode(X86ISD::TC_RETURN, dl,
2155 NodeTys, &Ops[0], Ops.size());
2158 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2159 InFlag = Chain.getValue(1);
2161 // Create the CALLSEQ_END node.
2162 unsigned NumBytesForCalleeToPush;
2163 if (IsCalleePop(isVarArg, CallConv))
2164 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2165 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2166 // If this is a call to a struct-return function, the callee
2167 // pops the hidden struct pointer, so we have to push it back.
2168 // This is common for Darwin/X86, Linux & Mingw32 targets.
2169 NumBytesForCalleeToPush = 4;
2171 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2173 // Returns a flag for retval copy to use.
2175 Chain = DAG.getCALLSEQ_END(Chain,
2176 DAG.getIntPtrConstant(NumBytes, true),
2177 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2180 InFlag = Chain.getValue(1);
2183 // Handle result values, copying them out of physregs into vregs that we
2185 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2186 Ins, dl, DAG, InVals);
2190 //===----------------------------------------------------------------------===//
2191 // Fast Calling Convention (tail call) implementation
2192 //===----------------------------------------------------------------------===//
2194 // Like std call, callee cleans arguments, convention except that ECX is
2195 // reserved for storing the tail called function address. Only 2 registers are
2196 // free for argument passing (inreg). Tail call optimization is performed
2198 // * tailcallopt is enabled
2199 // * caller/callee are fastcc
2200 // On X86_64 architecture with GOT-style position independent code only local
2201 // (within module) calls are supported at the moment.
2202 // To keep the stack aligned according to platform abi the function
2203 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2204 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2205 // If a tail called function callee has more arguments than the caller the
2206 // caller needs to make sure that there is room to move the RETADDR to. This is
2207 // achieved by reserving an area the size of the argument delta right after the
2208 // original REtADDR, but before the saved framepointer or the spilled registers
2209 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2221 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2222 /// for a 16 byte align requirement.
2223 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2224 SelectionDAG& DAG) {
2225 MachineFunction &MF = DAG.getMachineFunction();
2226 const TargetMachine &TM = MF.getTarget();
2227 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2228 unsigned StackAlignment = TFI.getStackAlignment();
2229 uint64_t AlignMask = StackAlignment - 1;
2230 int64_t Offset = StackSize;
2231 uint64_t SlotSize = TD->getPointerSize();
2232 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2233 // Number smaller than 12 so just add the difference.
2234 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2236 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2237 Offset = ((~AlignMask) & Offset) + StackAlignment +
2238 (StackAlignment-SlotSize);
2243 /// MatchingStackOffset - Return true if the given stack call argument is
2244 /// already available in the same position (relatively) of the caller's
2245 /// incoming argument stack.
2247 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2248 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2249 const X86InstrInfo *TII) {
2250 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2252 if (Arg.getOpcode() == ISD::CopyFromReg) {
2253 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2254 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2256 MachineInstr *Def = MRI->getVRegDef(VR);
2259 if (!Flags.isByVal()) {
2260 if (!TII->isLoadFromStackSlot(Def, FI))
2263 unsigned Opcode = Def->getOpcode();
2264 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2265 Def->getOperand(1).isFI()) {
2266 FI = Def->getOperand(1).getIndex();
2267 Bytes = Flags.getByValSize();
2271 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2272 if (Flags.isByVal())
2273 // ByVal argument is passed in as a pointer but it's now being
2274 // dereferenced. e.g.
2275 // define @foo(%struct.X* %A) {
2276 // tail call @bar(%struct.X* byval %A)
2279 SDValue Ptr = Ld->getBasePtr();
2280 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2283 FI = FINode->getIndex();
2287 assert(FI != INT_MAX);
2288 if (!MFI->isFixedObjectIndex(FI))
2290 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2293 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2294 /// for tail call optimization. Targets which want to do tail call
2295 /// optimization should implement this function.
2297 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2298 CallingConv::ID CalleeCC,
2300 bool isCalleeStructRet,
2301 bool isCallerStructRet,
2302 const SmallVectorImpl<ISD::OutputArg> &Outs,
2303 const SmallVectorImpl<ISD::InputArg> &Ins,
2304 SelectionDAG& DAG) const {
2305 if (!IsTailCallConvention(CalleeCC) &&
2306 CalleeCC != CallingConv::C)
2309 // If -tailcallopt is specified, make fastcc functions tail-callable.
2310 const MachineFunction &MF = DAG.getMachineFunction();
2311 const Function *CallerF = DAG.getMachineFunction().getFunction();
2312 if (GuaranteedTailCallOpt) {
2313 if (IsTailCallConvention(CalleeCC) &&
2314 CallerF->getCallingConv() == CalleeCC)
2319 // Look for obvious safe cases to perform tail call optimization that does not
2320 // requite ABI changes. This is what gcc calls sibcall.
2322 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2323 // emit a special epilogue.
2324 if (RegInfo->needsStackRealignment(MF))
2327 // Do not sibcall optimize vararg calls unless the call site is not passing any
2329 if (isVarArg && !Outs.empty())
2332 // Also avoid sibcall optimization if either caller or callee uses struct
2333 // return semantics.
2334 if (isCalleeStructRet || isCallerStructRet)
2337 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2338 // Therefore if it's not used by the call it is not safe to optimize this into
2340 bool Unused = false;
2341 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2348 SmallVector<CCValAssign, 16> RVLocs;
2349 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2350 RVLocs, *DAG.getContext());
2351 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2352 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2353 CCValAssign &VA = RVLocs[i];
2354 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2359 // If the callee takes no arguments then go on to check the results of the
2361 if (!Outs.empty()) {
2362 // Check if stack adjustment is needed. For now, do not do this if any
2363 // argument is passed on the stack.
2364 SmallVector<CCValAssign, 16> ArgLocs;
2365 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2366 ArgLocs, *DAG.getContext());
2367 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2368 if (CCInfo.getNextStackOffset()) {
2369 MachineFunction &MF = DAG.getMachineFunction();
2370 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2372 if (Subtarget->isTargetWin64())
2373 // Win64 ABI has additional complications.
2376 // Check if the arguments are already laid out in the right way as
2377 // the caller's fixed stack objects.
2378 MachineFrameInfo *MFI = MF.getFrameInfo();
2379 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2380 const X86InstrInfo *TII =
2381 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2382 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2383 CCValAssign &VA = ArgLocs[i];
2384 EVT RegVT = VA.getLocVT();
2385 SDValue Arg = Outs[i].Val;
2386 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2387 if (VA.getLocInfo() == CCValAssign::Indirect)
2389 if (!VA.isRegLoc()) {
2390 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2402 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2404 DenseMap<const Value *, unsigned> &vm,
2405 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2406 DenseMap<const AllocaInst *, int> &am
2408 , SmallSet<Instruction*, 8> &cil
2411 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2419 //===----------------------------------------------------------------------===//
2420 // Other Lowering Hooks
2421 //===----------------------------------------------------------------------===//
2424 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2425 MachineFunction &MF = DAG.getMachineFunction();
2426 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2427 int ReturnAddrIndex = FuncInfo->getRAIndex();
2429 if (ReturnAddrIndex == 0) {
2430 // Set up a frame object for the return address.
2431 uint64_t SlotSize = TD->getPointerSize();
2432 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2434 FuncInfo->setRAIndex(ReturnAddrIndex);
2437 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2441 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2442 bool hasSymbolicDisplacement) {
2443 // Offset should fit into 32 bit immediate field.
2444 if (!isInt<32>(Offset))
2447 // If we don't have a symbolic displacement - we don't have any extra
2449 if (!hasSymbolicDisplacement)
2452 // FIXME: Some tweaks might be needed for medium code model.
2453 if (M != CodeModel::Small && M != CodeModel::Kernel)
2456 // For small code model we assume that latest object is 16MB before end of 31
2457 // bits boundary. We may also accept pretty large negative constants knowing
2458 // that all objects are in the positive half of address space.
2459 if (M == CodeModel::Small && Offset < 16*1024*1024)
2462 // For kernel code model we know that all object resist in the negative half
2463 // of 32bits address space. We may not accept negative offsets, since they may
2464 // be just off and we may accept pretty large positive ones.
2465 if (M == CodeModel::Kernel && Offset > 0)
2471 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2472 /// specific condition code, returning the condition code and the LHS/RHS of the
2473 /// comparison to make.
2474 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2475 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2477 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2478 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2479 // X > -1 -> X == 0, jump !sign.
2480 RHS = DAG.getConstant(0, RHS.getValueType());
2481 return X86::COND_NS;
2482 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2483 // X < 0 -> X == 0, jump on sign.
2485 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2487 RHS = DAG.getConstant(0, RHS.getValueType());
2488 return X86::COND_LE;
2492 switch (SetCCOpcode) {
2493 default: llvm_unreachable("Invalid integer condition!");
2494 case ISD::SETEQ: return X86::COND_E;
2495 case ISD::SETGT: return X86::COND_G;
2496 case ISD::SETGE: return X86::COND_GE;
2497 case ISD::SETLT: return X86::COND_L;
2498 case ISD::SETLE: return X86::COND_LE;
2499 case ISD::SETNE: return X86::COND_NE;
2500 case ISD::SETULT: return X86::COND_B;
2501 case ISD::SETUGT: return X86::COND_A;
2502 case ISD::SETULE: return X86::COND_BE;
2503 case ISD::SETUGE: return X86::COND_AE;
2507 // First determine if it is required or is profitable to flip the operands.
2509 // If LHS is a foldable load, but RHS is not, flip the condition.
2510 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2511 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2512 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2513 std::swap(LHS, RHS);
2516 switch (SetCCOpcode) {
2522 std::swap(LHS, RHS);
2526 // On a floating point condition, the flags are set as follows:
2528 // 0 | 0 | 0 | X > Y
2529 // 0 | 0 | 1 | X < Y
2530 // 1 | 0 | 0 | X == Y
2531 // 1 | 1 | 1 | unordered
2532 switch (SetCCOpcode) {
2533 default: llvm_unreachable("Condcode should be pre-legalized away");
2535 case ISD::SETEQ: return X86::COND_E;
2536 case ISD::SETOLT: // flipped
2538 case ISD::SETGT: return X86::COND_A;
2539 case ISD::SETOLE: // flipped
2541 case ISD::SETGE: return X86::COND_AE;
2542 case ISD::SETUGT: // flipped
2544 case ISD::SETLT: return X86::COND_B;
2545 case ISD::SETUGE: // flipped
2547 case ISD::SETLE: return X86::COND_BE;
2549 case ISD::SETNE: return X86::COND_NE;
2550 case ISD::SETUO: return X86::COND_P;
2551 case ISD::SETO: return X86::COND_NP;
2553 case ISD::SETUNE: return X86::COND_INVALID;
2557 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2558 /// code. Current x86 isa includes the following FP cmov instructions:
2559 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2560 static bool hasFPCMov(unsigned X86CC) {
2576 /// isFPImmLegal - Returns true if the target can instruction select the
2577 /// specified FP immediate natively. If false, the legalizer will
2578 /// materialize the FP immediate as a load from a constant pool.
2579 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2580 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2581 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2587 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2588 /// the specified range (L, H].
2589 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2590 return (Val < 0) || (Val >= Low && Val < Hi);
2593 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2594 /// specified value.
2595 static bool isUndefOrEqual(int Val, int CmpVal) {
2596 if (Val < 0 || Val == CmpVal)
2601 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2602 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2603 /// the second operand.
2604 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2605 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2606 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2607 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2608 return (Mask[0] < 2 && Mask[1] < 2);
2612 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2613 SmallVector<int, 8> M;
2615 return ::isPSHUFDMask(M, N->getValueType(0));
2618 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2619 /// is suitable for input to PSHUFHW.
2620 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2621 if (VT != MVT::v8i16)
2624 // Lower quadword copied in order or undef.
2625 for (int i = 0; i != 4; ++i)
2626 if (Mask[i] >= 0 && Mask[i] != i)
2629 // Upper quadword shuffled.
2630 for (int i = 4; i != 8; ++i)
2631 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2637 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2638 SmallVector<int, 8> M;
2640 return ::isPSHUFHWMask(M, N->getValueType(0));
2643 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2644 /// is suitable for input to PSHUFLW.
2645 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2646 if (VT != MVT::v8i16)
2649 // Upper quadword copied in order.
2650 for (int i = 4; i != 8; ++i)
2651 if (Mask[i] >= 0 && Mask[i] != i)
2654 // Lower quadword shuffled.
2655 for (int i = 0; i != 4; ++i)
2662 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2663 SmallVector<int, 8> M;
2665 return ::isPSHUFLWMask(M, N->getValueType(0));
2668 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2669 /// is suitable for input to PALIGNR.
2670 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2672 int i, e = VT.getVectorNumElements();
2674 // Do not handle v2i64 / v2f64 shuffles with palignr.
2675 if (e < 4 || !hasSSSE3)
2678 for (i = 0; i != e; ++i)
2682 // All undef, not a palignr.
2686 // Determine if it's ok to perform a palignr with only the LHS, since we
2687 // don't have access to the actual shuffle elements to see if RHS is undef.
2688 bool Unary = Mask[i] < (int)e;
2689 bool NeedsUnary = false;
2691 int s = Mask[i] - i;
2693 // Check the rest of the elements to see if they are consecutive.
2694 for (++i; i != e; ++i) {
2699 Unary = Unary && (m < (int)e);
2700 NeedsUnary = NeedsUnary || (m < s);
2702 if (NeedsUnary && !Unary)
2704 if (Unary && m != ((s+i) & (e-1)))
2706 if (!Unary && m != (s+i))
2712 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2713 SmallVector<int, 8> M;
2715 return ::isPALIGNRMask(M, N->getValueType(0), true);
2718 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2719 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2720 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2721 int NumElems = VT.getVectorNumElements();
2722 if (NumElems != 2 && NumElems != 4)
2725 int Half = NumElems / 2;
2726 for (int i = 0; i < Half; ++i)
2727 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2729 for (int i = Half; i < NumElems; ++i)
2730 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2736 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2737 SmallVector<int, 8> M;
2739 return ::isSHUFPMask(M, N->getValueType(0));
2742 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2743 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2744 /// half elements to come from vector 1 (which would equal the dest.) and
2745 /// the upper half to come from vector 2.
2746 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2747 int NumElems = VT.getVectorNumElements();
2749 if (NumElems != 2 && NumElems != 4)
2752 int Half = NumElems / 2;
2753 for (int i = 0; i < Half; ++i)
2754 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2756 for (int i = Half; i < NumElems; ++i)
2757 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2762 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2763 SmallVector<int, 8> M;
2765 return isCommutedSHUFPMask(M, N->getValueType(0));
2768 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2769 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2770 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2771 if (N->getValueType(0).getVectorNumElements() != 4)
2774 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2775 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2776 isUndefOrEqual(N->getMaskElt(1), 7) &&
2777 isUndefOrEqual(N->getMaskElt(2), 2) &&
2778 isUndefOrEqual(N->getMaskElt(3), 3);
2781 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2782 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2784 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2785 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2790 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2791 isUndefOrEqual(N->getMaskElt(1), 3) &&
2792 isUndefOrEqual(N->getMaskElt(2), 2) &&
2793 isUndefOrEqual(N->getMaskElt(3), 3);
2796 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2797 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2798 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2799 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2801 if (NumElems != 2 && NumElems != 4)
2804 for (unsigned i = 0; i < NumElems/2; ++i)
2805 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2808 for (unsigned i = NumElems/2; i < NumElems; ++i)
2809 if (!isUndefOrEqual(N->getMaskElt(i), i))
2815 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2816 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2817 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2818 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2820 if (NumElems != 2 && NumElems != 4)
2823 for (unsigned i = 0; i < NumElems/2; ++i)
2824 if (!isUndefOrEqual(N->getMaskElt(i), i))
2827 for (unsigned i = 0; i < NumElems/2; ++i)
2828 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2834 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2835 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2836 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2837 bool V2IsSplat = false) {
2838 int NumElts = VT.getVectorNumElements();
2839 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2842 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2844 int BitI1 = Mask[i+1];
2845 if (!isUndefOrEqual(BitI, j))
2848 if (!isUndefOrEqual(BitI1, NumElts))
2851 if (!isUndefOrEqual(BitI1, j + NumElts))
2858 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2859 SmallVector<int, 8> M;
2861 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2864 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2865 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2866 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2867 bool V2IsSplat = false) {
2868 int NumElts = VT.getVectorNumElements();
2869 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2872 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2874 int BitI1 = Mask[i+1];
2875 if (!isUndefOrEqual(BitI, j + NumElts/2))
2878 if (isUndefOrEqual(BitI1, NumElts))
2881 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2888 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2889 SmallVector<int, 8> M;
2891 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2894 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2895 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2897 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2898 int NumElems = VT.getVectorNumElements();
2899 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2902 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2904 int BitI1 = Mask[i+1];
2905 if (!isUndefOrEqual(BitI, j))
2907 if (!isUndefOrEqual(BitI1, j))
2913 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2914 SmallVector<int, 8> M;
2916 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2919 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2920 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2922 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2923 int NumElems = VT.getVectorNumElements();
2924 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2927 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2929 int BitI1 = Mask[i+1];
2930 if (!isUndefOrEqual(BitI, j))
2932 if (!isUndefOrEqual(BitI1, j))
2938 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2939 SmallVector<int, 8> M;
2941 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2944 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2945 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2946 /// MOVSD, and MOVD, i.e. setting the lowest element.
2947 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2948 if (VT.getVectorElementType().getSizeInBits() < 32)
2951 int NumElts = VT.getVectorNumElements();
2953 if (!isUndefOrEqual(Mask[0], NumElts))
2956 for (int i = 1; i < NumElts; ++i)
2957 if (!isUndefOrEqual(Mask[i], i))
2963 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2964 SmallVector<int, 8> M;
2966 return ::isMOVLMask(M, N->getValueType(0));
2969 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2970 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2971 /// element of vector 2 and the other elements to come from vector 1 in order.
2972 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2973 bool V2IsSplat = false, bool V2IsUndef = false) {
2974 int NumOps = VT.getVectorNumElements();
2975 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2978 if (!isUndefOrEqual(Mask[0], 0))
2981 for (int i = 1; i < NumOps; ++i)
2982 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2983 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2984 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2990 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2991 bool V2IsUndef = false) {
2992 SmallVector<int, 8> M;
2994 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2997 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2998 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2999 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3000 if (N->getValueType(0).getVectorNumElements() != 4)
3003 // Expect 1, 1, 3, 3
3004 for (unsigned i = 0; i < 2; ++i) {
3005 int Elt = N->getMaskElt(i);
3006 if (Elt >= 0 && Elt != 1)
3011 for (unsigned i = 2; i < 4; ++i) {
3012 int Elt = N->getMaskElt(i);
3013 if (Elt >= 0 && Elt != 3)
3018 // Don't use movshdup if it can be done with a shufps.
3019 // FIXME: verify that matching u, u, 3, 3 is what we want.
3023 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3024 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3025 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3026 if (N->getValueType(0).getVectorNumElements() != 4)
3029 // Expect 0, 0, 2, 2
3030 for (unsigned i = 0; i < 2; ++i)
3031 if (N->getMaskElt(i) > 0)
3035 for (unsigned i = 2; i < 4; ++i) {
3036 int Elt = N->getMaskElt(i);
3037 if (Elt >= 0 && Elt != 2)
3042 // Don't use movsldup if it can be done with a shufps.
3046 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3047 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3048 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3049 int e = N->getValueType(0).getVectorNumElements() / 2;
3051 for (int i = 0; i < e; ++i)
3052 if (!isUndefOrEqual(N->getMaskElt(i), i))
3054 for (int i = 0; i < e; ++i)
3055 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3060 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3061 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3062 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3063 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3064 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3066 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3068 for (int i = 0; i < NumOperands; ++i) {
3069 int Val = SVOp->getMaskElt(NumOperands-i-1);
3070 if (Val < 0) Val = 0;
3071 if (Val >= NumOperands) Val -= NumOperands;
3073 if (i != NumOperands - 1)
3079 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3080 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3081 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3082 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3084 // 8 nodes, but we only care about the last 4.
3085 for (unsigned i = 7; i >= 4; --i) {
3086 int Val = SVOp->getMaskElt(i);
3095 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3096 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3097 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3098 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3100 // 8 nodes, but we only care about the first 4.
3101 for (int i = 3; i >= 0; --i) {
3102 int Val = SVOp->getMaskElt(i);
3111 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3112 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3113 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3114 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3115 EVT VVT = N->getValueType(0);
3116 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3120 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3121 Val = SVOp->getMaskElt(i);
3125 return (Val - i) * EltSize;
3128 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3130 bool X86::isZeroNode(SDValue Elt) {
3131 return ((isa<ConstantSDNode>(Elt) &&
3132 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3133 (isa<ConstantFPSDNode>(Elt) &&
3134 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3137 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3138 /// their permute mask.
3139 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3140 SelectionDAG &DAG) {
3141 EVT VT = SVOp->getValueType(0);
3142 unsigned NumElems = VT.getVectorNumElements();
3143 SmallVector<int, 8> MaskVec;
3145 for (unsigned i = 0; i != NumElems; ++i) {
3146 int idx = SVOp->getMaskElt(i);
3148 MaskVec.push_back(idx);
3149 else if (idx < (int)NumElems)
3150 MaskVec.push_back(idx + NumElems);
3152 MaskVec.push_back(idx - NumElems);
3154 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3155 SVOp->getOperand(0), &MaskVec[0]);
3158 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3159 /// the two vector operands have swapped position.
3160 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3161 unsigned NumElems = VT.getVectorNumElements();
3162 for (unsigned i = 0; i != NumElems; ++i) {
3166 else if (idx < (int)NumElems)
3167 Mask[i] = idx + NumElems;
3169 Mask[i] = idx - NumElems;
3173 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3174 /// match movhlps. The lower half elements should come from upper half of
3175 /// V1 (and in order), and the upper half elements should come from the upper
3176 /// half of V2 (and in order).
3177 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3178 if (Op->getValueType(0).getVectorNumElements() != 4)
3180 for (unsigned i = 0, e = 2; i != e; ++i)
3181 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3183 for (unsigned i = 2; i != 4; ++i)
3184 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3189 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3190 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3192 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3193 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3195 N = N->getOperand(0).getNode();
3196 if (!ISD::isNON_EXTLoad(N))
3199 *LD = cast<LoadSDNode>(N);
3203 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3204 /// match movlp{s|d}. The lower half elements should come from lower half of
3205 /// V1 (and in order), and the upper half elements should come from the upper
3206 /// half of V2 (and in order). And since V1 will become the source of the
3207 /// MOVLP, it must be either a vector load or a scalar load to vector.
3208 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3209 ShuffleVectorSDNode *Op) {
3210 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3212 // Is V2 is a vector load, don't do this transformation. We will try to use
3213 // load folding shufps op.
3214 if (ISD::isNON_EXTLoad(V2))
3217 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3219 if (NumElems != 2 && NumElems != 4)
3221 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3222 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3224 for (unsigned i = NumElems/2; i != NumElems; ++i)
3225 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3230 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3232 static bool isSplatVector(SDNode *N) {
3233 if (N->getOpcode() != ISD::BUILD_VECTOR)
3236 SDValue SplatValue = N->getOperand(0);
3237 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3238 if (N->getOperand(i) != SplatValue)
3243 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3244 /// to an zero vector.
3245 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3246 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3247 SDValue V1 = N->getOperand(0);
3248 SDValue V2 = N->getOperand(1);
3249 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3250 for (unsigned i = 0; i != NumElems; ++i) {
3251 int Idx = N->getMaskElt(i);
3252 if (Idx >= (int)NumElems) {
3253 unsigned Opc = V2.getOpcode();
3254 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3256 if (Opc != ISD::BUILD_VECTOR ||
3257 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3259 } else if (Idx >= 0) {
3260 unsigned Opc = V1.getOpcode();
3261 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3263 if (Opc != ISD::BUILD_VECTOR ||
3264 !X86::isZeroNode(V1.getOperand(Idx)))
3271 /// getZeroVector - Returns a vector of specified type with all zero elements.
3273 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3275 assert(VT.isVector() && "Expected a vector type");
3277 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3278 // type. This ensures they get CSE'd.
3280 if (VT.getSizeInBits() == 64) { // MMX
3281 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3282 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3283 } else if (HasSSE2) { // SSE2
3284 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3285 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3287 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3288 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3290 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3293 /// getOnesVector - Returns a vector of specified type with all bits set.
3295 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3296 assert(VT.isVector() && "Expected a vector type");
3298 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3299 // type. This ensures they get CSE'd.
3300 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3302 if (VT.getSizeInBits() == 64) // MMX
3303 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3305 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3306 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3310 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3311 /// that point to V2 points to its first element.
3312 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3313 EVT VT = SVOp->getValueType(0);
3314 unsigned NumElems = VT.getVectorNumElements();
3316 bool Changed = false;
3317 SmallVector<int, 8> MaskVec;
3318 SVOp->getMask(MaskVec);
3320 for (unsigned i = 0; i != NumElems; ++i) {
3321 if (MaskVec[i] > (int)NumElems) {
3322 MaskVec[i] = NumElems;
3327 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3328 SVOp->getOperand(1), &MaskVec[0]);
3329 return SDValue(SVOp, 0);
3332 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3333 /// operation of specified width.
3334 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3336 unsigned NumElems = VT.getVectorNumElements();
3337 SmallVector<int, 8> Mask;
3338 Mask.push_back(NumElems);
3339 for (unsigned i = 1; i != NumElems; ++i)
3341 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3344 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3345 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3347 unsigned NumElems = VT.getVectorNumElements();
3348 SmallVector<int, 8> Mask;
3349 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3351 Mask.push_back(i + NumElems);
3353 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3356 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3357 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3359 unsigned NumElems = VT.getVectorNumElements();
3360 unsigned Half = NumElems/2;
3361 SmallVector<int, 8> Mask;
3362 for (unsigned i = 0; i != Half; ++i) {
3363 Mask.push_back(i + Half);
3364 Mask.push_back(i + NumElems + Half);
3366 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3369 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3370 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3372 if (SV->getValueType(0).getVectorNumElements() <= 4)
3373 return SDValue(SV, 0);
3375 EVT PVT = MVT::v4f32;
3376 EVT VT = SV->getValueType(0);
3377 DebugLoc dl = SV->getDebugLoc();
3378 SDValue V1 = SV->getOperand(0);
3379 int NumElems = VT.getVectorNumElements();
3380 int EltNo = SV->getSplatIndex();
3382 // unpack elements to the correct location
3383 while (NumElems > 4) {
3384 if (EltNo < NumElems/2) {
3385 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3387 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3388 EltNo -= NumElems/2;
3393 // Perform the splat.
3394 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3395 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3396 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3397 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3400 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3401 /// vector of zero or undef vector. This produces a shuffle where the low
3402 /// element of V2 is swizzled into the zero/undef vector, landing at element
3403 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3404 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3405 bool isZero, bool HasSSE2,
3406 SelectionDAG &DAG) {
3407 EVT VT = V2.getValueType();
3409 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3410 unsigned NumElems = VT.getVectorNumElements();
3411 SmallVector<int, 16> MaskVec;
3412 for (unsigned i = 0; i != NumElems; ++i)
3413 // If this is the insertion idx, put the low elt of V2 here.
3414 MaskVec.push_back(i == Idx ? NumElems : i);
3415 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3418 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3419 /// a shuffle that is zero.
3421 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3422 bool Low, SelectionDAG &DAG) {
3423 unsigned NumZeros = 0;
3424 for (int i = 0; i < NumElems; ++i) {
3425 unsigned Index = Low ? i : NumElems-i-1;
3426 int Idx = SVOp->getMaskElt(Index);
3431 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3432 if (Elt.getNode() && X86::isZeroNode(Elt))
3440 /// isVectorShift - Returns true if the shuffle can be implemented as a
3441 /// logical left or right shift of a vector.
3442 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3443 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3444 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3445 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3448 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3451 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3455 bool SeenV1 = false;
3456 bool SeenV2 = false;
3457 for (int i = NumZeros; i < NumElems; ++i) {
3458 int Val = isLeft ? (i - NumZeros) : i;
3459 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3471 if (SeenV1 && SeenV2)
3474 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3480 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3482 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3483 unsigned NumNonZero, unsigned NumZero,
3484 SelectionDAG &DAG, TargetLowering &TLI) {
3488 DebugLoc dl = Op.getDebugLoc();
3491 for (unsigned i = 0; i < 16; ++i) {
3492 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3493 if (ThisIsNonZero && First) {
3495 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3497 V = DAG.getUNDEF(MVT::v8i16);
3502 SDValue ThisElt(0, 0), LastElt(0, 0);
3503 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3504 if (LastIsNonZero) {
3505 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3506 MVT::i16, Op.getOperand(i-1));
3508 if (ThisIsNonZero) {
3509 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3510 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3511 ThisElt, DAG.getConstant(8, MVT::i8));
3513 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3517 if (ThisElt.getNode())
3518 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3519 DAG.getIntPtrConstant(i/2));
3523 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3526 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3528 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3529 unsigned NumNonZero, unsigned NumZero,
3530 SelectionDAG &DAG, TargetLowering &TLI) {
3534 DebugLoc dl = Op.getDebugLoc();
3537 for (unsigned i = 0; i < 8; ++i) {
3538 bool isNonZero = (NonZeros & (1 << i)) != 0;
3542 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3544 V = DAG.getUNDEF(MVT::v8i16);
3547 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3548 MVT::v8i16, V, Op.getOperand(i),
3549 DAG.getIntPtrConstant(i));
3556 /// getVShift - Return a vector logical shift node.
3558 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3559 unsigned NumBits, SelectionDAG &DAG,
3560 const TargetLowering &TLI, DebugLoc dl) {
3561 bool isMMX = VT.getSizeInBits() == 64;
3562 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3563 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3564 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3565 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3566 DAG.getNode(Opc, dl, ShVT, SrcOp,
3567 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3571 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3572 SelectionDAG &DAG) {
3574 // Check if the scalar load can be widened into a vector load. And if
3575 // the address is "base + cst" see if the cst can be "absorbed" into
3576 // the shuffle mask.
3577 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3578 SDValue Ptr = LD->getBasePtr();
3579 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3581 EVT PVT = LD->getValueType(0);
3582 if (PVT != MVT::i32 && PVT != MVT::f32)
3587 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3588 FI = FINode->getIndex();
3590 } else if (Ptr.getOpcode() == ISD::ADD &&
3591 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3592 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3593 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3594 Offset = Ptr.getConstantOperandVal(1);
3595 Ptr = Ptr.getOperand(0);
3600 SDValue Chain = LD->getChain();
3601 // Make sure the stack object alignment is at least 16.
3602 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3603 if (DAG.InferPtrAlignment(Ptr) < 16) {
3604 if (MFI->isFixedObjectIndex(FI)) {
3605 // Can't change the alignment. FIXME: It's possible to compute
3606 // the exact stack offset and reference FI + adjust offset instead.
3607 // If someone *really* cares about this. That's the way to implement it.
3610 MFI->setObjectAlignment(FI, 16);
3614 // (Offset % 16) must be multiple of 4. Then address is then
3615 // Ptr + (Offset & ~15).
3618 if ((Offset % 16) & 3)
3620 int64_t StartOffset = Offset & ~15;
3622 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3623 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3625 int EltNo = (Offset - StartOffset) >> 2;
3626 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3627 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3628 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3630 // Canonicalize it to a v4i32 shuffle.
3631 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3632 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3633 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3634 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3640 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3641 /// vector of type 'VT', see if the elements can be replaced by a single large
3642 /// load which has the same value as a build_vector whose operands are 'elts'.
3644 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3646 /// FIXME: we'd also like to handle the case where the last elements are zero
3647 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3648 /// There's even a handy isZeroNode for that purpose.
3649 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3650 DebugLoc &dl, SelectionDAG &DAG) {
3651 EVT EltVT = VT.getVectorElementType();
3652 unsigned NumElems = Elts.size();
3654 LoadSDNode *LDBase = NULL;
3655 unsigned LastLoadedElt = -1U;
3657 // For each element in the initializer, see if we've found a load or an undef.
3658 // If we don't find an initial load element, or later load elements are
3659 // non-consecutive, bail out.
3660 for (unsigned i = 0; i < NumElems; ++i) {
3661 SDValue Elt = Elts[i];
3663 if (!Elt.getNode() ||
3664 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3667 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3669 LDBase = cast<LoadSDNode>(Elt.getNode());
3673 if (Elt.getOpcode() == ISD::UNDEF)
3676 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3677 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3682 // If we have found an entire vector of loads and undefs, then return a large
3683 // load of the entire vector width starting at the base pointer. If we found
3684 // consecutive loads for the low half, generate a vzext_load node.
3685 if (LastLoadedElt == NumElems - 1) {
3686 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3687 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3688 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3689 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3690 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3691 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3692 LDBase->isVolatile(), LDBase->isNonTemporal(),
3693 LDBase->getAlignment());
3694 } else if (NumElems == 4 && LastLoadedElt == 1) {
3695 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3696 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3697 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3698 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3704 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3705 DebugLoc dl = Op.getDebugLoc();
3706 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3707 if (ISD::isBuildVectorAllZeros(Op.getNode())
3708 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3709 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3710 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3711 // eliminated on x86-32 hosts.
3712 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3715 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3716 return getOnesVector(Op.getValueType(), DAG, dl);
3717 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3720 EVT VT = Op.getValueType();
3721 EVT ExtVT = VT.getVectorElementType();
3722 unsigned EVTBits = ExtVT.getSizeInBits();
3724 unsigned NumElems = Op.getNumOperands();
3725 unsigned NumZero = 0;
3726 unsigned NumNonZero = 0;
3727 unsigned NonZeros = 0;
3728 bool IsAllConstants = true;
3729 SmallSet<SDValue, 8> Values;
3730 for (unsigned i = 0; i < NumElems; ++i) {
3731 SDValue Elt = Op.getOperand(i);
3732 if (Elt.getOpcode() == ISD::UNDEF)
3735 if (Elt.getOpcode() != ISD::Constant &&
3736 Elt.getOpcode() != ISD::ConstantFP)
3737 IsAllConstants = false;
3738 if (X86::isZeroNode(Elt))
3741 NonZeros |= (1 << i);
3746 if (NumNonZero == 0) {
3747 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3748 return DAG.getUNDEF(VT);
3751 // Special case for single non-zero, non-undef, element.
3752 if (NumNonZero == 1) {
3753 unsigned Idx = CountTrailingZeros_32(NonZeros);
3754 SDValue Item = Op.getOperand(Idx);
3756 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3757 // the value are obviously zero, truncate the value to i32 and do the
3758 // insertion that way. Only do this if the value is non-constant or if the
3759 // value is a constant being inserted into element 0. It is cheaper to do
3760 // a constant pool load than it is to do a movd + shuffle.
3761 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3762 (!IsAllConstants || Idx == 0)) {
3763 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3764 // Handle MMX and SSE both.
3765 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3766 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3768 // Truncate the value (which may itself be a constant) to i32, and
3769 // convert it to a vector with movd (S2V+shuffle to zero extend).
3770 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3771 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3772 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3773 Subtarget->hasSSE2(), DAG);
3775 // Now we have our 32-bit value zero extended in the low element of
3776 // a vector. If Idx != 0, swizzle it into place.
3778 SmallVector<int, 4> Mask;
3779 Mask.push_back(Idx);
3780 for (unsigned i = 1; i != VecElts; ++i)
3782 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3783 DAG.getUNDEF(Item.getValueType()),
3786 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3790 // If we have a constant or non-constant insertion into the low element of
3791 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3792 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3793 // depending on what the source datatype is.
3796 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3797 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3798 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3799 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3800 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3801 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3803 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3804 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3805 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3806 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3807 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3808 Subtarget->hasSSE2(), DAG);
3809 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3813 // Is it a vector logical left shift?
3814 if (NumElems == 2 && Idx == 1 &&
3815 X86::isZeroNode(Op.getOperand(0)) &&
3816 !X86::isZeroNode(Op.getOperand(1))) {
3817 unsigned NumBits = VT.getSizeInBits();
3818 return getVShift(true, VT,
3819 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3820 VT, Op.getOperand(1)),
3821 NumBits/2, DAG, *this, dl);
3824 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3827 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3828 // is a non-constant being inserted into an element other than the low one,
3829 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3830 // movd/movss) to move this into the low element, then shuffle it into
3832 if (EVTBits == 32) {
3833 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3835 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3836 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3837 Subtarget->hasSSE2(), DAG);
3838 SmallVector<int, 8> MaskVec;
3839 for (unsigned i = 0; i < NumElems; i++)
3840 MaskVec.push_back(i == Idx ? 0 : 1);
3841 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3845 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3846 if (Values.size() == 1) {
3847 if (EVTBits == 32) {
3848 // Instead of a shuffle like this:
3849 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3850 // Check if it's possible to issue this instead.
3851 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3852 unsigned Idx = CountTrailingZeros_32(NonZeros);
3853 SDValue Item = Op.getOperand(Idx);
3854 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3855 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3860 // A vector full of immediates; various special cases are already
3861 // handled, so this is best done with a single constant-pool load.
3865 // Let legalizer expand 2-wide build_vectors.
3866 if (EVTBits == 64) {
3867 if (NumNonZero == 1) {
3868 // One half is zero or undef.
3869 unsigned Idx = CountTrailingZeros_32(NonZeros);
3870 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3871 Op.getOperand(Idx));
3872 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3873 Subtarget->hasSSE2(), DAG);
3878 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3879 if (EVTBits == 8 && NumElems == 16) {
3880 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3882 if (V.getNode()) return V;
3885 if (EVTBits == 16 && NumElems == 8) {
3886 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3888 if (V.getNode()) return V;
3891 // If element VT is == 32 bits, turn it into a number of shuffles.
3892 SmallVector<SDValue, 8> V;
3894 if (NumElems == 4 && NumZero > 0) {
3895 for (unsigned i = 0; i < 4; ++i) {
3896 bool isZero = !(NonZeros & (1 << i));
3898 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3900 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3903 for (unsigned i = 0; i < 2; ++i) {
3904 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3907 V[i] = V[i*2]; // Must be a zero vector.
3910 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3913 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3916 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3921 SmallVector<int, 8> MaskVec;
3922 bool Reverse = (NonZeros & 0x3) == 2;
3923 for (unsigned i = 0; i < 2; ++i)
3924 MaskVec.push_back(Reverse ? 1-i : i);
3925 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3926 for (unsigned i = 0; i < 2; ++i)
3927 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3928 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3931 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3932 // Check for a build vector of consecutive loads.
3933 for (unsigned i = 0; i < NumElems; ++i)
3934 V[i] = Op.getOperand(i);
3936 // Check for elements which are consecutive loads.
3937 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3941 // For SSE 4.1, use inserts into undef.
3942 if (getSubtarget()->hasSSE41()) {
3943 V[0] = DAG.getUNDEF(VT);
3944 for (unsigned i = 0; i < NumElems; ++i)
3945 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3946 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3947 Op.getOperand(i), DAG.getIntPtrConstant(i));
3951 // Otherwise, expand into a number of unpckl*
3953 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3954 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3955 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3956 for (unsigned i = 0; i < NumElems; ++i)
3957 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3959 while (NumElems != 0) {
3960 for (unsigned i = 0; i < NumElems; ++i)
3961 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3970 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3971 // We support concatenate two MMX registers and place them in a MMX
3972 // register. This is better than doing a stack convert.
3973 DebugLoc dl = Op.getDebugLoc();
3974 EVT ResVT = Op.getValueType();
3975 assert(Op.getNumOperands() == 2);
3976 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3977 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3979 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3980 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3981 InVec = Op.getOperand(1);
3982 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3983 unsigned NumElts = ResVT.getVectorNumElements();
3984 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3985 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3986 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3988 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3989 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3990 Mask[0] = 0; Mask[1] = 2;
3991 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3993 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3996 // v8i16 shuffles - Prefer shuffles in the following order:
3997 // 1. [all] pshuflw, pshufhw, optional move
3998 // 2. [ssse3] 1 x pshufb
3999 // 3. [ssse3] 2 x pshufb + 1 x por
4000 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4002 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4003 SelectionDAG &DAG, X86TargetLowering &TLI) {
4004 SDValue V1 = SVOp->getOperand(0);
4005 SDValue V2 = SVOp->getOperand(1);
4006 DebugLoc dl = SVOp->getDebugLoc();
4007 SmallVector<int, 8> MaskVals;
4009 // Determine if more than 1 of the words in each of the low and high quadwords
4010 // of the result come from the same quadword of one of the two inputs. Undef
4011 // mask values count as coming from any quadword, for better codegen.
4012 SmallVector<unsigned, 4> LoQuad(4);
4013 SmallVector<unsigned, 4> HiQuad(4);
4014 BitVector InputQuads(4);
4015 for (unsigned i = 0; i < 8; ++i) {
4016 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4017 int EltIdx = SVOp->getMaskElt(i);
4018 MaskVals.push_back(EltIdx);
4027 InputQuads.set(EltIdx / 4);
4030 int BestLoQuad = -1;
4031 unsigned MaxQuad = 1;
4032 for (unsigned i = 0; i < 4; ++i) {
4033 if (LoQuad[i] > MaxQuad) {
4035 MaxQuad = LoQuad[i];
4039 int BestHiQuad = -1;
4041 for (unsigned i = 0; i < 4; ++i) {
4042 if (HiQuad[i] > MaxQuad) {
4044 MaxQuad = HiQuad[i];
4048 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4049 // of the two input vectors, shuffle them into one input vector so only a
4050 // single pshufb instruction is necessary. If There are more than 2 input
4051 // quads, disable the next transformation since it does not help SSSE3.
4052 bool V1Used = InputQuads[0] || InputQuads[1];
4053 bool V2Used = InputQuads[2] || InputQuads[3];
4054 if (TLI.getSubtarget()->hasSSSE3()) {
4055 if (InputQuads.count() == 2 && V1Used && V2Used) {
4056 BestLoQuad = InputQuads.find_first();
4057 BestHiQuad = InputQuads.find_next(BestLoQuad);
4059 if (InputQuads.count() > 2) {
4065 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4066 // the shuffle mask. If a quad is scored as -1, that means that it contains
4067 // words from all 4 input quadwords.
4069 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4070 SmallVector<int, 8> MaskV;
4071 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4072 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4073 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4074 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4075 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4076 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4078 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4079 // source words for the shuffle, to aid later transformations.
4080 bool AllWordsInNewV = true;
4081 bool InOrder[2] = { true, true };
4082 for (unsigned i = 0; i != 8; ++i) {
4083 int idx = MaskVals[i];
4085 InOrder[i/4] = false;
4086 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4088 AllWordsInNewV = false;
4092 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4093 if (AllWordsInNewV) {
4094 for (int i = 0; i != 8; ++i) {
4095 int idx = MaskVals[i];
4098 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4099 if ((idx != i) && idx < 4)
4101 if ((idx != i) && idx > 3)
4110 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4111 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4112 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4113 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4114 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4118 // If we have SSSE3, and all words of the result are from 1 input vector,
4119 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4120 // is present, fall back to case 4.
4121 if (TLI.getSubtarget()->hasSSSE3()) {
4122 SmallVector<SDValue,16> pshufbMask;
4124 // If we have elements from both input vectors, set the high bit of the
4125 // shuffle mask element to zero out elements that come from V2 in the V1
4126 // mask, and elements that come from V1 in the V2 mask, so that the two
4127 // results can be OR'd together.
4128 bool TwoInputs = V1Used && V2Used;
4129 for (unsigned i = 0; i != 8; ++i) {
4130 int EltIdx = MaskVals[i] * 2;
4131 if (TwoInputs && (EltIdx >= 16)) {
4132 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4133 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4136 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4137 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4139 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4140 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4141 DAG.getNode(ISD::BUILD_VECTOR, dl,
4142 MVT::v16i8, &pshufbMask[0], 16));
4144 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4146 // Calculate the shuffle mask for the second input, shuffle it, and
4147 // OR it with the first shuffled input.
4149 for (unsigned i = 0; i != 8; ++i) {
4150 int EltIdx = MaskVals[i] * 2;
4152 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4153 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4156 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4157 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4159 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4160 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4161 DAG.getNode(ISD::BUILD_VECTOR, dl,
4162 MVT::v16i8, &pshufbMask[0], 16));
4163 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4164 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4167 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4168 // and update MaskVals with new element order.
4169 BitVector InOrder(8);
4170 if (BestLoQuad >= 0) {
4171 SmallVector<int, 8> MaskV;
4172 for (int i = 0; i != 4; ++i) {
4173 int idx = MaskVals[i];
4175 MaskV.push_back(-1);
4177 } else if ((idx / 4) == BestLoQuad) {
4178 MaskV.push_back(idx & 3);
4181 MaskV.push_back(-1);
4184 for (unsigned i = 4; i != 8; ++i)
4186 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4190 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4191 // and update MaskVals with the new element order.
4192 if (BestHiQuad >= 0) {
4193 SmallVector<int, 8> MaskV;
4194 for (unsigned i = 0; i != 4; ++i)
4196 for (unsigned i = 4; i != 8; ++i) {
4197 int idx = MaskVals[i];
4199 MaskV.push_back(-1);
4201 } else if ((idx / 4) == BestHiQuad) {
4202 MaskV.push_back((idx & 3) + 4);
4205 MaskV.push_back(-1);
4208 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4212 // In case BestHi & BestLo were both -1, which means each quadword has a word
4213 // from each of the four input quadwords, calculate the InOrder bitvector now
4214 // before falling through to the insert/extract cleanup.
4215 if (BestLoQuad == -1 && BestHiQuad == -1) {
4217 for (int i = 0; i != 8; ++i)
4218 if (MaskVals[i] < 0 || MaskVals[i] == i)
4222 // The other elements are put in the right place using pextrw and pinsrw.
4223 for (unsigned i = 0; i != 8; ++i) {
4226 int EltIdx = MaskVals[i];
4229 SDValue ExtOp = (EltIdx < 8)
4230 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4231 DAG.getIntPtrConstant(EltIdx))
4232 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4233 DAG.getIntPtrConstant(EltIdx - 8));
4234 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4235 DAG.getIntPtrConstant(i));
4240 // v16i8 shuffles - Prefer shuffles in the following order:
4241 // 1. [ssse3] 1 x pshufb
4242 // 2. [ssse3] 2 x pshufb + 1 x por
4243 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4245 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4246 SelectionDAG &DAG, X86TargetLowering &TLI) {
4247 SDValue V1 = SVOp->getOperand(0);
4248 SDValue V2 = SVOp->getOperand(1);
4249 DebugLoc dl = SVOp->getDebugLoc();
4250 SmallVector<int, 16> MaskVals;
4251 SVOp->getMask(MaskVals);
4253 // If we have SSSE3, case 1 is generated when all result bytes come from
4254 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4255 // present, fall back to case 3.
4256 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4259 for (unsigned i = 0; i < 16; ++i) {
4260 int EltIdx = MaskVals[i];
4269 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4270 if (TLI.getSubtarget()->hasSSSE3()) {
4271 SmallVector<SDValue,16> pshufbMask;
4273 // If all result elements are from one input vector, then only translate
4274 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4276 // Otherwise, we have elements from both input vectors, and must zero out
4277 // elements that come from V2 in the first mask, and V1 in the second mask
4278 // so that we can OR them together.
4279 bool TwoInputs = !(V1Only || V2Only);
4280 for (unsigned i = 0; i != 16; ++i) {
4281 int EltIdx = MaskVals[i];
4282 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4283 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4286 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4288 // If all the elements are from V2, assign it to V1 and return after
4289 // building the first pshufb.
4292 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4293 DAG.getNode(ISD::BUILD_VECTOR, dl,
4294 MVT::v16i8, &pshufbMask[0], 16));
4298 // Calculate the shuffle mask for the second input, shuffle it, and
4299 // OR it with the first shuffled input.
4301 for (unsigned i = 0; i != 16; ++i) {
4302 int EltIdx = MaskVals[i];
4304 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4307 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4309 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4310 DAG.getNode(ISD::BUILD_VECTOR, dl,
4311 MVT::v16i8, &pshufbMask[0], 16));
4312 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4315 // No SSSE3 - Calculate in place words and then fix all out of place words
4316 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4317 // the 16 different words that comprise the two doublequadword input vectors.
4318 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4319 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4320 SDValue NewV = V2Only ? V2 : V1;
4321 for (int i = 0; i != 8; ++i) {
4322 int Elt0 = MaskVals[i*2];
4323 int Elt1 = MaskVals[i*2+1];
4325 // This word of the result is all undef, skip it.
4326 if (Elt0 < 0 && Elt1 < 0)
4329 // This word of the result is already in the correct place, skip it.
4330 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4332 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4335 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4336 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4339 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4340 // using a single extract together, load it and store it.
4341 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4342 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4343 DAG.getIntPtrConstant(Elt1 / 2));
4344 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4345 DAG.getIntPtrConstant(i));
4349 // If Elt1 is defined, extract it from the appropriate source. If the
4350 // source byte is not also odd, shift the extracted word left 8 bits
4351 // otherwise clear the bottom 8 bits if we need to do an or.
4353 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4354 DAG.getIntPtrConstant(Elt1 / 2));
4355 if ((Elt1 & 1) == 0)
4356 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4357 DAG.getConstant(8, TLI.getShiftAmountTy()));
4359 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4360 DAG.getConstant(0xFF00, MVT::i16));
4362 // If Elt0 is defined, extract it from the appropriate source. If the
4363 // source byte is not also even, shift the extracted word right 8 bits. If
4364 // Elt1 was also defined, OR the extracted values together before
4365 // inserting them in the result.
4367 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4368 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4369 if ((Elt0 & 1) != 0)
4370 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4371 DAG.getConstant(8, TLI.getShiftAmountTy()));
4373 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4374 DAG.getConstant(0x00FF, MVT::i16));
4375 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4378 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4379 DAG.getIntPtrConstant(i));
4381 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4384 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4385 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4386 /// done when every pair / quad of shuffle mask elements point to elements in
4387 /// the right sequence. e.g.
4388 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4390 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4392 TargetLowering &TLI, DebugLoc dl) {
4393 EVT VT = SVOp->getValueType(0);
4394 SDValue V1 = SVOp->getOperand(0);
4395 SDValue V2 = SVOp->getOperand(1);
4396 unsigned NumElems = VT.getVectorNumElements();
4397 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4398 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4399 EVT MaskEltVT = MaskVT.getVectorElementType();
4401 switch (VT.getSimpleVT().SimpleTy) {
4402 default: assert(false && "Unexpected!");
4403 case MVT::v4f32: NewVT = MVT::v2f64; break;
4404 case MVT::v4i32: NewVT = MVT::v2i64; break;
4405 case MVT::v8i16: NewVT = MVT::v4i32; break;
4406 case MVT::v16i8: NewVT = MVT::v4i32; break;
4409 if (NewWidth == 2) {
4415 int Scale = NumElems / NewWidth;
4416 SmallVector<int, 8> MaskVec;
4417 for (unsigned i = 0; i < NumElems; i += Scale) {
4419 for (int j = 0; j < Scale; ++j) {
4420 int EltIdx = SVOp->getMaskElt(i+j);
4424 StartIdx = EltIdx - (EltIdx % Scale);
4425 if (EltIdx != StartIdx + j)
4429 MaskVec.push_back(-1);
4431 MaskVec.push_back(StartIdx / Scale);
4434 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4435 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4436 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4439 /// getVZextMovL - Return a zero-extending vector move low node.
4441 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4442 SDValue SrcOp, SelectionDAG &DAG,
4443 const X86Subtarget *Subtarget, DebugLoc dl) {
4444 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4445 LoadSDNode *LD = NULL;
4446 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4447 LD = dyn_cast<LoadSDNode>(SrcOp);
4449 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4451 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4452 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4453 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4454 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4455 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4457 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4458 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4459 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4460 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4468 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4469 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4470 DAG.getNode(ISD::BIT_CONVERT, dl,
4474 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4477 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4478 SDValue V1 = SVOp->getOperand(0);
4479 SDValue V2 = SVOp->getOperand(1);
4480 DebugLoc dl = SVOp->getDebugLoc();
4481 EVT VT = SVOp->getValueType(0);
4483 SmallVector<std::pair<int, int>, 8> Locs;
4485 SmallVector<int, 8> Mask1(4U, -1);
4486 SmallVector<int, 8> PermMask;
4487 SVOp->getMask(PermMask);
4491 for (unsigned i = 0; i != 4; ++i) {
4492 int Idx = PermMask[i];
4494 Locs[i] = std::make_pair(-1, -1);
4496 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4498 Locs[i] = std::make_pair(0, NumLo);
4502 Locs[i] = std::make_pair(1, NumHi);
4504 Mask1[2+NumHi] = Idx;
4510 if (NumLo <= 2 && NumHi <= 2) {
4511 // If no more than two elements come from either vector. This can be
4512 // implemented with two shuffles. First shuffle gather the elements.
4513 // The second shuffle, which takes the first shuffle as both of its
4514 // vector operands, put the elements into the right order.
4515 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4517 SmallVector<int, 8> Mask2(4U, -1);
4519 for (unsigned i = 0; i != 4; ++i) {
4520 if (Locs[i].first == -1)
4523 unsigned Idx = (i < 2) ? 0 : 4;
4524 Idx += Locs[i].first * 2 + Locs[i].second;
4529 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4530 } else if (NumLo == 3 || NumHi == 3) {
4531 // Otherwise, we must have three elements from one vector, call it X, and
4532 // one element from the other, call it Y. First, use a shufps to build an
4533 // intermediate vector with the one element from Y and the element from X
4534 // that will be in the same half in the final destination (the indexes don't
4535 // matter). Then, use a shufps to build the final vector, taking the half
4536 // containing the element from Y from the intermediate, and the other half
4539 // Normalize it so the 3 elements come from V1.
4540 CommuteVectorShuffleMask(PermMask, VT);
4544 // Find the element from V2.
4546 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4547 int Val = PermMask[HiIndex];
4554 Mask1[0] = PermMask[HiIndex];
4556 Mask1[2] = PermMask[HiIndex^1];
4558 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4561 Mask1[0] = PermMask[0];
4562 Mask1[1] = PermMask[1];
4563 Mask1[2] = HiIndex & 1 ? 6 : 4;
4564 Mask1[3] = HiIndex & 1 ? 4 : 6;
4565 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4567 Mask1[0] = HiIndex & 1 ? 2 : 0;
4568 Mask1[1] = HiIndex & 1 ? 0 : 2;
4569 Mask1[2] = PermMask[2];
4570 Mask1[3] = PermMask[3];
4575 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4579 // Break it into (shuffle shuffle_hi, shuffle_lo).
4581 SmallVector<int,8> LoMask(4U, -1);
4582 SmallVector<int,8> HiMask(4U, -1);
4584 SmallVector<int,8> *MaskPtr = &LoMask;
4585 unsigned MaskIdx = 0;
4588 for (unsigned i = 0; i != 4; ++i) {
4595 int Idx = PermMask[i];
4597 Locs[i] = std::make_pair(-1, -1);
4598 } else if (Idx < 4) {
4599 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4600 (*MaskPtr)[LoIdx] = Idx;
4603 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4604 (*MaskPtr)[HiIdx] = Idx;
4609 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4610 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4611 SmallVector<int, 8> MaskOps;
4612 for (unsigned i = 0; i != 4; ++i) {
4613 if (Locs[i].first == -1) {
4614 MaskOps.push_back(-1);
4616 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4617 MaskOps.push_back(Idx);
4620 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4624 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4625 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4626 SDValue V1 = Op.getOperand(0);
4627 SDValue V2 = Op.getOperand(1);
4628 EVT VT = Op.getValueType();
4629 DebugLoc dl = Op.getDebugLoc();
4630 unsigned NumElems = VT.getVectorNumElements();
4631 bool isMMX = VT.getSizeInBits() == 64;
4632 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4633 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4634 bool V1IsSplat = false;
4635 bool V2IsSplat = false;
4637 if (isZeroShuffle(SVOp))
4638 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4640 // Promote splats to v4f32.
4641 if (SVOp->isSplat()) {
4642 if (isMMX || NumElems < 4)
4644 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4647 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4649 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4650 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4651 if (NewOp.getNode())
4652 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4653 LowerVECTOR_SHUFFLE(NewOp, DAG));
4654 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4655 // FIXME: Figure out a cleaner way to do this.
4656 // Try to make use of movq to zero out the top part.
4657 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4658 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4659 if (NewOp.getNode()) {
4660 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4661 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4662 DAG, Subtarget, dl);
4664 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4665 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4666 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4667 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4668 DAG, Subtarget, dl);
4672 if (X86::isPSHUFDMask(SVOp))
4675 // Check if this can be converted into a logical shift.
4676 bool isLeft = false;
4679 bool isShift = getSubtarget()->hasSSE2() &&
4680 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4681 if (isShift && ShVal.hasOneUse()) {
4682 // If the shifted value has multiple uses, it may be cheaper to use
4683 // v_set0 + movlhps or movhlps, etc.
4684 EVT EltVT = VT.getVectorElementType();
4685 ShAmt *= EltVT.getSizeInBits();
4686 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4689 if (X86::isMOVLMask(SVOp)) {
4692 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4693 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4698 // FIXME: fold these into legal mask.
4699 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4700 X86::isMOVSLDUPMask(SVOp) ||
4701 X86::isMOVHLPSMask(SVOp) ||
4702 X86::isMOVLHPSMask(SVOp) ||
4703 X86::isMOVLPMask(SVOp)))
4706 if (ShouldXformToMOVHLPS(SVOp) ||
4707 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4708 return CommuteVectorShuffle(SVOp, DAG);
4711 // No better options. Use a vshl / vsrl.
4712 EVT EltVT = VT.getVectorElementType();
4713 ShAmt *= EltVT.getSizeInBits();
4714 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4717 bool Commuted = false;
4718 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4719 // 1,1,1,1 -> v8i16 though.
4720 V1IsSplat = isSplatVector(V1.getNode());
4721 V2IsSplat = isSplatVector(V2.getNode());
4723 // Canonicalize the splat or undef, if present, to be on the RHS.
4724 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4725 Op = CommuteVectorShuffle(SVOp, DAG);
4726 SVOp = cast<ShuffleVectorSDNode>(Op);
4727 V1 = SVOp->getOperand(0);
4728 V2 = SVOp->getOperand(1);
4729 std::swap(V1IsSplat, V2IsSplat);
4730 std::swap(V1IsUndef, V2IsUndef);
4734 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4735 // Shuffling low element of v1 into undef, just return v1.
4738 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4739 // the instruction selector will not match, so get a canonical MOVL with
4740 // swapped operands to undo the commute.
4741 return getMOVL(DAG, dl, VT, V2, V1);
4744 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4745 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4746 X86::isUNPCKLMask(SVOp) ||
4747 X86::isUNPCKHMask(SVOp))
4751 // Normalize mask so all entries that point to V2 points to its first
4752 // element then try to match unpck{h|l} again. If match, return a
4753 // new vector_shuffle with the corrected mask.
4754 SDValue NewMask = NormalizeMask(SVOp, DAG);
4755 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4756 if (NSVOp != SVOp) {
4757 if (X86::isUNPCKLMask(NSVOp, true)) {
4759 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4766 // Commute is back and try unpck* again.
4767 // FIXME: this seems wrong.
4768 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4769 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4770 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4771 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4772 X86::isUNPCKLMask(NewSVOp) ||
4773 X86::isUNPCKHMask(NewSVOp))
4777 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4779 // Normalize the node to match x86 shuffle ops if needed
4780 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4781 return CommuteVectorShuffle(SVOp, DAG);
4783 // Check for legal shuffle and return?
4784 SmallVector<int, 16> PermMask;
4785 SVOp->getMask(PermMask);
4786 if (isShuffleMaskLegal(PermMask, VT))
4789 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4790 if (VT == MVT::v8i16) {
4791 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4792 if (NewOp.getNode())
4796 if (VT == MVT::v16i8) {
4797 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4798 if (NewOp.getNode())
4802 // Handle all 4 wide cases with a number of shuffles except for MMX.
4803 if (NumElems == 4 && !isMMX)
4804 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4810 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4811 SelectionDAG &DAG) {
4812 EVT VT = Op.getValueType();
4813 DebugLoc dl = Op.getDebugLoc();
4814 if (VT.getSizeInBits() == 8) {
4815 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4816 Op.getOperand(0), Op.getOperand(1));
4817 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4818 DAG.getValueType(VT));
4819 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4820 } else if (VT.getSizeInBits() == 16) {
4821 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4822 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4824 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4825 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4826 DAG.getNode(ISD::BIT_CONVERT, dl,
4830 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4831 Op.getOperand(0), Op.getOperand(1));
4832 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4833 DAG.getValueType(VT));
4834 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4835 } else if (VT == MVT::f32) {
4836 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4837 // the result back to FR32 register. It's only worth matching if the
4838 // result has a single use which is a store or a bitcast to i32. And in
4839 // the case of a store, it's not worth it if the index is a constant 0,
4840 // because a MOVSSmr can be used instead, which is smaller and faster.
4841 if (!Op.hasOneUse())
4843 SDNode *User = *Op.getNode()->use_begin();
4844 if ((User->getOpcode() != ISD::STORE ||
4845 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4846 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4847 (User->getOpcode() != ISD::BIT_CONVERT ||
4848 User->getValueType(0) != MVT::i32))
4850 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4851 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4854 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4855 } else if (VT == MVT::i32) {
4856 // ExtractPS works with constant index.
4857 if (isa<ConstantSDNode>(Op.getOperand(1)))
4865 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4866 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4869 if (Subtarget->hasSSE41()) {
4870 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4875 EVT VT = Op.getValueType();
4876 DebugLoc dl = Op.getDebugLoc();
4877 // TODO: handle v16i8.
4878 if (VT.getSizeInBits() == 16) {
4879 SDValue Vec = Op.getOperand(0);
4880 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4882 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4883 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4884 DAG.getNode(ISD::BIT_CONVERT, dl,
4887 // Transform it so it match pextrw which produces a 32-bit result.
4888 EVT EltVT = MVT::i32;
4889 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4890 Op.getOperand(0), Op.getOperand(1));
4891 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4892 DAG.getValueType(VT));
4893 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4894 } else if (VT.getSizeInBits() == 32) {
4895 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4899 // SHUFPS the element to the lowest double word, then movss.
4900 int Mask[4] = { Idx, -1, -1, -1 };
4901 EVT VVT = Op.getOperand(0).getValueType();
4902 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4903 DAG.getUNDEF(VVT), Mask);
4904 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4905 DAG.getIntPtrConstant(0));
4906 } else if (VT.getSizeInBits() == 64) {
4907 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4908 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4909 // to match extract_elt for f64.
4910 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4914 // UNPCKHPD the element to the lowest double word, then movsd.
4915 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4916 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4917 int Mask[2] = { 1, -1 };
4918 EVT VVT = Op.getOperand(0).getValueType();
4919 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4920 DAG.getUNDEF(VVT), Mask);
4921 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4922 DAG.getIntPtrConstant(0));
4929 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4930 EVT VT = Op.getValueType();
4931 EVT EltVT = VT.getVectorElementType();
4932 DebugLoc dl = Op.getDebugLoc();
4934 SDValue N0 = Op.getOperand(0);
4935 SDValue N1 = Op.getOperand(1);
4936 SDValue N2 = Op.getOperand(2);
4938 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4939 isa<ConstantSDNode>(N2)) {
4941 if (VT == MVT::v8i16)
4942 Opc = X86ISD::PINSRW;
4943 else if (VT == MVT::v4i16)
4944 Opc = X86ISD::MMX_PINSRW;
4945 else if (VT == MVT::v16i8)
4946 Opc = X86ISD::PINSRB;
4948 Opc = X86ISD::PINSRB;
4950 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4952 if (N1.getValueType() != MVT::i32)
4953 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4954 if (N2.getValueType() != MVT::i32)
4955 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4956 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4957 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4958 // Bits [7:6] of the constant are the source select. This will always be
4959 // zero here. The DAG Combiner may combine an extract_elt index into these
4960 // bits. For example (insert (extract, 3), 2) could be matched by putting
4961 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4962 // Bits [5:4] of the constant are the destination select. This is the
4963 // value of the incoming immediate.
4964 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4965 // combine either bitwise AND or insert of float 0.0 to set these bits.
4966 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4967 // Create this as a scalar to vector..
4968 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4969 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4970 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4971 // PINSR* works with constant index.
4978 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4979 EVT VT = Op.getValueType();
4980 EVT EltVT = VT.getVectorElementType();
4982 if (Subtarget->hasSSE41())
4983 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4985 if (EltVT == MVT::i8)
4988 DebugLoc dl = Op.getDebugLoc();
4989 SDValue N0 = Op.getOperand(0);
4990 SDValue N1 = Op.getOperand(1);
4991 SDValue N2 = Op.getOperand(2);
4993 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4994 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4995 // as its second argument.
4996 if (N1.getValueType() != MVT::i32)
4997 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4998 if (N2.getValueType() != MVT::i32)
4999 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5000 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5001 dl, VT, N0, N1, N2);
5007 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
5008 DebugLoc dl = Op.getDebugLoc();
5009 if (Op.getValueType() == MVT::v2f32)
5010 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5011 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5012 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5013 Op.getOperand(0))));
5015 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5016 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5018 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5019 EVT VT = MVT::v2i32;
5020 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5027 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5028 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5031 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5032 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5033 // one of the above mentioned nodes. It has to be wrapped because otherwise
5034 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5035 // be used to form addressing mode. These wrapped nodes will be selected
5038 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
5039 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5041 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5043 unsigned char OpFlag = 0;
5044 unsigned WrapperKind = X86ISD::Wrapper;
5045 CodeModel::Model M = getTargetMachine().getCodeModel();
5047 if (Subtarget->isPICStyleRIPRel() &&
5048 (M == CodeModel::Small || M == CodeModel::Kernel))
5049 WrapperKind = X86ISD::WrapperRIP;
5050 else if (Subtarget->isPICStyleGOT())
5051 OpFlag = X86II::MO_GOTOFF;
5052 else if (Subtarget->isPICStyleStubPIC())
5053 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5055 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5057 CP->getOffset(), OpFlag);
5058 DebugLoc DL = CP->getDebugLoc();
5059 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5060 // With PIC, the address is actually $g + Offset.
5062 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5063 DAG.getNode(X86ISD::GlobalBaseReg,
5064 DebugLoc::getUnknownLoc(), getPointerTy()),
5071 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
5072 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5074 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5076 unsigned char OpFlag = 0;
5077 unsigned WrapperKind = X86ISD::Wrapper;
5078 CodeModel::Model M = getTargetMachine().getCodeModel();
5080 if (Subtarget->isPICStyleRIPRel() &&
5081 (M == CodeModel::Small || M == CodeModel::Kernel))
5082 WrapperKind = X86ISD::WrapperRIP;
5083 else if (Subtarget->isPICStyleGOT())
5084 OpFlag = X86II::MO_GOTOFF;
5085 else if (Subtarget->isPICStyleStubPIC())
5086 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5088 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5090 DebugLoc DL = JT->getDebugLoc();
5091 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5093 // With PIC, the address is actually $g + Offset.
5095 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5096 DAG.getNode(X86ISD::GlobalBaseReg,
5097 DebugLoc::getUnknownLoc(), getPointerTy()),
5105 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5106 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5108 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5110 unsigned char OpFlag = 0;
5111 unsigned WrapperKind = X86ISD::Wrapper;
5112 CodeModel::Model M = getTargetMachine().getCodeModel();
5114 if (Subtarget->isPICStyleRIPRel() &&
5115 (M == CodeModel::Small || M == CodeModel::Kernel))
5116 WrapperKind = X86ISD::WrapperRIP;
5117 else if (Subtarget->isPICStyleGOT())
5118 OpFlag = X86II::MO_GOTOFF;
5119 else if (Subtarget->isPICStyleStubPIC())
5120 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5122 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5124 DebugLoc DL = Op.getDebugLoc();
5125 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5128 // With PIC, the address is actually $g + Offset.
5129 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5130 !Subtarget->is64Bit()) {
5131 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5132 DAG.getNode(X86ISD::GlobalBaseReg,
5133 DebugLoc::getUnknownLoc(),
5142 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5143 // Create the TargetBlockAddressAddress node.
5144 unsigned char OpFlags =
5145 Subtarget->ClassifyBlockAddressReference();
5146 CodeModel::Model M = getTargetMachine().getCodeModel();
5147 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5148 DebugLoc dl = Op.getDebugLoc();
5149 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5150 /*isTarget=*/true, OpFlags);
5152 if (Subtarget->isPICStyleRIPRel() &&
5153 (M == CodeModel::Small || M == CodeModel::Kernel))
5154 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5156 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5158 // With PIC, the address is actually $g + Offset.
5159 if (isGlobalRelativeToPICBase(OpFlags)) {
5160 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5161 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5169 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5171 SelectionDAG &DAG) const {
5172 // Create the TargetGlobalAddress node, folding in the constant
5173 // offset if it is legal.
5174 unsigned char OpFlags =
5175 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5176 CodeModel::Model M = getTargetMachine().getCodeModel();
5178 if (OpFlags == X86II::MO_NO_FLAG &&
5179 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5180 // A direct static reference to a global.
5181 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5184 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5187 if (Subtarget->isPICStyleRIPRel() &&
5188 (M == CodeModel::Small || M == CodeModel::Kernel))
5189 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5191 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5193 // With PIC, the address is actually $g + Offset.
5194 if (isGlobalRelativeToPICBase(OpFlags)) {
5195 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5196 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5200 // For globals that require a load from a stub to get the address, emit the
5202 if (isGlobalStubReference(OpFlags))
5203 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5204 PseudoSourceValue::getGOT(), 0, false, false, 0);
5206 // If there was a non-zero offset that we didn't fold, create an explicit
5209 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5210 DAG.getConstant(Offset, getPointerTy()));
5216 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5217 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5218 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5219 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5223 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5224 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5225 unsigned char OperandFlags) {
5226 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5227 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5228 DebugLoc dl = GA->getDebugLoc();
5229 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5230 GA->getValueType(0),
5234 SDValue Ops[] = { Chain, TGA, *InFlag };
5235 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5237 SDValue Ops[] = { Chain, TGA };
5238 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5241 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5242 MFI->setHasCalls(true);
5244 SDValue Flag = Chain.getValue(1);
5245 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5248 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5250 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5253 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5254 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5255 DAG.getNode(X86ISD::GlobalBaseReg,
5256 DebugLoc::getUnknownLoc(),
5258 InFlag = Chain.getValue(1);
5260 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5263 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5265 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5267 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5268 X86::RAX, X86II::MO_TLSGD);
5271 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5272 // "local exec" model.
5273 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5274 const EVT PtrVT, TLSModel::Model model,
5276 DebugLoc dl = GA->getDebugLoc();
5277 // Get the Thread Pointer
5278 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5279 DebugLoc::getUnknownLoc(), PtrVT,
5280 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5283 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5284 NULL, 0, false, false, 0);
5286 unsigned char OperandFlags = 0;
5287 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5289 unsigned WrapperKind = X86ISD::Wrapper;
5290 if (model == TLSModel::LocalExec) {
5291 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5292 } else if (is64Bit) {
5293 assert(model == TLSModel::InitialExec);
5294 OperandFlags = X86II::MO_GOTTPOFF;
5295 WrapperKind = X86ISD::WrapperRIP;
5297 assert(model == TLSModel::InitialExec);
5298 OperandFlags = X86II::MO_INDNTPOFF;
5301 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5303 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5304 GA->getOffset(), OperandFlags);
5305 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5307 if (model == TLSModel::InitialExec)
5308 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5309 PseudoSourceValue::getGOT(), 0, false, false, 0);
5311 // The address of the thread local variable is the add of the thread
5312 // pointer with the offset of the variable.
5313 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5317 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5318 // TODO: implement the "local dynamic" model
5319 // TODO: implement the "initial exec"model for pic executables
5320 assert(Subtarget->isTargetELF() &&
5321 "TLS not implemented for non-ELF targets");
5322 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5323 const GlobalValue *GV = GA->getGlobal();
5325 // If GV is an alias then use the aliasee for determining
5326 // thread-localness.
5327 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5328 GV = GA->resolveAliasedGlobal(false);
5330 TLSModel::Model model = getTLSModel(GV,
5331 getTargetMachine().getRelocationModel());
5334 case TLSModel::GeneralDynamic:
5335 case TLSModel::LocalDynamic: // not implemented
5336 if (Subtarget->is64Bit())
5337 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5338 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5340 case TLSModel::InitialExec:
5341 case TLSModel::LocalExec:
5342 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5343 Subtarget->is64Bit());
5346 llvm_unreachable("Unreachable");
5351 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5352 /// take a 2 x i32 value to shift plus a shift amount.
5353 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5354 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5355 EVT VT = Op.getValueType();
5356 unsigned VTBits = VT.getSizeInBits();
5357 DebugLoc dl = Op.getDebugLoc();
5358 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5359 SDValue ShOpLo = Op.getOperand(0);
5360 SDValue ShOpHi = Op.getOperand(1);
5361 SDValue ShAmt = Op.getOperand(2);
5362 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5363 DAG.getConstant(VTBits - 1, MVT::i8))
5364 : DAG.getConstant(0, VT);
5367 if (Op.getOpcode() == ISD::SHL_PARTS) {
5368 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5369 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5371 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5372 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5375 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5376 DAG.getConstant(VTBits, MVT::i8));
5377 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5378 AndNode, DAG.getConstant(0, MVT::i8));
5381 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5382 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5383 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5385 if (Op.getOpcode() == ISD::SHL_PARTS) {
5386 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5387 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5389 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5390 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5393 SDValue Ops[2] = { Lo, Hi };
5394 return DAG.getMergeValues(Ops, 2, dl);
5397 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5398 EVT SrcVT = Op.getOperand(0).getValueType();
5400 if (SrcVT.isVector()) {
5401 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5407 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5408 "Unknown SINT_TO_FP to lower!");
5410 // These are really Legal; return the operand so the caller accepts it as
5412 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5414 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5415 Subtarget->is64Bit()) {
5419 DebugLoc dl = Op.getDebugLoc();
5420 unsigned Size = SrcVT.getSizeInBits()/8;
5421 MachineFunction &MF = DAG.getMachineFunction();
5422 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5423 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5424 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5426 PseudoSourceValue::getFixedStack(SSFI), 0,
5428 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5431 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5433 SelectionDAG &DAG) {
5435 DebugLoc dl = Op.getDebugLoc();
5437 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5439 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5441 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5442 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5443 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5444 Tys, Ops, array_lengthof(Ops));
5447 Chain = Result.getValue(1);
5448 SDValue InFlag = Result.getValue(2);
5450 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5451 // shouldn't be necessary except that RFP cannot be live across
5452 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5453 MachineFunction &MF = DAG.getMachineFunction();
5454 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5455 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5456 Tys = DAG.getVTList(MVT::Other);
5458 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5460 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5461 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5462 PseudoSourceValue::getFixedStack(SSFI), 0,
5469 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5470 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5471 // This algorithm is not obvious. Here it is in C code, more or less:
5473 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5474 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5475 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5477 // Copy ints to xmm registers.
5478 __m128i xh = _mm_cvtsi32_si128( hi );
5479 __m128i xl = _mm_cvtsi32_si128( lo );
5481 // Combine into low half of a single xmm register.
5482 __m128i x = _mm_unpacklo_epi32( xh, xl );
5486 // Merge in appropriate exponents to give the integer bits the right
5488 x = _mm_unpacklo_epi32( x, exp );
5490 // Subtract away the biases to deal with the IEEE-754 double precision
5492 d = _mm_sub_pd( (__m128d) x, bias );
5494 // All conversions up to here are exact. The correctly rounded result is
5495 // calculated using the current rounding mode using the following
5497 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5498 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5499 // store doesn't really need to be here (except
5500 // maybe to zero the other double)
5505 DebugLoc dl = Op.getDebugLoc();
5506 LLVMContext *Context = DAG.getContext();
5508 // Build some magic constants.
5509 std::vector<Constant*> CV0;
5510 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5511 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5512 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5513 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5514 Constant *C0 = ConstantVector::get(CV0);
5515 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5517 std::vector<Constant*> CV1;
5519 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5521 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5522 Constant *C1 = ConstantVector::get(CV1);
5523 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5525 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5526 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5528 DAG.getIntPtrConstant(1)));
5529 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5530 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5532 DAG.getIntPtrConstant(0)));
5533 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5534 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5535 PseudoSourceValue::getConstantPool(), 0,
5537 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5538 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5539 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5540 PseudoSourceValue::getConstantPool(), 0,
5542 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5544 // Add the halves; easiest way is to swap them into another reg first.
5545 int ShufMask[2] = { 1, -1 };
5546 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5547 DAG.getUNDEF(MVT::v2f64), ShufMask);
5548 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5549 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5550 DAG.getIntPtrConstant(0));
5553 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5554 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5555 DebugLoc dl = Op.getDebugLoc();
5556 // FP constant to bias correct the final result.
5557 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5560 // Load the 32-bit value into an XMM register.
5561 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5562 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5564 DAG.getIntPtrConstant(0)));
5566 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5567 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5568 DAG.getIntPtrConstant(0));
5570 // Or the load with the bias.
5571 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5572 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5573 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5575 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5576 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5577 MVT::v2f64, Bias)));
5578 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5579 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5580 DAG.getIntPtrConstant(0));
5582 // Subtract the bias.
5583 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5585 // Handle final rounding.
5586 EVT DestVT = Op.getValueType();
5588 if (DestVT.bitsLT(MVT::f64)) {
5589 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5590 DAG.getIntPtrConstant(0));
5591 } else if (DestVT.bitsGT(MVT::f64)) {
5592 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5595 // Handle final rounding.
5599 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5600 SDValue N0 = Op.getOperand(0);
5601 DebugLoc dl = Op.getDebugLoc();
5603 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5604 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5605 // the optimization here.
5606 if (DAG.SignBitIsZero(N0))
5607 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5609 EVT SrcVT = N0.getValueType();
5610 if (SrcVT == MVT::i64) {
5611 // We only handle SSE2 f64 target here; caller can expand the rest.
5612 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5615 return LowerUINT_TO_FP_i64(Op, DAG);
5616 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5617 return LowerUINT_TO_FP_i32(Op, DAG);
5620 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5622 // Make a 64-bit buffer, and use it to build an FILD.
5623 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5624 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5625 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5626 getPointerTy(), StackSlot, WordOff);
5627 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5628 StackSlot, NULL, 0, false, false, 0);
5629 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5630 OffsetSlot, NULL, 0, false, false, 0);
5631 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5634 std::pair<SDValue,SDValue> X86TargetLowering::
5635 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5636 DebugLoc dl = Op.getDebugLoc();
5638 EVT DstTy = Op.getValueType();
5641 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5645 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5646 DstTy.getSimpleVT() >= MVT::i16 &&
5647 "Unknown FP_TO_SINT to lower!");
5649 // These are really Legal.
5650 if (DstTy == MVT::i32 &&
5651 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5652 return std::make_pair(SDValue(), SDValue());
5653 if (Subtarget->is64Bit() &&
5654 DstTy == MVT::i64 &&
5655 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5656 return std::make_pair(SDValue(), SDValue());
5658 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5660 MachineFunction &MF = DAG.getMachineFunction();
5661 unsigned MemSize = DstTy.getSizeInBits()/8;
5662 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5663 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5666 switch (DstTy.getSimpleVT().SimpleTy) {
5667 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5668 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5669 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5670 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5673 SDValue Chain = DAG.getEntryNode();
5674 SDValue Value = Op.getOperand(0);
5675 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5676 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5677 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5678 PseudoSourceValue::getFixedStack(SSFI), 0,
5680 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5682 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5684 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5685 Chain = Value.getValue(1);
5686 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5687 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5690 // Build the FP_TO_INT*_IN_MEM
5691 SDValue Ops[] = { Chain, Value, StackSlot };
5692 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5694 return std::make_pair(FIST, StackSlot);
5697 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5698 if (Op.getValueType().isVector()) {
5699 if (Op.getValueType() == MVT::v2i32 &&
5700 Op.getOperand(0).getValueType() == MVT::v2f64) {
5706 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5707 SDValue FIST = Vals.first, StackSlot = Vals.second;
5708 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5709 if (FIST.getNode() == 0) return Op;
5712 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5713 FIST, StackSlot, NULL, 0, false, false, 0);
5716 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5717 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5718 SDValue FIST = Vals.first, StackSlot = Vals.second;
5719 assert(FIST.getNode() && "Unexpected failure");
5722 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5723 FIST, StackSlot, NULL, 0, false, false, 0);
5726 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5727 LLVMContext *Context = DAG.getContext();
5728 DebugLoc dl = Op.getDebugLoc();
5729 EVT VT = Op.getValueType();
5732 EltVT = VT.getVectorElementType();
5733 std::vector<Constant*> CV;
5734 if (EltVT == MVT::f64) {
5735 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5739 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5745 Constant *C = ConstantVector::get(CV);
5746 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5747 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5748 PseudoSourceValue::getConstantPool(), 0,
5750 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5753 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5754 LLVMContext *Context = DAG.getContext();
5755 DebugLoc dl = Op.getDebugLoc();
5756 EVT VT = Op.getValueType();
5759 EltVT = VT.getVectorElementType();
5760 std::vector<Constant*> CV;
5761 if (EltVT == MVT::f64) {
5762 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5766 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5772 Constant *C = ConstantVector::get(CV);
5773 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5774 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5775 PseudoSourceValue::getConstantPool(), 0,
5777 if (VT.isVector()) {
5778 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5779 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5780 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5782 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5784 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5788 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5789 LLVMContext *Context = DAG.getContext();
5790 SDValue Op0 = Op.getOperand(0);
5791 SDValue Op1 = Op.getOperand(1);
5792 DebugLoc dl = Op.getDebugLoc();
5793 EVT VT = Op.getValueType();
5794 EVT SrcVT = Op1.getValueType();
5796 // If second operand is smaller, extend it first.
5797 if (SrcVT.bitsLT(VT)) {
5798 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5801 // And if it is bigger, shrink it first.
5802 if (SrcVT.bitsGT(VT)) {
5803 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5807 // At this point the operands and the result should have the same
5808 // type, and that won't be f80 since that is not custom lowered.
5810 // First get the sign bit of second operand.
5811 std::vector<Constant*> CV;
5812 if (SrcVT == MVT::f64) {
5813 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5814 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5816 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5817 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5818 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5819 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5821 Constant *C = ConstantVector::get(CV);
5822 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5823 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5824 PseudoSourceValue::getConstantPool(), 0,
5826 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5828 // Shift sign bit right or left if the two operands have different types.
5829 if (SrcVT.bitsGT(VT)) {
5830 // Op0 is MVT::f32, Op1 is MVT::f64.
5831 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5832 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5833 DAG.getConstant(32, MVT::i32));
5834 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5835 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5836 DAG.getIntPtrConstant(0));
5839 // Clear first operand sign bit.
5841 if (VT == MVT::f64) {
5842 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5843 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5845 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5846 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5847 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5848 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5850 C = ConstantVector::get(CV);
5851 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5852 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5853 PseudoSourceValue::getConstantPool(), 0,
5855 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5857 // Or the value with the sign bit.
5858 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5861 /// Emit nodes that will be selected as "test Op0,Op0", or something
5863 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5864 SelectionDAG &DAG) {
5865 DebugLoc dl = Op.getDebugLoc();
5867 // CF and OF aren't always set the way we want. Determine which
5868 // of these we need.
5869 bool NeedCF = false;
5870 bool NeedOF = false;
5872 case X86::COND_A: case X86::COND_AE:
5873 case X86::COND_B: case X86::COND_BE:
5876 case X86::COND_G: case X86::COND_GE:
5877 case X86::COND_L: case X86::COND_LE:
5878 case X86::COND_O: case X86::COND_NO:
5884 // See if we can use the EFLAGS value from the operand instead of
5885 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5886 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5887 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5888 unsigned Opcode = 0;
5889 unsigned NumOperands = 0;
5890 switch (Op.getNode()->getOpcode()) {
5892 // Due to an isel shortcoming, be conservative if this add is likely to
5893 // be selected as part of a load-modify-store instruction. When the root
5894 // node in a match is a store, isel doesn't know how to remap non-chain
5895 // non-flag uses of other nodes in the match, such as the ADD in this
5896 // case. This leads to the ADD being left around and reselected, with
5897 // the result being two adds in the output.
5898 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5899 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5900 if (UI->getOpcode() == ISD::STORE)
5902 if (ConstantSDNode *C =
5903 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5904 // An add of one will be selected as an INC.
5905 if (C->getAPIntValue() == 1) {
5906 Opcode = X86ISD::INC;
5910 // An add of negative one (subtract of one) will be selected as a DEC.
5911 if (C->getAPIntValue().isAllOnesValue()) {
5912 Opcode = X86ISD::DEC;
5917 // Otherwise use a regular EFLAGS-setting add.
5918 Opcode = X86ISD::ADD;
5922 // If the primary and result isn't used, don't bother using X86ISD::AND,
5923 // because a TEST instruction will be better.
5924 bool NonFlagUse = false;
5925 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5926 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5928 unsigned UOpNo = UI.getOperandNo();
5929 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5930 // Look pass truncate.
5931 UOpNo = User->use_begin().getOperandNo();
5932 User = *User->use_begin();
5934 if (User->getOpcode() != ISD::BRCOND &&
5935 User->getOpcode() != ISD::SETCC &&
5936 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5948 // Due to the ISEL shortcoming noted above, be conservative if this op is
5949 // likely to be selected as part of a load-modify-store instruction.
5950 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5951 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5952 if (UI->getOpcode() == ISD::STORE)
5954 // Otherwise use a regular EFLAGS-setting instruction.
5955 switch (Op.getNode()->getOpcode()) {
5956 case ISD::SUB: Opcode = X86ISD::SUB; break;
5957 case ISD::OR: Opcode = X86ISD::OR; break;
5958 case ISD::XOR: Opcode = X86ISD::XOR; break;
5959 case ISD::AND: Opcode = X86ISD::AND; break;
5960 default: llvm_unreachable("unexpected operator!");
5971 return SDValue(Op.getNode(), 1);
5977 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5978 SmallVector<SDValue, 4> Ops;
5979 for (unsigned i = 0; i != NumOperands; ++i)
5980 Ops.push_back(Op.getOperand(i));
5981 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5982 DAG.ReplaceAllUsesWith(Op, New);
5983 return SDValue(New.getNode(), 1);
5987 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5988 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5989 DAG.getConstant(0, Op.getValueType()));
5992 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5994 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5995 SelectionDAG &DAG) {
5996 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5997 if (C->getAPIntValue() == 0)
5998 return EmitTest(Op0, X86CC, DAG);
6000 DebugLoc dl = Op0.getDebugLoc();
6001 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6004 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6005 /// if it's possible.
6006 static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
6007 DebugLoc dl, SelectionDAG &DAG) {
6008 SDValue Op0 = And.getOperand(0);
6009 SDValue Op1 = And.getOperand(1);
6010 if (Op0.getOpcode() == ISD::TRUNCATE)
6011 Op0 = Op0.getOperand(0);
6012 if (Op1.getOpcode() == ISD::TRUNCATE)
6013 Op1 = Op1.getOperand(0);
6016 if (Op1.getOpcode() == ISD::SHL) {
6017 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6018 if (And10C->getZExtValue() == 1) {
6020 RHS = Op1.getOperand(1);
6022 } else if (Op0.getOpcode() == ISD::SHL) {
6023 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6024 if (And00C->getZExtValue() == 1) {
6026 RHS = Op0.getOperand(1);
6028 } else if (Op1.getOpcode() == ISD::Constant) {
6029 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6030 SDValue AndLHS = Op0;
6031 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6032 LHS = AndLHS.getOperand(0);
6033 RHS = AndLHS.getOperand(1);
6037 if (LHS.getNode()) {
6038 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
6039 // instruction. Since the shift amount is in-range-or-undefined, we know
6040 // that doing a bittest on the i16 value is ok. We extend to i32 because
6041 // the encoding for the i16 version is larger than the i32 version.
6042 if (LHS.getValueType() == MVT::i8)
6043 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6045 // If the operand types disagree, extend the shift amount to match. Since
6046 // BT ignores high bits (like shifts) we can use anyextend.
6047 if (LHS.getValueType() != RHS.getValueType())
6048 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6050 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6051 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6052 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6053 DAG.getConstant(Cond, MVT::i8), BT);
6059 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
6060 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6061 SDValue Op0 = Op.getOperand(0);
6062 SDValue Op1 = Op.getOperand(1);
6063 DebugLoc dl = Op.getDebugLoc();
6064 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6066 // Optimize to BT if possible.
6067 // Lower (X & (1 << N)) == 0 to BT(X, N).
6068 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6069 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6070 if (Op0.getOpcode() == ISD::AND &&
6072 Op1.getOpcode() == ISD::Constant &&
6073 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6074 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6075 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6076 if (NewSetCC.getNode())
6080 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6081 if (Op0.getOpcode() == X86ISD::SETCC &&
6082 Op1.getOpcode() == ISD::Constant &&
6083 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6084 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6085 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6086 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6087 bool Invert = (CC == ISD::SETNE) ^
6088 cast<ConstantSDNode>(Op1)->isNullValue();
6090 CCode = X86::GetOppositeBranchCondition(CCode);
6091 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6092 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6095 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6096 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6097 if (X86CC == X86::COND_INVALID)
6100 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6102 // Use sbb x, x to materialize carry bit into a GPR.
6103 if (X86CC == X86::COND_B)
6104 return DAG.getNode(ISD::AND, dl, MVT::i8,
6105 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6106 DAG.getConstant(X86CC, MVT::i8), Cond),
6107 DAG.getConstant(1, MVT::i8));
6109 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6110 DAG.getConstant(X86CC, MVT::i8), Cond);
6113 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6115 SDValue Op0 = Op.getOperand(0);
6116 SDValue Op1 = Op.getOperand(1);
6117 SDValue CC = Op.getOperand(2);
6118 EVT VT = Op.getValueType();
6119 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6120 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6121 DebugLoc dl = Op.getDebugLoc();
6125 EVT VT0 = Op0.getValueType();
6126 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6127 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6130 switch (SetCCOpcode) {
6133 case ISD::SETEQ: SSECC = 0; break;
6135 case ISD::SETGT: Swap = true; // Fallthrough
6137 case ISD::SETOLT: SSECC = 1; break;
6139 case ISD::SETGE: Swap = true; // Fallthrough
6141 case ISD::SETOLE: SSECC = 2; break;
6142 case ISD::SETUO: SSECC = 3; break;
6144 case ISD::SETNE: SSECC = 4; break;
6145 case ISD::SETULE: Swap = true;
6146 case ISD::SETUGE: SSECC = 5; break;
6147 case ISD::SETULT: Swap = true;
6148 case ISD::SETUGT: SSECC = 6; break;
6149 case ISD::SETO: SSECC = 7; break;
6152 std::swap(Op0, Op1);
6154 // In the two special cases we can't handle, emit two comparisons.
6156 if (SetCCOpcode == ISD::SETUEQ) {
6158 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6159 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6160 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6162 else if (SetCCOpcode == ISD::SETONE) {
6164 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6165 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6166 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6168 llvm_unreachable("Illegal FP comparison");
6170 // Handle all other FP comparisons here.
6171 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6174 // We are handling one of the integer comparisons here. Since SSE only has
6175 // GT and EQ comparisons for integer, swapping operands and multiple
6176 // operations may be required for some comparisons.
6177 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6178 bool Swap = false, Invert = false, FlipSigns = false;
6180 switch (VT.getSimpleVT().SimpleTy) {
6183 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6185 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6187 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6188 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6191 switch (SetCCOpcode) {
6193 case ISD::SETNE: Invert = true;
6194 case ISD::SETEQ: Opc = EQOpc; break;
6195 case ISD::SETLT: Swap = true;
6196 case ISD::SETGT: Opc = GTOpc; break;
6197 case ISD::SETGE: Swap = true;
6198 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6199 case ISD::SETULT: Swap = true;
6200 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6201 case ISD::SETUGE: Swap = true;
6202 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6205 std::swap(Op0, Op1);
6207 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6208 // bits of the inputs before performing those operations.
6210 EVT EltVT = VT.getVectorElementType();
6211 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6213 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6214 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6216 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6217 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6220 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6222 // If the logical-not of the result is required, perform that now.
6224 Result = DAG.getNOT(dl, Result, VT);
6229 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6230 static bool isX86LogicalCmp(SDValue Op) {
6231 unsigned Opc = Op.getNode()->getOpcode();
6232 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6234 if (Op.getResNo() == 1 &&
6235 (Opc == X86ISD::ADD ||
6236 Opc == X86ISD::SUB ||
6237 Opc == X86ISD::SMUL ||
6238 Opc == X86ISD::UMUL ||
6239 Opc == X86ISD::INC ||
6240 Opc == X86ISD::DEC ||
6241 Opc == X86ISD::OR ||
6242 Opc == X86ISD::XOR ||
6243 Opc == X86ISD::AND))
6249 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6250 bool addTest = true;
6251 SDValue Cond = Op.getOperand(0);
6252 DebugLoc dl = Op.getDebugLoc();
6255 if (Cond.getOpcode() == ISD::SETCC) {
6256 SDValue NewCond = LowerSETCC(Cond, DAG);
6257 if (NewCond.getNode())
6261 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6262 SDValue Op1 = Op.getOperand(1);
6263 SDValue Op2 = Op.getOperand(2);
6264 if (Cond.getOpcode() == X86ISD::SETCC &&
6265 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6266 SDValue Cmp = Cond.getOperand(1);
6267 if (Cmp.getOpcode() == X86ISD::CMP) {
6268 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6269 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6270 ConstantSDNode *RHSC =
6271 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6272 if (N1C && N1C->isAllOnesValue() &&
6273 N2C && N2C->isNullValue() &&
6274 RHSC && RHSC->isNullValue()) {
6275 SDValue CmpOp0 = Cmp.getOperand(0);
6276 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6277 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6278 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6279 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6284 // Look pass (and (setcc_carry (cmp ...)), 1).
6285 if (Cond.getOpcode() == ISD::AND &&
6286 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6287 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6288 if (C && C->getAPIntValue() == 1)
6289 Cond = Cond.getOperand(0);
6292 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6293 // setting operand in place of the X86ISD::SETCC.
6294 if (Cond.getOpcode() == X86ISD::SETCC ||
6295 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6296 CC = Cond.getOperand(0);
6298 SDValue Cmp = Cond.getOperand(1);
6299 unsigned Opc = Cmp.getOpcode();
6300 EVT VT = Op.getValueType();
6302 bool IllegalFPCMov = false;
6303 if (VT.isFloatingPoint() && !VT.isVector() &&
6304 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6305 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6307 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6308 Opc == X86ISD::BT) { // FIXME
6315 // Look pass the truncate.
6316 if (Cond.getOpcode() == ISD::TRUNCATE)
6317 Cond = Cond.getOperand(0);
6319 // We know the result of AND is compared against zero. Try to match
6321 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6322 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6323 if (NewSetCC.getNode()) {
6324 CC = NewSetCC.getOperand(0);
6325 Cond = NewSetCC.getOperand(1);
6332 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6333 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6336 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6337 // condition is true.
6338 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6339 SDValue Ops[] = { Op2, Op1, CC, Cond };
6340 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6343 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6344 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6345 // from the AND / OR.
6346 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6347 Opc = Op.getOpcode();
6348 if (Opc != ISD::OR && Opc != ISD::AND)
6350 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6351 Op.getOperand(0).hasOneUse() &&
6352 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6353 Op.getOperand(1).hasOneUse());
6356 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6357 // 1 and that the SETCC node has a single use.
6358 static bool isXor1OfSetCC(SDValue Op) {
6359 if (Op.getOpcode() != ISD::XOR)
6361 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6362 if (N1C && N1C->getAPIntValue() == 1) {
6363 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6364 Op.getOperand(0).hasOneUse();
6369 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6370 bool addTest = true;
6371 SDValue Chain = Op.getOperand(0);
6372 SDValue Cond = Op.getOperand(1);
6373 SDValue Dest = Op.getOperand(2);
6374 DebugLoc dl = Op.getDebugLoc();
6377 if (Cond.getOpcode() == ISD::SETCC) {
6378 SDValue NewCond = LowerSETCC(Cond, DAG);
6379 if (NewCond.getNode())
6383 // FIXME: LowerXALUO doesn't handle these!!
6384 else if (Cond.getOpcode() == X86ISD::ADD ||
6385 Cond.getOpcode() == X86ISD::SUB ||
6386 Cond.getOpcode() == X86ISD::SMUL ||
6387 Cond.getOpcode() == X86ISD::UMUL)
6388 Cond = LowerXALUO(Cond, DAG);
6391 // Look pass (and (setcc_carry (cmp ...)), 1).
6392 if (Cond.getOpcode() == ISD::AND &&
6393 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6394 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6395 if (C && C->getAPIntValue() == 1)
6396 Cond = Cond.getOperand(0);
6399 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6400 // setting operand in place of the X86ISD::SETCC.
6401 if (Cond.getOpcode() == X86ISD::SETCC ||
6402 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6403 CC = Cond.getOperand(0);
6405 SDValue Cmp = Cond.getOperand(1);
6406 unsigned Opc = Cmp.getOpcode();
6407 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6408 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6412 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6416 // These can only come from an arithmetic instruction with overflow,
6417 // e.g. SADDO, UADDO.
6418 Cond = Cond.getNode()->getOperand(1);
6425 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6426 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6427 if (CondOpc == ISD::OR) {
6428 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6429 // two branches instead of an explicit OR instruction with a
6431 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6432 isX86LogicalCmp(Cmp)) {
6433 CC = Cond.getOperand(0).getOperand(0);
6434 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6435 Chain, Dest, CC, Cmp);
6436 CC = Cond.getOperand(1).getOperand(0);
6440 } else { // ISD::AND
6441 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6442 // two branches instead of an explicit AND instruction with a
6443 // separate test. However, we only do this if this block doesn't
6444 // have a fall-through edge, because this requires an explicit
6445 // jmp when the condition is false.
6446 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6447 isX86LogicalCmp(Cmp) &&
6448 Op.getNode()->hasOneUse()) {
6449 X86::CondCode CCode =
6450 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6451 CCode = X86::GetOppositeBranchCondition(CCode);
6452 CC = DAG.getConstant(CCode, MVT::i8);
6453 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6454 // Look for an unconditional branch following this conditional branch.
6455 // We need this because we need to reverse the successors in order
6456 // to implement FCMP_OEQ.
6457 if (User.getOpcode() == ISD::BR) {
6458 SDValue FalseBB = User.getOperand(1);
6460 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6461 assert(NewBR == User);
6464 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6465 Chain, Dest, CC, Cmp);
6466 X86::CondCode CCode =
6467 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6468 CCode = X86::GetOppositeBranchCondition(CCode);
6469 CC = DAG.getConstant(CCode, MVT::i8);
6475 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6476 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6477 // It should be transformed during dag combiner except when the condition
6478 // is set by a arithmetics with overflow node.
6479 X86::CondCode CCode =
6480 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6481 CCode = X86::GetOppositeBranchCondition(CCode);
6482 CC = DAG.getConstant(CCode, MVT::i8);
6483 Cond = Cond.getOperand(0).getOperand(1);
6489 // Look pass the truncate.
6490 if (Cond.getOpcode() == ISD::TRUNCATE)
6491 Cond = Cond.getOperand(0);
6493 // We know the result of AND is compared against zero. Try to match
6495 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6496 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6497 if (NewSetCC.getNode()) {
6498 CC = NewSetCC.getOperand(0);
6499 Cond = NewSetCC.getOperand(1);
6506 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6507 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6509 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6510 Chain, Dest, CC, Cond);
6514 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6515 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6516 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6517 // that the guard pages used by the OS virtual memory manager are allocated in
6518 // correct sequence.
6520 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6521 SelectionDAG &DAG) {
6522 assert(Subtarget->isTargetCygMing() &&
6523 "This should be used only on Cygwin/Mingw targets");
6524 DebugLoc dl = Op.getDebugLoc();
6527 SDValue Chain = Op.getOperand(0);
6528 SDValue Size = Op.getOperand(1);
6529 // FIXME: Ensure alignment here
6533 EVT IntPtr = getPointerTy();
6534 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6536 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6537 Flag = Chain.getValue(1);
6539 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6541 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6542 Flag = Chain.getValue(1);
6544 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6546 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6547 return DAG.getMergeValues(Ops1, 2, dl);
6551 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6553 SDValue Dst, SDValue Src,
6554 SDValue Size, unsigned Align,
6556 uint64_t DstSVOff) {
6557 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6559 // If not DWORD aligned or size is more than the threshold, call the library.
6560 // The libc version is likely to be faster for these cases. It can use the
6561 // address value and run time information about the CPU.
6562 if ((Align & 3) != 0 ||
6564 ConstantSize->getZExtValue() >
6565 getSubtarget()->getMaxInlineSizeThreshold()) {
6566 SDValue InFlag(0, 0);
6568 // Check to see if there is a specialized entry-point for memory zeroing.
6569 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6571 if (const char *bzeroEntry = V &&
6572 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6573 EVT IntPtr = getPointerTy();
6574 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6575 TargetLowering::ArgListTy Args;
6576 TargetLowering::ArgListEntry Entry;
6578 Entry.Ty = IntPtrTy;
6579 Args.push_back(Entry);
6581 Args.push_back(Entry);
6582 std::pair<SDValue,SDValue> CallResult =
6583 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6584 false, false, false, false,
6585 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6586 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6587 return CallResult.second;
6590 // Otherwise have the target-independent code call memset.
6594 uint64_t SizeVal = ConstantSize->getZExtValue();
6595 SDValue InFlag(0, 0);
6598 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6599 unsigned BytesLeft = 0;
6600 bool TwoRepStos = false;
6603 uint64_t Val = ValC->getZExtValue() & 255;
6605 // If the value is a constant, then we can potentially use larger sets.
6606 switch (Align & 3) {
6607 case 2: // WORD aligned
6610 Val = (Val << 8) | Val;
6612 case 0: // DWORD aligned
6615 Val = (Val << 8) | Val;
6616 Val = (Val << 16) | Val;
6617 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6620 Val = (Val << 32) | Val;
6623 default: // Byte aligned
6626 Count = DAG.getIntPtrConstant(SizeVal);
6630 if (AVT.bitsGT(MVT::i8)) {
6631 unsigned UBytes = AVT.getSizeInBits() / 8;
6632 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6633 BytesLeft = SizeVal % UBytes;
6636 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6638 InFlag = Chain.getValue(1);
6641 Count = DAG.getIntPtrConstant(SizeVal);
6642 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6643 InFlag = Chain.getValue(1);
6646 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6649 InFlag = Chain.getValue(1);
6650 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6653 InFlag = Chain.getValue(1);
6655 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6656 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6657 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6660 InFlag = Chain.getValue(1);
6662 EVT CVT = Count.getValueType();
6663 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6664 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6665 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6668 InFlag = Chain.getValue(1);
6669 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6670 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6671 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6672 } else if (BytesLeft) {
6673 // Handle the last 1 - 7 bytes.
6674 unsigned Offset = SizeVal - BytesLeft;
6675 EVT AddrVT = Dst.getValueType();
6676 EVT SizeVT = Size.getValueType();
6678 Chain = DAG.getMemset(Chain, dl,
6679 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6680 DAG.getConstant(Offset, AddrVT)),
6682 DAG.getConstant(BytesLeft, SizeVT),
6683 Align, DstSV, DstSVOff + Offset);
6686 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6691 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6692 SDValue Chain, SDValue Dst, SDValue Src,
6693 SDValue Size, unsigned Align,
6695 const Value *DstSV, uint64_t DstSVOff,
6696 const Value *SrcSV, uint64_t SrcSVOff) {
6697 // This requires the copy size to be a constant, preferrably
6698 // within a subtarget-specific limit.
6699 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6702 uint64_t SizeVal = ConstantSize->getZExtValue();
6703 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6706 /// If not DWORD aligned, call the library.
6707 if ((Align & 3) != 0)
6712 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6715 unsigned UBytes = AVT.getSizeInBits() / 8;
6716 unsigned CountVal = SizeVal / UBytes;
6717 SDValue Count = DAG.getIntPtrConstant(CountVal);
6718 unsigned BytesLeft = SizeVal % UBytes;
6720 SDValue InFlag(0, 0);
6721 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6724 InFlag = Chain.getValue(1);
6725 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6728 InFlag = Chain.getValue(1);
6729 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6732 InFlag = Chain.getValue(1);
6734 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6735 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6736 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6737 array_lengthof(Ops));
6739 SmallVector<SDValue, 4> Results;
6740 Results.push_back(RepMovs);
6742 // Handle the last 1 - 7 bytes.
6743 unsigned Offset = SizeVal - BytesLeft;
6744 EVT DstVT = Dst.getValueType();
6745 EVT SrcVT = Src.getValueType();
6746 EVT SizeVT = Size.getValueType();
6747 Results.push_back(DAG.getMemcpy(Chain, dl,
6748 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6749 DAG.getConstant(Offset, DstVT)),
6750 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6751 DAG.getConstant(Offset, SrcVT)),
6752 DAG.getConstant(BytesLeft, SizeVT),
6753 Align, AlwaysInline,
6754 DstSV, DstSVOff + Offset,
6755 SrcSV, SrcSVOff + Offset));
6758 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6759 &Results[0], Results.size());
6762 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6763 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6764 DebugLoc dl = Op.getDebugLoc();
6766 if (!Subtarget->is64Bit()) {
6767 // vastart just stores the address of the VarArgsFrameIndex slot into the
6768 // memory location argument.
6769 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6770 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6775 // gp_offset (0 - 6 * 8)
6776 // fp_offset (48 - 48 + 8 * 16)
6777 // overflow_arg_area (point to parameters coming in memory).
6779 SmallVector<SDValue, 8> MemOps;
6780 SDValue FIN = Op.getOperand(1);
6782 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6783 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6784 FIN, SV, 0, false, false, 0);
6785 MemOps.push_back(Store);
6788 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6789 FIN, DAG.getIntPtrConstant(4));
6790 Store = DAG.getStore(Op.getOperand(0), dl,
6791 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6792 FIN, SV, 0, false, false, 0);
6793 MemOps.push_back(Store);
6795 // Store ptr to overflow_arg_area
6796 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6797 FIN, DAG.getIntPtrConstant(4));
6798 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6799 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6801 MemOps.push_back(Store);
6803 // Store ptr to reg_save_area.
6804 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6805 FIN, DAG.getIntPtrConstant(8));
6806 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6807 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6809 MemOps.push_back(Store);
6810 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6811 &MemOps[0], MemOps.size());
6814 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6815 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6816 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6817 SDValue Chain = Op.getOperand(0);
6818 SDValue SrcPtr = Op.getOperand(1);
6819 SDValue SrcSV = Op.getOperand(2);
6821 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6825 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6826 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6827 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6828 SDValue Chain = Op.getOperand(0);
6829 SDValue DstPtr = Op.getOperand(1);
6830 SDValue SrcPtr = Op.getOperand(2);
6831 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6832 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6833 DebugLoc dl = Op.getDebugLoc();
6835 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6836 DAG.getIntPtrConstant(24), 8, false,
6837 DstSV, 0, SrcSV, 0);
6841 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6842 DebugLoc dl = Op.getDebugLoc();
6843 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6845 default: return SDValue(); // Don't custom lower most intrinsics.
6846 // Comparison intrinsics.
6847 case Intrinsic::x86_sse_comieq_ss:
6848 case Intrinsic::x86_sse_comilt_ss:
6849 case Intrinsic::x86_sse_comile_ss:
6850 case Intrinsic::x86_sse_comigt_ss:
6851 case Intrinsic::x86_sse_comige_ss:
6852 case Intrinsic::x86_sse_comineq_ss:
6853 case Intrinsic::x86_sse_ucomieq_ss:
6854 case Intrinsic::x86_sse_ucomilt_ss:
6855 case Intrinsic::x86_sse_ucomile_ss:
6856 case Intrinsic::x86_sse_ucomigt_ss:
6857 case Intrinsic::x86_sse_ucomige_ss:
6858 case Intrinsic::x86_sse_ucomineq_ss:
6859 case Intrinsic::x86_sse2_comieq_sd:
6860 case Intrinsic::x86_sse2_comilt_sd:
6861 case Intrinsic::x86_sse2_comile_sd:
6862 case Intrinsic::x86_sse2_comigt_sd:
6863 case Intrinsic::x86_sse2_comige_sd:
6864 case Intrinsic::x86_sse2_comineq_sd:
6865 case Intrinsic::x86_sse2_ucomieq_sd:
6866 case Intrinsic::x86_sse2_ucomilt_sd:
6867 case Intrinsic::x86_sse2_ucomile_sd:
6868 case Intrinsic::x86_sse2_ucomigt_sd:
6869 case Intrinsic::x86_sse2_ucomige_sd:
6870 case Intrinsic::x86_sse2_ucomineq_sd: {
6872 ISD::CondCode CC = ISD::SETCC_INVALID;
6875 case Intrinsic::x86_sse_comieq_ss:
6876 case Intrinsic::x86_sse2_comieq_sd:
6880 case Intrinsic::x86_sse_comilt_ss:
6881 case Intrinsic::x86_sse2_comilt_sd:
6885 case Intrinsic::x86_sse_comile_ss:
6886 case Intrinsic::x86_sse2_comile_sd:
6890 case Intrinsic::x86_sse_comigt_ss:
6891 case Intrinsic::x86_sse2_comigt_sd:
6895 case Intrinsic::x86_sse_comige_ss:
6896 case Intrinsic::x86_sse2_comige_sd:
6900 case Intrinsic::x86_sse_comineq_ss:
6901 case Intrinsic::x86_sse2_comineq_sd:
6905 case Intrinsic::x86_sse_ucomieq_ss:
6906 case Intrinsic::x86_sse2_ucomieq_sd:
6907 Opc = X86ISD::UCOMI;
6910 case Intrinsic::x86_sse_ucomilt_ss:
6911 case Intrinsic::x86_sse2_ucomilt_sd:
6912 Opc = X86ISD::UCOMI;
6915 case Intrinsic::x86_sse_ucomile_ss:
6916 case Intrinsic::x86_sse2_ucomile_sd:
6917 Opc = X86ISD::UCOMI;
6920 case Intrinsic::x86_sse_ucomigt_ss:
6921 case Intrinsic::x86_sse2_ucomigt_sd:
6922 Opc = X86ISD::UCOMI;
6925 case Intrinsic::x86_sse_ucomige_ss:
6926 case Intrinsic::x86_sse2_ucomige_sd:
6927 Opc = X86ISD::UCOMI;
6930 case Intrinsic::x86_sse_ucomineq_ss:
6931 case Intrinsic::x86_sse2_ucomineq_sd:
6932 Opc = X86ISD::UCOMI;
6937 SDValue LHS = Op.getOperand(1);
6938 SDValue RHS = Op.getOperand(2);
6939 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6940 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6941 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6942 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6943 DAG.getConstant(X86CC, MVT::i8), Cond);
6944 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6946 // ptest intrinsics. The intrinsic these come from are designed to return
6947 // an integer value, not just an instruction so lower it to the ptest
6948 // pattern and a setcc for the result.
6949 case Intrinsic::x86_sse41_ptestz:
6950 case Intrinsic::x86_sse41_ptestc:
6951 case Intrinsic::x86_sse41_ptestnzc:{
6954 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6955 case Intrinsic::x86_sse41_ptestz:
6957 X86CC = X86::COND_E;
6959 case Intrinsic::x86_sse41_ptestc:
6961 X86CC = X86::COND_B;
6963 case Intrinsic::x86_sse41_ptestnzc:
6965 X86CC = X86::COND_A;
6969 SDValue LHS = Op.getOperand(1);
6970 SDValue RHS = Op.getOperand(2);
6971 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6972 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6973 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6974 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6977 // Fix vector shift instructions where the last operand is a non-immediate
6979 case Intrinsic::x86_sse2_pslli_w:
6980 case Intrinsic::x86_sse2_pslli_d:
6981 case Intrinsic::x86_sse2_pslli_q:
6982 case Intrinsic::x86_sse2_psrli_w:
6983 case Intrinsic::x86_sse2_psrli_d:
6984 case Intrinsic::x86_sse2_psrli_q:
6985 case Intrinsic::x86_sse2_psrai_w:
6986 case Intrinsic::x86_sse2_psrai_d:
6987 case Intrinsic::x86_mmx_pslli_w:
6988 case Intrinsic::x86_mmx_pslli_d:
6989 case Intrinsic::x86_mmx_pslli_q:
6990 case Intrinsic::x86_mmx_psrli_w:
6991 case Intrinsic::x86_mmx_psrli_d:
6992 case Intrinsic::x86_mmx_psrli_q:
6993 case Intrinsic::x86_mmx_psrai_w:
6994 case Intrinsic::x86_mmx_psrai_d: {
6995 SDValue ShAmt = Op.getOperand(2);
6996 if (isa<ConstantSDNode>(ShAmt))
6999 unsigned NewIntNo = 0;
7000 EVT ShAmtVT = MVT::v4i32;
7002 case Intrinsic::x86_sse2_pslli_w:
7003 NewIntNo = Intrinsic::x86_sse2_psll_w;
7005 case Intrinsic::x86_sse2_pslli_d:
7006 NewIntNo = Intrinsic::x86_sse2_psll_d;
7008 case Intrinsic::x86_sse2_pslli_q:
7009 NewIntNo = Intrinsic::x86_sse2_psll_q;
7011 case Intrinsic::x86_sse2_psrli_w:
7012 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7014 case Intrinsic::x86_sse2_psrli_d:
7015 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7017 case Intrinsic::x86_sse2_psrli_q:
7018 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7020 case Intrinsic::x86_sse2_psrai_w:
7021 NewIntNo = Intrinsic::x86_sse2_psra_w;
7023 case Intrinsic::x86_sse2_psrai_d:
7024 NewIntNo = Intrinsic::x86_sse2_psra_d;
7027 ShAmtVT = MVT::v2i32;
7029 case Intrinsic::x86_mmx_pslli_w:
7030 NewIntNo = Intrinsic::x86_mmx_psll_w;
7032 case Intrinsic::x86_mmx_pslli_d:
7033 NewIntNo = Intrinsic::x86_mmx_psll_d;
7035 case Intrinsic::x86_mmx_pslli_q:
7036 NewIntNo = Intrinsic::x86_mmx_psll_q;
7038 case Intrinsic::x86_mmx_psrli_w:
7039 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7041 case Intrinsic::x86_mmx_psrli_d:
7042 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7044 case Intrinsic::x86_mmx_psrli_q:
7045 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7047 case Intrinsic::x86_mmx_psrai_w:
7048 NewIntNo = Intrinsic::x86_mmx_psra_w;
7050 case Intrinsic::x86_mmx_psrai_d:
7051 NewIntNo = Intrinsic::x86_mmx_psra_d;
7053 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7059 // The vector shift intrinsics with scalars uses 32b shift amounts but
7060 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7064 ShOps[1] = DAG.getConstant(0, MVT::i32);
7065 if (ShAmtVT == MVT::v4i32) {
7066 ShOps[2] = DAG.getUNDEF(MVT::i32);
7067 ShOps[3] = DAG.getUNDEF(MVT::i32);
7068 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7070 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7073 EVT VT = Op.getValueType();
7074 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7075 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7076 DAG.getConstant(NewIntNo, MVT::i32),
7077 Op.getOperand(1), ShAmt);
7082 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7083 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7084 DebugLoc dl = Op.getDebugLoc();
7087 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7089 DAG.getConstant(TD->getPointerSize(),
7090 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7091 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7092 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7094 NULL, 0, false, false, 0);
7097 // Just load the return address.
7098 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7099 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7100 RetAddrFI, NULL, 0, false, false, 0);
7103 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7104 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7105 MFI->setFrameAddressIsTaken(true);
7106 EVT VT = Op.getValueType();
7107 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7108 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7109 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7110 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7112 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7117 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7118 SelectionDAG &DAG) {
7119 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7122 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7124 MachineFunction &MF = DAG.getMachineFunction();
7125 SDValue Chain = Op.getOperand(0);
7126 SDValue Offset = Op.getOperand(1);
7127 SDValue Handler = Op.getOperand(2);
7128 DebugLoc dl = Op.getDebugLoc();
7130 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7132 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7134 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7135 DAG.getIntPtrConstant(-TD->getPointerSize()));
7136 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7137 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7138 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7139 MF.getRegInfo().addLiveOut(StoreAddrReg);
7141 return DAG.getNode(X86ISD::EH_RETURN, dl,
7143 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7146 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7147 SelectionDAG &DAG) {
7148 SDValue Root = Op.getOperand(0);
7149 SDValue Trmp = Op.getOperand(1); // trampoline
7150 SDValue FPtr = Op.getOperand(2); // nested function
7151 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7152 DebugLoc dl = Op.getDebugLoc();
7154 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7156 if (Subtarget->is64Bit()) {
7157 SDValue OutChains[6];
7159 // Large code-model.
7160 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7161 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7163 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7164 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7166 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7168 // Load the pointer to the nested function into R11.
7169 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7170 SDValue Addr = Trmp;
7171 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7172 Addr, TrmpAddr, 0, false, false, 0);
7174 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7175 DAG.getConstant(2, MVT::i64));
7176 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7179 // Load the 'nest' parameter value into R10.
7180 // R10 is specified in X86CallingConv.td
7181 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7182 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7183 DAG.getConstant(10, MVT::i64));
7184 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7185 Addr, TrmpAddr, 10, false, false, 0);
7187 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7188 DAG.getConstant(12, MVT::i64));
7189 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7192 // Jump to the nested function.
7193 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7194 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7195 DAG.getConstant(20, MVT::i64));
7196 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7197 Addr, TrmpAddr, 20, false, false, 0);
7199 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7200 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7201 DAG.getConstant(22, MVT::i64));
7202 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7203 TrmpAddr, 22, false, false, 0);
7206 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7207 return DAG.getMergeValues(Ops, 2, dl);
7209 const Function *Func =
7210 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7211 CallingConv::ID CC = Func->getCallingConv();
7216 llvm_unreachable("Unsupported calling convention");
7217 case CallingConv::C:
7218 case CallingConv::X86_StdCall: {
7219 // Pass 'nest' parameter in ECX.
7220 // Must be kept in sync with X86CallingConv.td
7223 // Check that ECX wasn't needed by an 'inreg' parameter.
7224 const FunctionType *FTy = Func->getFunctionType();
7225 const AttrListPtr &Attrs = Func->getAttributes();
7227 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7228 unsigned InRegCount = 0;
7231 for (FunctionType::param_iterator I = FTy->param_begin(),
7232 E = FTy->param_end(); I != E; ++I, ++Idx)
7233 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7234 // FIXME: should only count parameters that are lowered to integers.
7235 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7237 if (InRegCount > 2) {
7238 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7243 case CallingConv::X86_FastCall:
7244 case CallingConv::Fast:
7245 // Pass 'nest' parameter in EAX.
7246 // Must be kept in sync with X86CallingConv.td
7251 SDValue OutChains[4];
7254 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7255 DAG.getConstant(10, MVT::i32));
7256 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7258 // This is storing the opcode for MOV32ri.
7259 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7260 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7261 OutChains[0] = DAG.getStore(Root, dl,
7262 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7263 Trmp, TrmpAddr, 0, false, false, 0);
7265 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7266 DAG.getConstant(1, MVT::i32));
7267 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7270 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7271 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7272 DAG.getConstant(5, MVT::i32));
7273 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7274 TrmpAddr, 5, false, false, 1);
7276 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7277 DAG.getConstant(6, MVT::i32));
7278 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7282 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7283 return DAG.getMergeValues(Ops, 2, dl);
7287 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7289 The rounding mode is in bits 11:10 of FPSR, and has the following
7296 FLT_ROUNDS, on the other hand, expects the following:
7303 To perform the conversion, we do:
7304 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7307 MachineFunction &MF = DAG.getMachineFunction();
7308 const TargetMachine &TM = MF.getTarget();
7309 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7310 unsigned StackAlignment = TFI.getStackAlignment();
7311 EVT VT = Op.getValueType();
7312 DebugLoc dl = Op.getDebugLoc();
7314 // Save FP Control Word to stack slot
7315 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7316 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7318 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7319 DAG.getEntryNode(), StackSlot);
7321 // Load FP Control Word from stack slot
7322 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7325 // Transform as necessary
7327 DAG.getNode(ISD::SRL, dl, MVT::i16,
7328 DAG.getNode(ISD::AND, dl, MVT::i16,
7329 CWD, DAG.getConstant(0x800, MVT::i16)),
7330 DAG.getConstant(11, MVT::i8));
7332 DAG.getNode(ISD::SRL, dl, MVT::i16,
7333 DAG.getNode(ISD::AND, dl, MVT::i16,
7334 CWD, DAG.getConstant(0x400, MVT::i16)),
7335 DAG.getConstant(9, MVT::i8));
7338 DAG.getNode(ISD::AND, dl, MVT::i16,
7339 DAG.getNode(ISD::ADD, dl, MVT::i16,
7340 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7341 DAG.getConstant(1, MVT::i16)),
7342 DAG.getConstant(3, MVT::i16));
7345 return DAG.getNode((VT.getSizeInBits() < 16 ?
7346 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7349 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7350 EVT VT = Op.getValueType();
7352 unsigned NumBits = VT.getSizeInBits();
7353 DebugLoc dl = Op.getDebugLoc();
7355 Op = Op.getOperand(0);
7356 if (VT == MVT::i8) {
7357 // Zero extend to i32 since there is not an i8 bsr.
7359 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7362 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7363 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7364 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7366 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7369 DAG.getConstant(NumBits+NumBits-1, OpVT),
7370 DAG.getConstant(X86::COND_E, MVT::i8),
7373 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7375 // Finally xor with NumBits-1.
7376 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7379 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7383 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7384 EVT VT = Op.getValueType();
7386 unsigned NumBits = VT.getSizeInBits();
7387 DebugLoc dl = Op.getDebugLoc();
7389 Op = Op.getOperand(0);
7390 if (VT == MVT::i8) {
7392 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7395 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7396 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7397 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7399 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7402 DAG.getConstant(NumBits, OpVT),
7403 DAG.getConstant(X86::COND_E, MVT::i8),
7406 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7409 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7413 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7414 EVT VT = Op.getValueType();
7415 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7416 DebugLoc dl = Op.getDebugLoc();
7418 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7419 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7420 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7421 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7422 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7424 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7425 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7426 // return AloBlo + AloBhi + AhiBlo;
7428 SDValue A = Op.getOperand(0);
7429 SDValue B = Op.getOperand(1);
7431 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7432 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7433 A, DAG.getConstant(32, MVT::i32));
7434 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7435 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7436 B, DAG.getConstant(32, MVT::i32));
7437 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7438 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7440 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7441 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7443 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7444 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7446 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7447 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7448 AloBhi, DAG.getConstant(32, MVT::i32));
7449 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7450 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7451 AhiBlo, DAG.getConstant(32, MVT::i32));
7452 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7453 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7458 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7459 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7460 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7461 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7462 // has only one use.
7463 SDNode *N = Op.getNode();
7464 SDValue LHS = N->getOperand(0);
7465 SDValue RHS = N->getOperand(1);
7466 unsigned BaseOp = 0;
7468 DebugLoc dl = Op.getDebugLoc();
7470 switch (Op.getOpcode()) {
7471 default: llvm_unreachable("Unknown ovf instruction!");
7473 // A subtract of one will be selected as a INC. Note that INC doesn't
7474 // set CF, so we can't do this for UADDO.
7475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7476 if (C->getAPIntValue() == 1) {
7477 BaseOp = X86ISD::INC;
7481 BaseOp = X86ISD::ADD;
7485 BaseOp = X86ISD::ADD;
7489 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7490 // set CF, so we can't do this for USUBO.
7491 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7492 if (C->getAPIntValue() == 1) {
7493 BaseOp = X86ISD::DEC;
7497 BaseOp = X86ISD::SUB;
7501 BaseOp = X86ISD::SUB;
7505 BaseOp = X86ISD::SMUL;
7509 BaseOp = X86ISD::UMUL;
7514 // Also sets EFLAGS.
7515 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7516 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7519 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7520 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7526 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7527 EVT T = Op.getValueType();
7528 DebugLoc dl = Op.getDebugLoc();
7531 switch(T.getSimpleVT().SimpleTy) {
7533 assert(false && "Invalid value type!");
7534 case MVT::i8: Reg = X86::AL; size = 1; break;
7535 case MVT::i16: Reg = X86::AX; size = 2; break;
7536 case MVT::i32: Reg = X86::EAX; size = 4; break;
7538 assert(Subtarget->is64Bit() && "Node not type legal!");
7539 Reg = X86::RAX; size = 8;
7542 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7543 Op.getOperand(2), SDValue());
7544 SDValue Ops[] = { cpIn.getValue(0),
7547 DAG.getTargetConstant(size, MVT::i8),
7549 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7550 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7552 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7556 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7557 SelectionDAG &DAG) {
7558 assert(Subtarget->is64Bit() && "Result not type legalized?");
7559 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7560 SDValue TheChain = Op.getOperand(0);
7561 DebugLoc dl = Op.getDebugLoc();
7562 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7563 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7564 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7566 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7567 DAG.getConstant(32, MVT::i8));
7569 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7572 return DAG.getMergeValues(Ops, 2, dl);
7575 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7576 SDNode *Node = Op.getNode();
7577 DebugLoc dl = Node->getDebugLoc();
7578 EVT T = Node->getValueType(0);
7579 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7580 DAG.getConstant(0, T), Node->getOperand(2));
7581 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7582 cast<AtomicSDNode>(Node)->getMemoryVT(),
7583 Node->getOperand(0),
7584 Node->getOperand(1), negOp,
7585 cast<AtomicSDNode>(Node)->getSrcValue(),
7586 cast<AtomicSDNode>(Node)->getAlignment());
7589 /// LowerOperation - Provide custom lowering hooks for some operations.
7591 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7592 switch (Op.getOpcode()) {
7593 default: llvm_unreachable("Should not custom lower this!");
7594 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7595 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7596 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7597 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7598 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7599 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7600 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7601 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7602 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7603 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7604 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7605 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7606 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7607 case ISD::SHL_PARTS:
7608 case ISD::SRA_PARTS:
7609 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7610 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7611 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7612 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7613 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7614 case ISD::FABS: return LowerFABS(Op, DAG);
7615 case ISD::FNEG: return LowerFNEG(Op, DAG);
7616 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7617 case ISD::SETCC: return LowerSETCC(Op, DAG);
7618 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7619 case ISD::SELECT: return LowerSELECT(Op, DAG);
7620 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7621 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7622 case ISD::VASTART: return LowerVASTART(Op, DAG);
7623 case ISD::VAARG: return LowerVAARG(Op, DAG);
7624 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7625 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7626 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7627 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7628 case ISD::FRAME_TO_ARGS_OFFSET:
7629 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7630 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7631 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7632 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7633 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7634 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7635 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7636 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7642 case ISD::UMULO: return LowerXALUO(Op, DAG);
7643 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7647 void X86TargetLowering::
7648 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7649 SelectionDAG &DAG, unsigned NewOp) {
7650 EVT T = Node->getValueType(0);
7651 DebugLoc dl = Node->getDebugLoc();
7652 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7654 SDValue Chain = Node->getOperand(0);
7655 SDValue In1 = Node->getOperand(1);
7656 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7657 Node->getOperand(2), DAG.getIntPtrConstant(0));
7658 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7659 Node->getOperand(2), DAG.getIntPtrConstant(1));
7660 SDValue Ops[] = { Chain, In1, In2L, In2H };
7661 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7663 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7664 cast<MemSDNode>(Node)->getMemOperand());
7665 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7666 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7667 Results.push_back(Result.getValue(2));
7670 /// ReplaceNodeResults - Replace a node with an illegal result type
7671 /// with a new node built out of custom code.
7672 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7673 SmallVectorImpl<SDValue>&Results,
7674 SelectionDAG &DAG) {
7675 DebugLoc dl = N->getDebugLoc();
7676 switch (N->getOpcode()) {
7678 assert(false && "Do not know how to custom type legalize this operation!");
7680 case ISD::FP_TO_SINT: {
7681 std::pair<SDValue,SDValue> Vals =
7682 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7683 SDValue FIST = Vals.first, StackSlot = Vals.second;
7684 if (FIST.getNode() != 0) {
7685 EVT VT = N->getValueType(0);
7686 // Return a load from the stack slot.
7687 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7692 case ISD::READCYCLECOUNTER: {
7693 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7694 SDValue TheChain = N->getOperand(0);
7695 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7696 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7698 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7700 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7701 SDValue Ops[] = { eax, edx };
7702 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7703 Results.push_back(edx.getValue(1));
7706 case ISD::ATOMIC_CMP_SWAP: {
7707 EVT T = N->getValueType(0);
7708 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7709 SDValue cpInL, cpInH;
7710 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7711 DAG.getConstant(0, MVT::i32));
7712 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7713 DAG.getConstant(1, MVT::i32));
7714 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7715 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7717 SDValue swapInL, swapInH;
7718 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7719 DAG.getConstant(0, MVT::i32));
7720 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7721 DAG.getConstant(1, MVT::i32));
7722 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7724 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7725 swapInL.getValue(1));
7726 SDValue Ops[] = { swapInH.getValue(0),
7728 swapInH.getValue(1) };
7729 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7730 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7731 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7732 MVT::i32, Result.getValue(1));
7733 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7734 MVT::i32, cpOutL.getValue(2));
7735 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7736 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7737 Results.push_back(cpOutH.getValue(1));
7740 case ISD::ATOMIC_LOAD_ADD:
7741 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7743 case ISD::ATOMIC_LOAD_AND:
7744 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7746 case ISD::ATOMIC_LOAD_NAND:
7747 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7749 case ISD::ATOMIC_LOAD_OR:
7750 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7752 case ISD::ATOMIC_LOAD_SUB:
7753 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7755 case ISD::ATOMIC_LOAD_XOR:
7756 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7758 case ISD::ATOMIC_SWAP:
7759 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7764 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7766 default: return NULL;
7767 case X86ISD::BSF: return "X86ISD::BSF";
7768 case X86ISD::BSR: return "X86ISD::BSR";
7769 case X86ISD::SHLD: return "X86ISD::SHLD";
7770 case X86ISD::SHRD: return "X86ISD::SHRD";
7771 case X86ISD::FAND: return "X86ISD::FAND";
7772 case X86ISD::FOR: return "X86ISD::FOR";
7773 case X86ISD::FXOR: return "X86ISD::FXOR";
7774 case X86ISD::FSRL: return "X86ISD::FSRL";
7775 case X86ISD::FILD: return "X86ISD::FILD";
7776 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7777 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7778 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7779 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7780 case X86ISD::FLD: return "X86ISD::FLD";
7781 case X86ISD::FST: return "X86ISD::FST";
7782 case X86ISD::CALL: return "X86ISD::CALL";
7783 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7784 case X86ISD::BT: return "X86ISD::BT";
7785 case X86ISD::CMP: return "X86ISD::CMP";
7786 case X86ISD::COMI: return "X86ISD::COMI";
7787 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7788 case X86ISD::SETCC: return "X86ISD::SETCC";
7789 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7790 case X86ISD::CMOV: return "X86ISD::CMOV";
7791 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7792 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7793 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7794 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7795 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7796 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7797 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7798 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7799 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7800 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7801 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7802 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7803 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7804 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7805 case X86ISD::FMAX: return "X86ISD::FMAX";
7806 case X86ISD::FMIN: return "X86ISD::FMIN";
7807 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7808 case X86ISD::FRCP: return "X86ISD::FRCP";
7809 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7810 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7811 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7812 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7813 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7814 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7815 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7816 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7817 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7818 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7819 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7820 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7821 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7822 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7823 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7824 case X86ISD::VSHL: return "X86ISD::VSHL";
7825 case X86ISD::VSRL: return "X86ISD::VSRL";
7826 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7827 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7828 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7829 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7830 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7831 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7832 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7833 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7834 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7835 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7836 case X86ISD::ADD: return "X86ISD::ADD";
7837 case X86ISD::SUB: return "X86ISD::SUB";
7838 case X86ISD::SMUL: return "X86ISD::SMUL";
7839 case X86ISD::UMUL: return "X86ISD::UMUL";
7840 case X86ISD::INC: return "X86ISD::INC";
7841 case X86ISD::DEC: return "X86ISD::DEC";
7842 case X86ISD::OR: return "X86ISD::OR";
7843 case X86ISD::XOR: return "X86ISD::XOR";
7844 case X86ISD::AND: return "X86ISD::AND";
7845 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7846 case X86ISD::PTEST: return "X86ISD::PTEST";
7847 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7848 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7852 // isLegalAddressingMode - Return true if the addressing mode represented
7853 // by AM is legal for this target, for a load/store of the specified type.
7854 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7855 const Type *Ty) const {
7856 // X86 supports extremely general addressing modes.
7857 CodeModel::Model M = getTargetMachine().getCodeModel();
7859 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7860 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7865 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7867 // If a reference to this global requires an extra load, we can't fold it.
7868 if (isGlobalStubReference(GVFlags))
7871 // If BaseGV requires a register for the PIC base, we cannot also have a
7872 // BaseReg specified.
7873 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7876 // If lower 4G is not available, then we must use rip-relative addressing.
7877 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7887 // These scales always work.
7892 // These scales are formed with basereg+scalereg. Only accept if there is
7897 default: // Other stuff never works.
7905 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7906 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7908 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7909 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7910 if (NumBits1 <= NumBits2)
7915 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7916 if (!VT1.isInteger() || !VT2.isInteger())
7918 unsigned NumBits1 = VT1.getSizeInBits();
7919 unsigned NumBits2 = VT2.getSizeInBits();
7920 if (NumBits1 <= NumBits2)
7925 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7926 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7927 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7930 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7931 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7932 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7935 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7936 // i16 instructions are longer (0x66 prefix) and potentially slower.
7937 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7940 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7941 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7942 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7943 /// are assumed to be legal.
7945 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7947 // Only do shuffles on 128-bit vector types for now.
7948 if (VT.getSizeInBits() == 64)
7951 // FIXME: pshufb, blends, shifts.
7952 return (VT.getVectorNumElements() == 2 ||
7953 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7954 isMOVLMask(M, VT) ||
7955 isSHUFPMask(M, VT) ||
7956 isPSHUFDMask(M, VT) ||
7957 isPSHUFHWMask(M, VT) ||
7958 isPSHUFLWMask(M, VT) ||
7959 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7960 isUNPCKLMask(M, VT) ||
7961 isUNPCKHMask(M, VT) ||
7962 isUNPCKL_v_undef_Mask(M, VT) ||
7963 isUNPCKH_v_undef_Mask(M, VT));
7967 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7969 unsigned NumElts = VT.getVectorNumElements();
7970 // FIXME: This collection of masks seems suspect.
7973 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7974 return (isMOVLMask(Mask, VT) ||
7975 isCommutedMOVLMask(Mask, VT, true) ||
7976 isSHUFPMask(Mask, VT) ||
7977 isCommutedSHUFPMask(Mask, VT));
7982 //===----------------------------------------------------------------------===//
7983 // X86 Scheduler Hooks
7984 //===----------------------------------------------------------------------===//
7986 // private utility function
7988 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7989 MachineBasicBlock *MBB,
7997 TargetRegisterClass *RC,
7998 bool invSrc) const {
7999 // For the atomic bitwise operator, we generate
8002 // ld t1 = [bitinstr.addr]
8003 // op t2 = t1, [bitinstr.val]
8005 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8007 // fallthrough -->nextMBB
8008 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8009 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8010 MachineFunction::iterator MBBIter = MBB;
8013 /// First build the CFG
8014 MachineFunction *F = MBB->getParent();
8015 MachineBasicBlock *thisMBB = MBB;
8016 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8017 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8018 F->insert(MBBIter, newMBB);
8019 F->insert(MBBIter, nextMBB);
8021 // Move all successors to thisMBB to nextMBB
8022 nextMBB->transferSuccessors(thisMBB);
8024 // Update thisMBB to fall through to newMBB
8025 thisMBB->addSuccessor(newMBB);
8027 // newMBB jumps to itself and fall through to nextMBB
8028 newMBB->addSuccessor(nextMBB);
8029 newMBB->addSuccessor(newMBB);
8031 // Insert instructions into newMBB based on incoming instruction
8032 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8033 "unexpected number of operands");
8034 DebugLoc dl = bInstr->getDebugLoc();
8035 MachineOperand& destOper = bInstr->getOperand(0);
8036 MachineOperand* argOpers[2 + X86AddrNumOperands];
8037 int numArgs = bInstr->getNumOperands() - 1;
8038 for (int i=0; i < numArgs; ++i)
8039 argOpers[i] = &bInstr->getOperand(i+1);
8041 // x86 address has 4 operands: base, index, scale, and displacement
8042 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8043 int valArgIndx = lastAddrIndx + 1;
8045 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8046 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8047 for (int i=0; i <= lastAddrIndx; ++i)
8048 (*MIB).addOperand(*argOpers[i]);
8050 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8052 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8057 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8058 assert((argOpers[valArgIndx]->isReg() ||
8059 argOpers[valArgIndx]->isImm()) &&
8061 if (argOpers[valArgIndx]->isReg())
8062 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8064 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8066 (*MIB).addOperand(*argOpers[valArgIndx]);
8068 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8071 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8072 for (int i=0; i <= lastAddrIndx; ++i)
8073 (*MIB).addOperand(*argOpers[i]);
8075 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8076 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8077 bInstr->memoperands_end());
8079 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8083 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8085 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8089 // private utility function: 64 bit atomics on 32 bit host.
8091 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8092 MachineBasicBlock *MBB,
8097 bool invSrc) const {
8098 // For the atomic bitwise operator, we generate
8099 // thisMBB (instructions are in pairs, except cmpxchg8b)
8100 // ld t1,t2 = [bitinstr.addr]
8102 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8103 // op t5, t6 <- out1, out2, [bitinstr.val]
8104 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
8105 // mov ECX, EBX <- t5, t6
8106 // mov EAX, EDX <- t1, t2
8107 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
8108 // mov t3, t4 <- EAX, EDX
8110 // result in out1, out2
8111 // fallthrough -->nextMBB
8113 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8114 const unsigned LoadOpc = X86::MOV32rm;
8115 const unsigned copyOpc = X86::MOV32rr;
8116 const unsigned NotOpc = X86::NOT32r;
8117 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8118 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8119 MachineFunction::iterator MBBIter = MBB;
8122 /// First build the CFG
8123 MachineFunction *F = MBB->getParent();
8124 MachineBasicBlock *thisMBB = MBB;
8125 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8126 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8127 F->insert(MBBIter, newMBB);
8128 F->insert(MBBIter, nextMBB);
8130 // Move all successors to thisMBB to nextMBB
8131 nextMBB->transferSuccessors(thisMBB);
8133 // Update thisMBB to fall through to newMBB
8134 thisMBB->addSuccessor(newMBB);
8136 // newMBB jumps to itself and fall through to nextMBB
8137 newMBB->addSuccessor(nextMBB);
8138 newMBB->addSuccessor(newMBB);
8140 DebugLoc dl = bInstr->getDebugLoc();
8141 // Insert instructions into newMBB based on incoming instruction
8142 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8143 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8144 "unexpected number of operands");
8145 MachineOperand& dest1Oper = bInstr->getOperand(0);
8146 MachineOperand& dest2Oper = bInstr->getOperand(1);
8147 MachineOperand* argOpers[2 + X86AddrNumOperands];
8148 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8149 argOpers[i] = &bInstr->getOperand(i+2);
8151 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8152 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8154 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8155 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8156 for (int i=0; i <= lastAddrIndx; ++i)
8157 (*MIB).addOperand(*argOpers[i]);
8158 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8159 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8160 // add 4 to displacement.
8161 for (int i=0; i <= lastAddrIndx-2; ++i)
8162 (*MIB).addOperand(*argOpers[i]);
8163 MachineOperand newOp3 = *(argOpers[3]);
8165 newOp3.setImm(newOp3.getImm()+4);
8167 newOp3.setOffset(newOp3.getOffset()+4);
8168 (*MIB).addOperand(newOp3);
8169 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8171 // t3/4 are defined later, at the bottom of the loop
8172 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8173 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8174 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8175 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8176 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8177 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8179 // The subsequent operations should be using the destination registers of
8180 //the PHI instructions.
8182 t1 = F->getRegInfo().createVirtualRegister(RC);
8183 t2 = F->getRegInfo().createVirtualRegister(RC);
8184 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8185 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8187 t1 = dest1Oper.getReg();
8188 t2 = dest2Oper.getReg();
8191 int valArgIndx = lastAddrIndx + 1;
8192 assert((argOpers[valArgIndx]->isReg() ||
8193 argOpers[valArgIndx]->isImm()) &&
8195 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8196 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8197 if (argOpers[valArgIndx]->isReg())
8198 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8200 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8201 if (regOpcL != X86::MOV32rr)
8203 (*MIB).addOperand(*argOpers[valArgIndx]);
8204 assert(argOpers[valArgIndx + 1]->isReg() ==
8205 argOpers[valArgIndx]->isReg());
8206 assert(argOpers[valArgIndx + 1]->isImm() ==
8207 argOpers[valArgIndx]->isImm());
8208 if (argOpers[valArgIndx + 1]->isReg())
8209 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8211 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8212 if (regOpcH != X86::MOV32rr)
8214 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8216 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8218 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8221 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8223 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8226 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8227 for (int i=0; i <= lastAddrIndx; ++i)
8228 (*MIB).addOperand(*argOpers[i]);
8230 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8231 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8232 bInstr->memoperands_end());
8234 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8235 MIB.addReg(X86::EAX);
8236 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8237 MIB.addReg(X86::EDX);
8240 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8242 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8246 // private utility function
8248 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8249 MachineBasicBlock *MBB,
8250 unsigned cmovOpc) const {
8251 // For the atomic min/max operator, we generate
8254 // ld t1 = [min/max.addr]
8255 // mov t2 = [min/max.val]
8257 // cmov[cond] t2 = t1
8259 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8261 // fallthrough -->nextMBB
8263 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8264 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8265 MachineFunction::iterator MBBIter = MBB;
8268 /// First build the CFG
8269 MachineFunction *F = MBB->getParent();
8270 MachineBasicBlock *thisMBB = MBB;
8271 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8272 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8273 F->insert(MBBIter, newMBB);
8274 F->insert(MBBIter, nextMBB);
8276 // Move all successors of thisMBB to nextMBB
8277 nextMBB->transferSuccessors(thisMBB);
8279 // Update thisMBB to fall through to newMBB
8280 thisMBB->addSuccessor(newMBB);
8282 // newMBB jumps to newMBB and fall through to nextMBB
8283 newMBB->addSuccessor(nextMBB);
8284 newMBB->addSuccessor(newMBB);
8286 DebugLoc dl = mInstr->getDebugLoc();
8287 // Insert instructions into newMBB based on incoming instruction
8288 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8289 "unexpected number of operands");
8290 MachineOperand& destOper = mInstr->getOperand(0);
8291 MachineOperand* argOpers[2 + X86AddrNumOperands];
8292 int numArgs = mInstr->getNumOperands() - 1;
8293 for (int i=0; i < numArgs; ++i)
8294 argOpers[i] = &mInstr->getOperand(i+1);
8296 // x86 address has 4 operands: base, index, scale, and displacement
8297 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8298 int valArgIndx = lastAddrIndx + 1;
8300 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8301 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8302 for (int i=0; i <= lastAddrIndx; ++i)
8303 (*MIB).addOperand(*argOpers[i]);
8305 // We only support register and immediate values
8306 assert((argOpers[valArgIndx]->isReg() ||
8307 argOpers[valArgIndx]->isImm()) &&
8310 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8311 if (argOpers[valArgIndx]->isReg())
8312 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8314 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8315 (*MIB).addOperand(*argOpers[valArgIndx]);
8317 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8320 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8325 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8326 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8330 // Cmp and exchange if none has modified the memory location
8331 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8332 for (int i=0; i <= lastAddrIndx; ++i)
8333 (*MIB).addOperand(*argOpers[i]);
8335 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8336 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8337 mInstr->memoperands_end());
8339 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8340 MIB.addReg(X86::EAX);
8343 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8345 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8349 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8350 // all of this code can be replaced with that in the .td file.
8352 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8353 unsigned numArgs, bool memArg) const {
8355 MachineFunction *F = BB->getParent();
8356 DebugLoc dl = MI->getDebugLoc();
8357 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8361 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8363 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8365 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8367 for (unsigned i = 0; i < numArgs; ++i) {
8368 MachineOperand &Op = MI->getOperand(i+1);
8370 if (!(Op.isReg() && Op.isImplicit()))
8374 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8377 F->DeleteMachineInstr(MI);
8383 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8385 MachineBasicBlock *MBB) const {
8386 // Emit code to save XMM registers to the stack. The ABI says that the
8387 // number of registers to save is given in %al, so it's theoretically
8388 // possible to do an indirect jump trick to avoid saving all of them,
8389 // however this code takes a simpler approach and just executes all
8390 // of the stores if %al is non-zero. It's less code, and it's probably
8391 // easier on the hardware branch predictor, and stores aren't all that
8392 // expensive anyway.
8394 // Create the new basic blocks. One block contains all the XMM stores,
8395 // and one block is the final destination regardless of whether any
8396 // stores were performed.
8397 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8398 MachineFunction *F = MBB->getParent();
8399 MachineFunction::iterator MBBIter = MBB;
8401 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8402 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8403 F->insert(MBBIter, XMMSaveMBB);
8404 F->insert(MBBIter, EndMBB);
8407 // Move any original successors of MBB to the end block.
8408 EndMBB->transferSuccessors(MBB);
8409 // The original block will now fall through to the XMM save block.
8410 MBB->addSuccessor(XMMSaveMBB);
8411 // The XMMSaveMBB will fall through to the end block.
8412 XMMSaveMBB->addSuccessor(EndMBB);
8414 // Now add the instructions.
8415 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8416 DebugLoc DL = MI->getDebugLoc();
8418 unsigned CountReg = MI->getOperand(0).getReg();
8419 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8420 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8422 if (!Subtarget->isTargetWin64()) {
8423 // If %al is 0, branch around the XMM save block.
8424 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8425 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8426 MBB->addSuccessor(EndMBB);
8429 // In the XMM save block, save all the XMM argument registers.
8430 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8431 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8432 MachineMemOperand *MMO =
8433 F->getMachineMemOperand(
8434 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8435 MachineMemOperand::MOStore, Offset,
8436 /*Size=*/16, /*Align=*/16);
8437 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8438 .addFrameIndex(RegSaveFrameIndex)
8439 .addImm(/*Scale=*/1)
8440 .addReg(/*IndexReg=*/0)
8441 .addImm(/*Disp=*/Offset)
8442 .addReg(/*Segment=*/0)
8443 .addReg(MI->getOperand(i).getReg())
8444 .addMemOperand(MMO);
8447 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8453 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8454 MachineBasicBlock *BB,
8455 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8456 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8457 DebugLoc DL = MI->getDebugLoc();
8459 // To "insert" a SELECT_CC instruction, we actually have to insert the
8460 // diamond control-flow pattern. The incoming instruction knows the
8461 // destination vreg to set, the condition code register to branch on, the
8462 // true/false values to select between, and a branch opcode to use.
8463 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8464 MachineFunction::iterator It = BB;
8470 // cmpTY ccX, r1, r2
8472 // fallthrough --> copy0MBB
8473 MachineBasicBlock *thisMBB = BB;
8474 MachineFunction *F = BB->getParent();
8475 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8476 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8478 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8479 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8480 F->insert(It, copy0MBB);
8481 F->insert(It, sinkMBB);
8482 // Update machine-CFG edges by first adding all successors of the current
8483 // block to the new block which will contain the Phi node for the select.
8484 // Also inform sdisel of the edge changes.
8485 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8486 E = BB->succ_end(); I != E; ++I) {
8487 EM->insert(std::make_pair(*I, sinkMBB));
8488 sinkMBB->addSuccessor(*I);
8490 // Next, remove all successors of the current block, and add the true
8491 // and fallthrough blocks as its successors.
8492 while (!BB->succ_empty())
8493 BB->removeSuccessor(BB->succ_begin());
8494 // Add the true and fallthrough blocks as its successors.
8495 BB->addSuccessor(copy0MBB);
8496 BB->addSuccessor(sinkMBB);
8499 // %FalseValue = ...
8500 // # fallthrough to sinkMBB
8503 // Update machine-CFG edges
8504 BB->addSuccessor(sinkMBB);
8507 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8510 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8511 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8512 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8514 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8519 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8520 MachineBasicBlock *BB,
8521 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8522 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8523 DebugLoc DL = MI->getDebugLoc();
8524 MachineFunction *F = BB->getParent();
8526 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8527 // non-trivial part is impdef of ESP.
8528 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8531 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8532 .addExternalSymbol("_alloca")
8533 .addReg(X86::EAX, RegState::Implicit)
8534 .addReg(X86::ESP, RegState::Implicit)
8535 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8536 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8538 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8543 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8544 MachineBasicBlock *BB,
8545 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8546 switch (MI->getOpcode()) {
8547 default: assert(false && "Unexpected instr type to insert");
8548 case X86::MINGW_ALLOCA:
8549 return EmitLoweredMingwAlloca(MI, BB, EM);
8551 case X86::CMOV_V1I64:
8552 case X86::CMOV_FR32:
8553 case X86::CMOV_FR64:
8554 case X86::CMOV_V4F32:
8555 case X86::CMOV_V2F64:
8556 case X86::CMOV_V2I64:
8557 case X86::CMOV_GR16:
8558 case X86::CMOV_GR32:
8559 case X86::CMOV_RFP32:
8560 case X86::CMOV_RFP64:
8561 case X86::CMOV_RFP80:
8562 return EmitLoweredSelect(MI, BB, EM);
8564 case X86::FP32_TO_INT16_IN_MEM:
8565 case X86::FP32_TO_INT32_IN_MEM:
8566 case X86::FP32_TO_INT64_IN_MEM:
8567 case X86::FP64_TO_INT16_IN_MEM:
8568 case X86::FP64_TO_INT32_IN_MEM:
8569 case X86::FP64_TO_INT64_IN_MEM:
8570 case X86::FP80_TO_INT16_IN_MEM:
8571 case X86::FP80_TO_INT32_IN_MEM:
8572 case X86::FP80_TO_INT64_IN_MEM: {
8573 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8574 DebugLoc DL = MI->getDebugLoc();
8576 // Change the floating point control register to use "round towards zero"
8577 // mode when truncating to an integer value.
8578 MachineFunction *F = BB->getParent();
8579 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8580 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8582 // Load the old value of the high byte of the control word...
8584 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8585 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8588 // Set the high part to be round to zero...
8589 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8592 // Reload the modified control word now...
8593 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8595 // Restore the memory image of control word to original value
8596 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8599 // Get the X86 opcode to use.
8601 switch (MI->getOpcode()) {
8602 default: llvm_unreachable("illegal opcode!");
8603 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8604 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8605 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8606 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8607 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8608 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8609 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8610 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8611 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8615 MachineOperand &Op = MI->getOperand(0);
8617 AM.BaseType = X86AddressMode::RegBase;
8618 AM.Base.Reg = Op.getReg();
8620 AM.BaseType = X86AddressMode::FrameIndexBase;
8621 AM.Base.FrameIndex = Op.getIndex();
8623 Op = MI->getOperand(1);
8625 AM.Scale = Op.getImm();
8626 Op = MI->getOperand(2);
8628 AM.IndexReg = Op.getImm();
8629 Op = MI->getOperand(3);
8630 if (Op.isGlobal()) {
8631 AM.GV = Op.getGlobal();
8633 AM.Disp = Op.getImm();
8635 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8636 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8638 // Reload the original control word now.
8639 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8641 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8644 // DBG_VALUE. Only the frame index case is done here.
8645 case X86::DBG_VALUE: {
8646 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8647 DebugLoc DL = MI->getDebugLoc();
8649 MachineFunction *F = BB->getParent();
8650 AM.BaseType = X86AddressMode::FrameIndexBase;
8651 AM.Base.FrameIndex = MI->getOperand(0).getImm();
8652 addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8653 addImm(MI->getOperand(1).getImm()).
8654 addMetadata(MI->getOperand(2).getMetadata());
8655 F->DeleteMachineInstr(MI); // Remove pseudo.
8659 // String/text processing lowering.
8660 case X86::PCMPISTRM128REG:
8661 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8662 case X86::PCMPISTRM128MEM:
8663 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8664 case X86::PCMPESTRM128REG:
8665 return EmitPCMP(MI, BB, 5, false /* in mem */);
8666 case X86::PCMPESTRM128MEM:
8667 return EmitPCMP(MI, BB, 5, true /* in mem */);
8670 case X86::ATOMAND32:
8671 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8672 X86::AND32ri, X86::MOV32rm,
8673 X86::LCMPXCHG32, X86::MOV32rr,
8674 X86::NOT32r, X86::EAX,
8675 X86::GR32RegisterClass);
8677 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8678 X86::OR32ri, X86::MOV32rm,
8679 X86::LCMPXCHG32, X86::MOV32rr,
8680 X86::NOT32r, X86::EAX,
8681 X86::GR32RegisterClass);
8682 case X86::ATOMXOR32:
8683 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8684 X86::XOR32ri, X86::MOV32rm,
8685 X86::LCMPXCHG32, X86::MOV32rr,
8686 X86::NOT32r, X86::EAX,
8687 X86::GR32RegisterClass);
8688 case X86::ATOMNAND32:
8689 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8690 X86::AND32ri, X86::MOV32rm,
8691 X86::LCMPXCHG32, X86::MOV32rr,
8692 X86::NOT32r, X86::EAX,
8693 X86::GR32RegisterClass, true);
8694 case X86::ATOMMIN32:
8695 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8696 case X86::ATOMMAX32:
8697 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8698 case X86::ATOMUMIN32:
8699 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8700 case X86::ATOMUMAX32:
8701 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8703 case X86::ATOMAND16:
8704 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8705 X86::AND16ri, X86::MOV16rm,
8706 X86::LCMPXCHG16, X86::MOV16rr,
8707 X86::NOT16r, X86::AX,
8708 X86::GR16RegisterClass);
8710 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8711 X86::OR16ri, X86::MOV16rm,
8712 X86::LCMPXCHG16, X86::MOV16rr,
8713 X86::NOT16r, X86::AX,
8714 X86::GR16RegisterClass);
8715 case X86::ATOMXOR16:
8716 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8717 X86::XOR16ri, X86::MOV16rm,
8718 X86::LCMPXCHG16, X86::MOV16rr,
8719 X86::NOT16r, X86::AX,
8720 X86::GR16RegisterClass);
8721 case X86::ATOMNAND16:
8722 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8723 X86::AND16ri, X86::MOV16rm,
8724 X86::LCMPXCHG16, X86::MOV16rr,
8725 X86::NOT16r, X86::AX,
8726 X86::GR16RegisterClass, true);
8727 case X86::ATOMMIN16:
8728 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8729 case X86::ATOMMAX16:
8730 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8731 case X86::ATOMUMIN16:
8732 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8733 case X86::ATOMUMAX16:
8734 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8737 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8738 X86::AND8ri, X86::MOV8rm,
8739 X86::LCMPXCHG8, X86::MOV8rr,
8740 X86::NOT8r, X86::AL,
8741 X86::GR8RegisterClass);
8743 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8744 X86::OR8ri, X86::MOV8rm,
8745 X86::LCMPXCHG8, X86::MOV8rr,
8746 X86::NOT8r, X86::AL,
8747 X86::GR8RegisterClass);
8749 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8750 X86::XOR8ri, X86::MOV8rm,
8751 X86::LCMPXCHG8, X86::MOV8rr,
8752 X86::NOT8r, X86::AL,
8753 X86::GR8RegisterClass);
8754 case X86::ATOMNAND8:
8755 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8756 X86::AND8ri, X86::MOV8rm,
8757 X86::LCMPXCHG8, X86::MOV8rr,
8758 X86::NOT8r, X86::AL,
8759 X86::GR8RegisterClass, true);
8760 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8761 // This group is for 64-bit host.
8762 case X86::ATOMAND64:
8763 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8764 X86::AND64ri32, X86::MOV64rm,
8765 X86::LCMPXCHG64, X86::MOV64rr,
8766 X86::NOT64r, X86::RAX,
8767 X86::GR64RegisterClass);
8769 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8770 X86::OR64ri32, X86::MOV64rm,
8771 X86::LCMPXCHG64, X86::MOV64rr,
8772 X86::NOT64r, X86::RAX,
8773 X86::GR64RegisterClass);
8774 case X86::ATOMXOR64:
8775 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8776 X86::XOR64ri32, X86::MOV64rm,
8777 X86::LCMPXCHG64, X86::MOV64rr,
8778 X86::NOT64r, X86::RAX,
8779 X86::GR64RegisterClass);
8780 case X86::ATOMNAND64:
8781 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8782 X86::AND64ri32, X86::MOV64rm,
8783 X86::LCMPXCHG64, X86::MOV64rr,
8784 X86::NOT64r, X86::RAX,
8785 X86::GR64RegisterClass, true);
8786 case X86::ATOMMIN64:
8787 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8788 case X86::ATOMMAX64:
8789 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8790 case X86::ATOMUMIN64:
8791 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8792 case X86::ATOMUMAX64:
8793 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8795 // This group does 64-bit operations on a 32-bit host.
8796 case X86::ATOMAND6432:
8797 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8798 X86::AND32rr, X86::AND32rr,
8799 X86::AND32ri, X86::AND32ri,
8801 case X86::ATOMOR6432:
8802 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8803 X86::OR32rr, X86::OR32rr,
8804 X86::OR32ri, X86::OR32ri,
8806 case X86::ATOMXOR6432:
8807 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8808 X86::XOR32rr, X86::XOR32rr,
8809 X86::XOR32ri, X86::XOR32ri,
8811 case X86::ATOMNAND6432:
8812 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8813 X86::AND32rr, X86::AND32rr,
8814 X86::AND32ri, X86::AND32ri,
8816 case X86::ATOMADD6432:
8817 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8818 X86::ADD32rr, X86::ADC32rr,
8819 X86::ADD32ri, X86::ADC32ri,
8821 case X86::ATOMSUB6432:
8822 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8823 X86::SUB32rr, X86::SBB32rr,
8824 X86::SUB32ri, X86::SBB32ri,
8826 case X86::ATOMSWAP6432:
8827 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8828 X86::MOV32rr, X86::MOV32rr,
8829 X86::MOV32ri, X86::MOV32ri,
8831 case X86::VASTART_SAVE_XMM_REGS:
8832 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8836 //===----------------------------------------------------------------------===//
8837 // X86 Optimization Hooks
8838 //===----------------------------------------------------------------------===//
8840 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8844 const SelectionDAG &DAG,
8845 unsigned Depth) const {
8846 unsigned Opc = Op.getOpcode();
8847 assert((Opc >= ISD::BUILTIN_OP_END ||
8848 Opc == ISD::INTRINSIC_WO_CHAIN ||
8849 Opc == ISD::INTRINSIC_W_CHAIN ||
8850 Opc == ISD::INTRINSIC_VOID) &&
8851 "Should use MaskedValueIsZero if you don't know whether Op"
8852 " is a target node!");
8854 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8866 // These nodes' second result is a boolean.
8867 if (Op.getResNo() == 0)
8871 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8872 Mask.getBitWidth() - 1);
8877 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8878 /// node is a GlobalAddress + offset.
8879 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8880 GlobalValue* &GA, int64_t &Offset) const{
8881 if (N->getOpcode() == X86ISD::Wrapper) {
8882 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8883 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8884 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8888 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8891 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8892 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8893 /// if the load addresses are consecutive, non-overlapping, and in the right
8895 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8896 const TargetLowering &TLI) {
8897 DebugLoc dl = N->getDebugLoc();
8898 EVT VT = N->getValueType(0);
8899 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8901 if (VT.getSizeInBits() != 128)
8904 SmallVector<SDValue, 16> Elts;
8905 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8906 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8908 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8911 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8912 /// and convert it from being a bunch of shuffles and extracts to a simple
8913 /// store and scalar loads to extract the elements.
8914 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8915 const TargetLowering &TLI) {
8916 SDValue InputVector = N->getOperand(0);
8918 // Only operate on vectors of 4 elements, where the alternative shuffling
8919 // gets to be more expensive.
8920 if (InputVector.getValueType() != MVT::v4i32)
8923 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8924 // single use which is a sign-extend or zero-extend, and all elements are
8926 SmallVector<SDNode *, 4> Uses;
8927 unsigned ExtractedElements = 0;
8928 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8929 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8930 if (UI.getUse().getResNo() != InputVector.getResNo())
8933 SDNode *Extract = *UI;
8934 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8937 if (Extract->getValueType(0) != MVT::i32)
8939 if (!Extract->hasOneUse())
8941 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8942 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8944 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8947 // Record which element was extracted.
8948 ExtractedElements |=
8949 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8951 Uses.push_back(Extract);
8954 // If not all the elements were used, this may not be worthwhile.
8955 if (ExtractedElements != 15)
8958 // Ok, we've now decided to do the transformation.
8959 DebugLoc dl = InputVector.getDebugLoc();
8961 // Store the value to a temporary stack slot.
8962 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8963 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8966 // Replace each use (extract) with a load of the appropriate element.
8967 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8968 UE = Uses.end(); UI != UE; ++UI) {
8969 SDNode *Extract = *UI;
8971 // Compute the element's address.
8972 SDValue Idx = Extract->getOperand(1);
8974 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8975 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8976 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8978 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8981 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8982 NULL, 0, false, false, 0);
8984 // Replace the exact with the load.
8985 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8988 // The replacement was made in place; don't return anything.
8992 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8993 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8994 const X86Subtarget *Subtarget) {
8995 DebugLoc DL = N->getDebugLoc();
8996 SDValue Cond = N->getOperand(0);
8997 // Get the LHS/RHS of the select.
8998 SDValue LHS = N->getOperand(1);
8999 SDValue RHS = N->getOperand(2);
9001 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9002 // instructions match the semantics of the common C idiom x<y?x:y but not
9003 // x<=y?x:y, because of how they handle negative zero (which can be
9004 // ignored in unsafe-math mode).
9005 if (Subtarget->hasSSE2() &&
9006 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9007 Cond.getOpcode() == ISD::SETCC) {
9008 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9010 unsigned Opcode = 0;
9011 // Check for x CC y ? x : y.
9012 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9013 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9017 // Converting this to a min would handle NaNs incorrectly, and swapping
9018 // the operands would cause it to handle comparisons between positive
9019 // and negative zero incorrectly.
9020 if (!FiniteOnlyFPMath() &&
9021 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9022 if (!UnsafeFPMath &&
9023 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9025 std::swap(LHS, RHS);
9027 Opcode = X86ISD::FMIN;
9030 // Converting this to a min would handle comparisons between positive
9031 // and negative zero incorrectly.
9032 if (!UnsafeFPMath &&
9033 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9035 Opcode = X86ISD::FMIN;
9038 // Converting this to a min would handle both negative zeros and NaNs
9039 // incorrectly, but we can swap the operands to fix both.
9040 std::swap(LHS, RHS);
9044 Opcode = X86ISD::FMIN;
9048 // Converting this to a max would handle comparisons between positive
9049 // and negative zero incorrectly.
9050 if (!UnsafeFPMath &&
9051 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9053 Opcode = X86ISD::FMAX;
9056 // Converting this to a max would handle NaNs incorrectly, and swapping
9057 // the operands would cause it to handle comparisons between positive
9058 // and negative zero incorrectly.
9059 if (!FiniteOnlyFPMath() &&
9060 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9061 if (!UnsafeFPMath &&
9062 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9064 std::swap(LHS, RHS);
9066 Opcode = X86ISD::FMAX;
9069 // Converting this to a max would handle both negative zeros and NaNs
9070 // incorrectly, but we can swap the operands to fix both.
9071 std::swap(LHS, RHS);
9075 Opcode = X86ISD::FMAX;
9078 // Check for x CC y ? y : x -- a min/max with reversed arms.
9079 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9080 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9084 // Converting this to a min would handle comparisons between positive
9085 // and negative zero incorrectly, and swapping the operands would
9086 // cause it to handle NaNs incorrectly.
9087 if (!UnsafeFPMath &&
9088 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9089 if (!FiniteOnlyFPMath() &&
9090 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9092 std::swap(LHS, RHS);
9094 Opcode = X86ISD::FMIN;
9097 // Converting this to a min would handle NaNs incorrectly.
9098 if (!UnsafeFPMath &&
9099 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9101 Opcode = X86ISD::FMIN;
9104 // Converting this to a min would handle both negative zeros and NaNs
9105 // incorrectly, but we can swap the operands to fix both.
9106 std::swap(LHS, RHS);
9110 Opcode = X86ISD::FMIN;
9114 // Converting this to a max would handle NaNs incorrectly.
9115 if (!FiniteOnlyFPMath() &&
9116 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9118 Opcode = X86ISD::FMAX;
9121 // Converting this to a max would handle comparisons between positive
9122 // and negative zero incorrectly, and swapping the operands would
9123 // cause it to handle NaNs incorrectly.
9124 if (!UnsafeFPMath &&
9125 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9126 if (!FiniteOnlyFPMath() &&
9127 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9129 std::swap(LHS, RHS);
9131 Opcode = X86ISD::FMAX;
9134 // Converting this to a max would handle both negative zeros and NaNs
9135 // incorrectly, but we can swap the operands to fix both.
9136 std::swap(LHS, RHS);
9140 Opcode = X86ISD::FMAX;
9146 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9149 // If this is a select between two integer constants, try to do some
9151 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9152 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9153 // Don't do this for crazy integer types.
9154 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9155 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9156 // so that TrueC (the true value) is larger than FalseC.
9157 bool NeedsCondInvert = false;
9159 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9160 // Efficiently invertible.
9161 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9162 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9163 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9164 NeedsCondInvert = true;
9165 std::swap(TrueC, FalseC);
9168 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9169 if (FalseC->getAPIntValue() == 0 &&
9170 TrueC->getAPIntValue().isPowerOf2()) {
9171 if (NeedsCondInvert) // Invert the condition if needed.
9172 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9173 DAG.getConstant(1, Cond.getValueType()));
9175 // Zero extend the condition if needed.
9176 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9178 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9179 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9180 DAG.getConstant(ShAmt, MVT::i8));
9183 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9184 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9185 if (NeedsCondInvert) // Invert the condition if needed.
9186 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9187 DAG.getConstant(1, Cond.getValueType()));
9189 // Zero extend the condition if needed.
9190 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9191 FalseC->getValueType(0), Cond);
9192 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9193 SDValue(FalseC, 0));
9196 // Optimize cases that will turn into an LEA instruction. This requires
9197 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9198 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9199 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9200 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9202 bool isFastMultiplier = false;
9204 switch ((unsigned char)Diff) {
9206 case 1: // result = add base, cond
9207 case 2: // result = lea base( , cond*2)
9208 case 3: // result = lea base(cond, cond*2)
9209 case 4: // result = lea base( , cond*4)
9210 case 5: // result = lea base(cond, cond*4)
9211 case 8: // result = lea base( , cond*8)
9212 case 9: // result = lea base(cond, cond*8)
9213 isFastMultiplier = true;
9218 if (isFastMultiplier) {
9219 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9220 if (NeedsCondInvert) // Invert the condition if needed.
9221 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9222 DAG.getConstant(1, Cond.getValueType()));
9224 // Zero extend the condition if needed.
9225 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9227 // Scale the condition by the difference.
9229 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9230 DAG.getConstant(Diff, Cond.getValueType()));
9232 // Add the base if non-zero.
9233 if (FalseC->getAPIntValue() != 0)
9234 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9235 SDValue(FalseC, 0));
9245 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9246 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9247 TargetLowering::DAGCombinerInfo &DCI) {
9248 DebugLoc DL = N->getDebugLoc();
9250 // If the flag operand isn't dead, don't touch this CMOV.
9251 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9254 // If this is a select between two integer constants, try to do some
9255 // optimizations. Note that the operands are ordered the opposite of SELECT
9257 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9258 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9259 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9260 // larger than FalseC (the false value).
9261 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9263 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9264 CC = X86::GetOppositeBranchCondition(CC);
9265 std::swap(TrueC, FalseC);
9268 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9269 // This is efficient for any integer data type (including i8/i16) and
9271 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9272 SDValue Cond = N->getOperand(3);
9273 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9274 DAG.getConstant(CC, MVT::i8), Cond);
9276 // Zero extend the condition if needed.
9277 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9279 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9280 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9281 DAG.getConstant(ShAmt, MVT::i8));
9282 if (N->getNumValues() == 2) // Dead flag value?
9283 return DCI.CombineTo(N, Cond, SDValue());
9287 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9288 // for any integer data type, including i8/i16.
9289 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9290 SDValue Cond = N->getOperand(3);
9291 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9292 DAG.getConstant(CC, MVT::i8), Cond);
9294 // Zero extend the condition if needed.
9295 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9296 FalseC->getValueType(0), Cond);
9297 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9298 SDValue(FalseC, 0));
9300 if (N->getNumValues() == 2) // Dead flag value?
9301 return DCI.CombineTo(N, Cond, SDValue());
9305 // Optimize cases that will turn into an LEA instruction. This requires
9306 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9307 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9308 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9309 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9311 bool isFastMultiplier = false;
9313 switch ((unsigned char)Diff) {
9315 case 1: // result = add base, cond
9316 case 2: // result = lea base( , cond*2)
9317 case 3: // result = lea base(cond, cond*2)
9318 case 4: // result = lea base( , cond*4)
9319 case 5: // result = lea base(cond, cond*4)
9320 case 8: // result = lea base( , cond*8)
9321 case 9: // result = lea base(cond, cond*8)
9322 isFastMultiplier = true;
9327 if (isFastMultiplier) {
9328 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9329 SDValue Cond = N->getOperand(3);
9330 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9331 DAG.getConstant(CC, MVT::i8), Cond);
9332 // Zero extend the condition if needed.
9333 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9335 // Scale the condition by the difference.
9337 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9338 DAG.getConstant(Diff, Cond.getValueType()));
9340 // Add the base if non-zero.
9341 if (FalseC->getAPIntValue() != 0)
9342 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9343 SDValue(FalseC, 0));
9344 if (N->getNumValues() == 2) // Dead flag value?
9345 return DCI.CombineTo(N, Cond, SDValue());
9355 /// PerformMulCombine - Optimize a single multiply with constant into two
9356 /// in order to implement it with two cheaper instructions, e.g.
9357 /// LEA + SHL, LEA + LEA.
9358 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9359 TargetLowering::DAGCombinerInfo &DCI) {
9360 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9363 EVT VT = N->getValueType(0);
9367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9370 uint64_t MulAmt = C->getZExtValue();
9371 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9374 uint64_t MulAmt1 = 0;
9375 uint64_t MulAmt2 = 0;
9376 if ((MulAmt % 9) == 0) {
9378 MulAmt2 = MulAmt / 9;
9379 } else if ((MulAmt % 5) == 0) {
9381 MulAmt2 = MulAmt / 5;
9382 } else if ((MulAmt % 3) == 0) {
9384 MulAmt2 = MulAmt / 3;
9387 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9388 DebugLoc DL = N->getDebugLoc();
9390 if (isPowerOf2_64(MulAmt2) &&
9391 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9392 // If second multiplifer is pow2, issue it first. We want the multiply by
9393 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9395 std::swap(MulAmt1, MulAmt2);
9398 if (isPowerOf2_64(MulAmt1))
9399 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9400 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9402 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9403 DAG.getConstant(MulAmt1, VT));
9405 if (isPowerOf2_64(MulAmt2))
9406 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9407 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9409 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9410 DAG.getConstant(MulAmt2, VT));
9412 // Do not add new nodes to DAG combiner worklist.
9413 DCI.CombineTo(N, NewMul, false);
9418 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9419 SDValue N0 = N->getOperand(0);
9420 SDValue N1 = N->getOperand(1);
9421 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9422 EVT VT = N0.getValueType();
9424 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9425 // since the result of setcc_c is all zero's or all ones.
9426 if (N1C && N0.getOpcode() == ISD::AND &&
9427 N0.getOperand(1).getOpcode() == ISD::Constant) {
9428 SDValue N00 = N0.getOperand(0);
9429 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9430 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9431 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9432 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9433 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9434 APInt ShAmt = N1C->getAPIntValue();
9435 Mask = Mask.shl(ShAmt);
9437 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9438 N00, DAG.getConstant(Mask, VT));
9445 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9447 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9448 const X86Subtarget *Subtarget) {
9449 EVT VT = N->getValueType(0);
9450 if (!VT.isVector() && VT.isInteger() &&
9451 N->getOpcode() == ISD::SHL)
9452 return PerformSHLCombine(N, DAG);
9454 // On X86 with SSE2 support, we can transform this to a vector shift if
9455 // all elements are shifted by the same amount. We can't do this in legalize
9456 // because the a constant vector is typically transformed to a constant pool
9457 // so we have no knowledge of the shift amount.
9458 if (!Subtarget->hasSSE2())
9461 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9464 SDValue ShAmtOp = N->getOperand(1);
9465 EVT EltVT = VT.getVectorElementType();
9466 DebugLoc DL = N->getDebugLoc();
9467 SDValue BaseShAmt = SDValue();
9468 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9469 unsigned NumElts = VT.getVectorNumElements();
9471 for (; i != NumElts; ++i) {
9472 SDValue Arg = ShAmtOp.getOperand(i);
9473 if (Arg.getOpcode() == ISD::UNDEF) continue;
9477 for (; i != NumElts; ++i) {
9478 SDValue Arg = ShAmtOp.getOperand(i);
9479 if (Arg.getOpcode() == ISD::UNDEF) continue;
9480 if (Arg != BaseShAmt) {
9484 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9485 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9486 SDValue InVec = ShAmtOp.getOperand(0);
9487 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9488 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9490 for (; i != NumElts; ++i) {
9491 SDValue Arg = InVec.getOperand(i);
9492 if (Arg.getOpcode() == ISD::UNDEF) continue;
9496 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9497 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9498 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9499 if (C->getZExtValue() == SplatIdx)
9500 BaseShAmt = InVec.getOperand(1);
9503 if (BaseShAmt.getNode() == 0)
9504 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9505 DAG.getIntPtrConstant(0));
9509 // The shift amount is an i32.
9510 if (EltVT.bitsGT(MVT::i32))
9511 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9512 else if (EltVT.bitsLT(MVT::i32))
9513 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9515 // The shift amount is identical so we can do a vector shift.
9516 SDValue ValOp = N->getOperand(0);
9517 switch (N->getOpcode()) {
9519 llvm_unreachable("Unknown shift opcode!");
9522 if (VT == MVT::v2i64)
9523 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9524 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9526 if (VT == MVT::v4i32)
9527 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9528 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9530 if (VT == MVT::v8i16)
9531 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9532 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9536 if (VT == MVT::v4i32)
9537 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9538 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9540 if (VT == MVT::v8i16)
9541 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9542 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9546 if (VT == MVT::v2i64)
9547 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9548 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9550 if (VT == MVT::v4i32)
9551 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9552 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9554 if (VT == MVT::v8i16)
9555 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9556 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9563 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9564 const X86Subtarget *Subtarget) {
9565 EVT VT = N->getValueType(0);
9566 if (VT != MVT::i64 || !Subtarget->is64Bit())
9569 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9570 SDValue N0 = N->getOperand(0);
9571 SDValue N1 = N->getOperand(1);
9572 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9574 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9577 SDValue ShAmt0 = N0.getOperand(1);
9578 if (ShAmt0.getValueType() != MVT::i8)
9580 SDValue ShAmt1 = N1.getOperand(1);
9581 if (ShAmt1.getValueType() != MVT::i8)
9583 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9584 ShAmt0 = ShAmt0.getOperand(0);
9585 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9586 ShAmt1 = ShAmt1.getOperand(0);
9588 DebugLoc DL = N->getDebugLoc();
9589 unsigned Opc = X86ISD::SHLD;
9590 SDValue Op0 = N0.getOperand(0);
9591 SDValue Op1 = N1.getOperand(0);
9592 if (ShAmt0.getOpcode() == ISD::SUB) {
9594 std::swap(Op0, Op1);
9595 std::swap(ShAmt0, ShAmt1);
9598 if (ShAmt1.getOpcode() == ISD::SUB) {
9599 SDValue Sum = ShAmt1.getOperand(0);
9600 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9601 if (SumC->getSExtValue() == 64 &&
9602 ShAmt1.getOperand(1) == ShAmt0)
9603 return DAG.getNode(Opc, DL, VT,
9605 DAG.getNode(ISD::TRUNCATE, DL,
9608 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9609 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9611 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9612 return DAG.getNode(Opc, DL, VT,
9613 N0.getOperand(0), N1.getOperand(0),
9614 DAG.getNode(ISD::TRUNCATE, DL,
9621 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9622 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9623 const X86Subtarget *Subtarget) {
9624 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9625 // the FP state in cases where an emms may be missing.
9626 // A preferable solution to the general problem is to figure out the right
9627 // places to insert EMMS. This qualifies as a quick hack.
9629 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9630 StoreSDNode *St = cast<StoreSDNode>(N);
9631 EVT VT = St->getValue().getValueType();
9632 if (VT.getSizeInBits() != 64)
9635 const Function *F = DAG.getMachineFunction().getFunction();
9636 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9637 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9638 && Subtarget->hasSSE2();
9639 if ((VT.isVector() ||
9640 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9641 isa<LoadSDNode>(St->getValue()) &&
9642 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9643 St->getChain().hasOneUse() && !St->isVolatile()) {
9644 SDNode* LdVal = St->getValue().getNode();
9646 int TokenFactorIndex = -1;
9647 SmallVector<SDValue, 8> Ops;
9648 SDNode* ChainVal = St->getChain().getNode();
9649 // Must be a store of a load. We currently handle two cases: the load
9650 // is a direct child, and it's under an intervening TokenFactor. It is
9651 // possible to dig deeper under nested TokenFactors.
9652 if (ChainVal == LdVal)
9653 Ld = cast<LoadSDNode>(St->getChain());
9654 else if (St->getValue().hasOneUse() &&
9655 ChainVal->getOpcode() == ISD::TokenFactor) {
9656 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9657 if (ChainVal->getOperand(i).getNode() == LdVal) {
9658 TokenFactorIndex = i;
9659 Ld = cast<LoadSDNode>(St->getValue());
9661 Ops.push_back(ChainVal->getOperand(i));
9665 if (!Ld || !ISD::isNormalLoad(Ld))
9668 // If this is not the MMX case, i.e. we are just turning i64 load/store
9669 // into f64 load/store, avoid the transformation if there are multiple
9670 // uses of the loaded value.
9671 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9674 DebugLoc LdDL = Ld->getDebugLoc();
9675 DebugLoc StDL = N->getDebugLoc();
9676 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9677 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9679 if (Subtarget->is64Bit() || F64IsLegal) {
9680 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9681 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9682 Ld->getBasePtr(), Ld->getSrcValue(),
9683 Ld->getSrcValueOffset(), Ld->isVolatile(),
9684 Ld->isNonTemporal(), Ld->getAlignment());
9685 SDValue NewChain = NewLd.getValue(1);
9686 if (TokenFactorIndex != -1) {
9687 Ops.push_back(NewChain);
9688 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9691 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9692 St->getSrcValue(), St->getSrcValueOffset(),
9693 St->isVolatile(), St->isNonTemporal(),
9694 St->getAlignment());
9697 // Otherwise, lower to two pairs of 32-bit loads / stores.
9698 SDValue LoAddr = Ld->getBasePtr();
9699 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9700 DAG.getConstant(4, MVT::i32));
9702 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9703 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9704 Ld->isVolatile(), Ld->isNonTemporal(),
9705 Ld->getAlignment());
9706 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9707 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9708 Ld->isVolatile(), Ld->isNonTemporal(),
9709 MinAlign(Ld->getAlignment(), 4));
9711 SDValue NewChain = LoLd.getValue(1);
9712 if (TokenFactorIndex != -1) {
9713 Ops.push_back(LoLd);
9714 Ops.push_back(HiLd);
9715 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9719 LoAddr = St->getBasePtr();
9720 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9721 DAG.getConstant(4, MVT::i32));
9723 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9724 St->getSrcValue(), St->getSrcValueOffset(),
9725 St->isVolatile(), St->isNonTemporal(),
9726 St->getAlignment());
9727 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9729 St->getSrcValueOffset() + 4,
9731 St->isNonTemporal(),
9732 MinAlign(St->getAlignment(), 4));
9733 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9738 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9739 /// X86ISD::FXOR nodes.
9740 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9741 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9742 // F[X]OR(0.0, x) -> x
9743 // F[X]OR(x, 0.0) -> x
9744 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9745 if (C->getValueAPF().isPosZero())
9746 return N->getOperand(1);
9747 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9748 if (C->getValueAPF().isPosZero())
9749 return N->getOperand(0);
9753 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9754 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9755 // FAND(0.0, x) -> 0.0
9756 // FAND(x, 0.0) -> 0.0
9757 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9758 if (C->getValueAPF().isPosZero())
9759 return N->getOperand(0);
9760 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9761 if (C->getValueAPF().isPosZero())
9762 return N->getOperand(1);
9766 static SDValue PerformBTCombine(SDNode *N,
9768 TargetLowering::DAGCombinerInfo &DCI) {
9769 // BT ignores high bits in the bit index operand.
9770 SDValue Op1 = N->getOperand(1);
9771 if (Op1.hasOneUse()) {
9772 unsigned BitWidth = Op1.getValueSizeInBits();
9773 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9774 APInt KnownZero, KnownOne;
9775 TargetLowering::TargetLoweringOpt TLO(DAG);
9776 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9777 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9778 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9779 DCI.CommitTargetLoweringOpt(TLO);
9784 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9785 SDValue Op = N->getOperand(0);
9786 if (Op.getOpcode() == ISD::BIT_CONVERT)
9787 Op = Op.getOperand(0);
9788 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9789 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9790 VT.getVectorElementType().getSizeInBits() ==
9791 OpVT.getVectorElementType().getSizeInBits()) {
9792 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9797 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9798 // Locked instructions, in turn, have implicit fence semantics (all memory
9799 // operations are flushed before issuing the locked instruction, and the
9800 // are not buffered), so we can fold away the common pattern of
9801 // fence-atomic-fence.
9802 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9803 SDValue atomic = N->getOperand(0);
9804 switch (atomic.getOpcode()) {
9805 case ISD::ATOMIC_CMP_SWAP:
9806 case ISD::ATOMIC_SWAP:
9807 case ISD::ATOMIC_LOAD_ADD:
9808 case ISD::ATOMIC_LOAD_SUB:
9809 case ISD::ATOMIC_LOAD_AND:
9810 case ISD::ATOMIC_LOAD_OR:
9811 case ISD::ATOMIC_LOAD_XOR:
9812 case ISD::ATOMIC_LOAD_NAND:
9813 case ISD::ATOMIC_LOAD_MIN:
9814 case ISD::ATOMIC_LOAD_MAX:
9815 case ISD::ATOMIC_LOAD_UMIN:
9816 case ISD::ATOMIC_LOAD_UMAX:
9822 SDValue fence = atomic.getOperand(0);
9823 if (fence.getOpcode() != ISD::MEMBARRIER)
9826 switch (atomic.getOpcode()) {
9827 case ISD::ATOMIC_CMP_SWAP:
9828 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9829 atomic.getOperand(1), atomic.getOperand(2),
9830 atomic.getOperand(3));
9831 case ISD::ATOMIC_SWAP:
9832 case ISD::ATOMIC_LOAD_ADD:
9833 case ISD::ATOMIC_LOAD_SUB:
9834 case ISD::ATOMIC_LOAD_AND:
9835 case ISD::ATOMIC_LOAD_OR:
9836 case ISD::ATOMIC_LOAD_XOR:
9837 case ISD::ATOMIC_LOAD_NAND:
9838 case ISD::ATOMIC_LOAD_MIN:
9839 case ISD::ATOMIC_LOAD_MAX:
9840 case ISD::ATOMIC_LOAD_UMIN:
9841 case ISD::ATOMIC_LOAD_UMAX:
9842 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9843 atomic.getOperand(1), atomic.getOperand(2));
9849 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9850 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9851 // (and (i32 x86isd::setcc_carry), 1)
9852 // This eliminates the zext. This transformation is necessary because
9853 // ISD::SETCC is always legalized to i8.
9854 DebugLoc dl = N->getDebugLoc();
9855 SDValue N0 = N->getOperand(0);
9856 EVT VT = N->getValueType(0);
9857 if (N0.getOpcode() == ISD::AND &&
9859 N0.getOperand(0).hasOneUse()) {
9860 SDValue N00 = N0.getOperand(0);
9861 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9863 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9864 if (!C || C->getZExtValue() != 1)
9866 return DAG.getNode(ISD::AND, dl, VT,
9867 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9868 N00.getOperand(0), N00.getOperand(1)),
9869 DAG.getConstant(1, VT));
9875 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9876 DAGCombinerInfo &DCI) const {
9877 SelectionDAG &DAG = DCI.DAG;
9878 switch (N->getOpcode()) {
9880 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9881 case ISD::EXTRACT_VECTOR_ELT:
9882 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9883 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9884 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9885 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9888 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9889 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9890 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9892 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9893 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9894 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9895 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9896 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9897 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9903 //===----------------------------------------------------------------------===//
9904 // X86 Inline Assembly Support
9905 //===----------------------------------------------------------------------===//
9907 static bool LowerToBSwap(CallInst *CI) {
9908 // FIXME: this should verify that we are targetting a 486 or better. If not,
9909 // we will turn this bswap into something that will be lowered to logical ops
9910 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9911 // so don't worry about this.
9913 // Verify this is a simple bswap.
9914 if (CI->getNumOperands() != 2 ||
9915 CI->getType() != CI->getOperand(1)->getType() ||
9916 !CI->getType()->isIntegerTy())
9919 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9920 if (!Ty || Ty->getBitWidth() % 16 != 0)
9923 // Okay, we can do this xform, do so now.
9924 const Type *Tys[] = { Ty };
9925 Module *M = CI->getParent()->getParent()->getParent();
9926 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9928 Value *Op = CI->getOperand(1);
9929 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9931 CI->replaceAllUsesWith(Op);
9932 CI->eraseFromParent();
9936 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9937 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9938 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9940 std::string AsmStr = IA->getAsmString();
9942 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9943 SmallVector<StringRef, 4> AsmPieces;
9944 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9946 switch (AsmPieces.size()) {
9947 default: return false;
9949 AsmStr = AsmPieces[0];
9951 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9954 if (AsmPieces.size() == 2 &&
9955 (AsmPieces[0] == "bswap" ||
9956 AsmPieces[0] == "bswapq" ||
9957 AsmPieces[0] == "bswapl") &&
9958 (AsmPieces[1] == "$0" ||
9959 AsmPieces[1] == "${0:q}")) {
9960 // No need to check constraints, nothing other than the equivalent of
9961 // "=r,0" would be valid here.
9962 return LowerToBSwap(CI);
9964 // rorw $$8, ${0:w} --> llvm.bswap.i16
9965 if (CI->getType()->isIntegerTy(16) &&
9966 AsmPieces.size() == 3 &&
9967 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9968 AsmPieces[1] == "$$8," &&
9969 AsmPieces[2] == "${0:w}" &&
9970 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9972 const std::string &Constraints = IA->getConstraintString();
9973 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9974 std::sort(AsmPieces.begin(), AsmPieces.end());
9975 if (AsmPieces.size() == 4 &&
9976 AsmPieces[0] == "~{cc}" &&
9977 AsmPieces[1] == "~{dirflag}" &&
9978 AsmPieces[2] == "~{flags}" &&
9979 AsmPieces[3] == "~{fpsr}") {
9980 return LowerToBSwap(CI);
9985 if (CI->getType()->isIntegerTy(64) &&
9986 Constraints.size() >= 2 &&
9987 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9988 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9989 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9990 SmallVector<StringRef, 4> Words;
9991 SplitString(AsmPieces[0], Words, " \t");
9992 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9994 SplitString(AsmPieces[1], Words, " \t");
9995 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9997 SplitString(AsmPieces[2], Words, " \t,");
9998 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9999 Words[2] == "%edx") {
10000 return LowerToBSwap(CI);
10012 /// getConstraintType - Given a constraint letter, return the type of
10013 /// constraint it is for this target.
10014 X86TargetLowering::ConstraintType
10015 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10016 if (Constraint.size() == 1) {
10017 switch (Constraint[0]) {
10029 return C_RegisterClass;
10037 return TargetLowering::getConstraintType(Constraint);
10040 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10041 /// with another that has more specific requirements based on the type of the
10042 /// corresponding operand.
10043 const char *X86TargetLowering::
10044 LowerXConstraint(EVT ConstraintVT) const {
10045 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10046 // 'f' like normal targets.
10047 if (ConstraintVT.isFloatingPoint()) {
10048 if (Subtarget->hasSSE2())
10050 if (Subtarget->hasSSE1())
10054 return TargetLowering::LowerXConstraint(ConstraintVT);
10057 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10058 /// vector. If it is invalid, don't add anything to Ops.
10059 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10062 std::vector<SDValue>&Ops,
10063 SelectionDAG &DAG) const {
10064 SDValue Result(0, 0);
10066 switch (Constraint) {
10069 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10070 if (C->getZExtValue() <= 31) {
10071 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10077 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10078 if (C->getZExtValue() <= 63) {
10079 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10085 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10086 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10087 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10094 if (C->getZExtValue() <= 255) {
10095 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10101 // 32-bit signed value
10102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10103 const ConstantInt *CI = C->getConstantIntValue();
10104 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10105 C->getSExtValue())) {
10106 // Widen to 64 bits here to get it sign extended.
10107 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10110 // FIXME gcc accepts some relocatable values here too, but only in certain
10111 // memory models; it's complicated.
10116 // 32-bit unsigned value
10117 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10118 const ConstantInt *CI = C->getConstantIntValue();
10119 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10120 C->getZExtValue())) {
10121 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10125 // FIXME gcc accepts some relocatable values here too, but only in certain
10126 // memory models; it's complicated.
10130 // Literal immediates are always ok.
10131 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10132 // Widen to 64 bits here to get it sign extended.
10133 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10137 // If we are in non-pic codegen mode, we allow the address of a global (with
10138 // an optional displacement) to be used with 'i'.
10139 GlobalAddressSDNode *GA = 0;
10140 int64_t Offset = 0;
10142 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10144 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10145 Offset += GA->getOffset();
10147 } else if (Op.getOpcode() == ISD::ADD) {
10148 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10149 Offset += C->getZExtValue();
10150 Op = Op.getOperand(0);
10153 } else if (Op.getOpcode() == ISD::SUB) {
10154 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10155 Offset += -C->getZExtValue();
10156 Op = Op.getOperand(0);
10161 // Otherwise, this isn't something we can handle, reject it.
10165 GlobalValue *GV = GA->getGlobal();
10166 // If we require an extra load to get this address, as in PIC mode, we
10167 // can't accept it.
10168 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10169 getTargetMachine())))
10173 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10175 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10181 if (Result.getNode()) {
10182 Ops.push_back(Result);
10185 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10189 std::vector<unsigned> X86TargetLowering::
10190 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10192 if (Constraint.size() == 1) {
10193 // FIXME: not handling fp-stack yet!
10194 switch (Constraint[0]) { // GCC X86 Constraint Letters
10195 default: break; // Unknown constraint letter
10196 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10197 if (Subtarget->is64Bit()) {
10198 if (VT == MVT::i32)
10199 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10200 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10201 X86::R10D,X86::R11D,X86::R12D,
10202 X86::R13D,X86::R14D,X86::R15D,
10203 X86::EBP, X86::ESP, 0);
10204 else if (VT == MVT::i16)
10205 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10206 X86::SI, X86::DI, X86::R8W,X86::R9W,
10207 X86::R10W,X86::R11W,X86::R12W,
10208 X86::R13W,X86::R14W,X86::R15W,
10209 X86::BP, X86::SP, 0);
10210 else if (VT == MVT::i8)
10211 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10212 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10213 X86::R10B,X86::R11B,X86::R12B,
10214 X86::R13B,X86::R14B,X86::R15B,
10215 X86::BPL, X86::SPL, 0);
10217 else if (VT == MVT::i64)
10218 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10219 X86::RSI, X86::RDI, X86::R8, X86::R9,
10220 X86::R10, X86::R11, X86::R12,
10221 X86::R13, X86::R14, X86::R15,
10222 X86::RBP, X86::RSP, 0);
10226 // 32-bit fallthrough
10227 case 'Q': // Q_REGS
10228 if (VT == MVT::i32)
10229 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10230 else if (VT == MVT::i16)
10231 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10232 else if (VT == MVT::i8)
10233 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10234 else if (VT == MVT::i64)
10235 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10240 return std::vector<unsigned>();
10243 std::pair<unsigned, const TargetRegisterClass*>
10244 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10246 // First, see if this is a constraint that directly corresponds to an LLVM
10248 if (Constraint.size() == 1) {
10249 // GCC Constraint Letters
10250 switch (Constraint[0]) {
10252 case 'r': // GENERAL_REGS
10253 case 'l': // INDEX_REGS
10255 return std::make_pair(0U, X86::GR8RegisterClass);
10256 if (VT == MVT::i16)
10257 return std::make_pair(0U, X86::GR16RegisterClass);
10258 if (VT == MVT::i32 || !Subtarget->is64Bit())
10259 return std::make_pair(0U, X86::GR32RegisterClass);
10260 return std::make_pair(0U, X86::GR64RegisterClass);
10261 case 'R': // LEGACY_REGS
10263 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10264 if (VT == MVT::i16)
10265 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10266 if (VT == MVT::i32 || !Subtarget->is64Bit())
10267 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10268 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10269 case 'f': // FP Stack registers.
10270 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10271 // value to the correct fpstack register class.
10272 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10273 return std::make_pair(0U, X86::RFP32RegisterClass);
10274 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10275 return std::make_pair(0U, X86::RFP64RegisterClass);
10276 return std::make_pair(0U, X86::RFP80RegisterClass);
10277 case 'y': // MMX_REGS if MMX allowed.
10278 if (!Subtarget->hasMMX()) break;
10279 return std::make_pair(0U, X86::VR64RegisterClass);
10280 case 'Y': // SSE_REGS if SSE2 allowed
10281 if (!Subtarget->hasSSE2()) break;
10283 case 'x': // SSE_REGS if SSE1 allowed
10284 if (!Subtarget->hasSSE1()) break;
10286 switch (VT.getSimpleVT().SimpleTy) {
10288 // Scalar SSE types.
10291 return std::make_pair(0U, X86::FR32RegisterClass);
10294 return std::make_pair(0U, X86::FR64RegisterClass);
10302 return std::make_pair(0U, X86::VR128RegisterClass);
10308 // Use the default implementation in TargetLowering to convert the register
10309 // constraint into a member of a register class.
10310 std::pair<unsigned, const TargetRegisterClass*> Res;
10311 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10313 // Not found as a standard register?
10314 if (Res.second == 0) {
10315 // Map st(0) -> st(7) -> ST0
10316 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10317 tolower(Constraint[1]) == 's' &&
10318 tolower(Constraint[2]) == 't' &&
10319 Constraint[3] == '(' &&
10320 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10321 Constraint[5] == ')' &&
10322 Constraint[6] == '}') {
10324 Res.first = X86::ST0+Constraint[4]-'0';
10325 Res.second = X86::RFP80RegisterClass;
10329 // GCC allows "st(0)" to be called just plain "st".
10330 if (StringRef("{st}").equals_lower(Constraint)) {
10331 Res.first = X86::ST0;
10332 Res.second = X86::RFP80RegisterClass;
10337 if (StringRef("{flags}").equals_lower(Constraint)) {
10338 Res.first = X86::EFLAGS;
10339 Res.second = X86::CCRRegisterClass;
10343 // 'A' means EAX + EDX.
10344 if (Constraint == "A") {
10345 Res.first = X86::EAX;
10346 Res.second = X86::GR32_ADRegisterClass;
10352 // Otherwise, check to see if this is a register class of the wrong value
10353 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10354 // turn into {ax},{dx}.
10355 if (Res.second->hasType(VT))
10356 return Res; // Correct type already, nothing to do.
10358 // All of the single-register GCC register classes map their values onto
10359 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10360 // really want an 8-bit or 32-bit register, map to the appropriate register
10361 // class and return the appropriate register.
10362 if (Res.second == X86::GR16RegisterClass) {
10363 if (VT == MVT::i8) {
10364 unsigned DestReg = 0;
10365 switch (Res.first) {
10367 case X86::AX: DestReg = X86::AL; break;
10368 case X86::DX: DestReg = X86::DL; break;
10369 case X86::CX: DestReg = X86::CL; break;
10370 case X86::BX: DestReg = X86::BL; break;
10373 Res.first = DestReg;
10374 Res.second = X86::GR8RegisterClass;
10376 } else if (VT == MVT::i32) {
10377 unsigned DestReg = 0;
10378 switch (Res.first) {
10380 case X86::AX: DestReg = X86::EAX; break;
10381 case X86::DX: DestReg = X86::EDX; break;
10382 case X86::CX: DestReg = X86::ECX; break;
10383 case X86::BX: DestReg = X86::EBX; break;
10384 case X86::SI: DestReg = X86::ESI; break;
10385 case X86::DI: DestReg = X86::EDI; break;
10386 case X86::BP: DestReg = X86::EBP; break;
10387 case X86::SP: DestReg = X86::ESP; break;
10390 Res.first = DestReg;
10391 Res.second = X86::GR32RegisterClass;
10393 } else if (VT == MVT::i64) {
10394 unsigned DestReg = 0;
10395 switch (Res.first) {
10397 case X86::AX: DestReg = X86::RAX; break;
10398 case X86::DX: DestReg = X86::RDX; break;
10399 case X86::CX: DestReg = X86::RCX; break;
10400 case X86::BX: DestReg = X86::RBX; break;
10401 case X86::SI: DestReg = X86::RSI; break;
10402 case X86::DI: DestReg = X86::RDI; break;
10403 case X86::BP: DestReg = X86::RBP; break;
10404 case X86::SP: DestReg = X86::RSP; break;
10407 Res.first = DestReg;
10408 Res.second = X86::GR64RegisterClass;
10411 } else if (Res.second == X86::FR32RegisterClass ||
10412 Res.second == X86::FR64RegisterClass ||
10413 Res.second == X86::VR128RegisterClass) {
10414 // Handle references to XMM physical registers that got mapped into the
10415 // wrong class. This can happen with constraints like {xmm0} where the
10416 // target independent register mapper will just pick the first match it can
10417 // find, ignoring the required type.
10418 if (VT == MVT::f32)
10419 Res.second = X86::FR32RegisterClass;
10420 else if (VT == MVT::f64)
10421 Res.second = X86::FR64RegisterClass;
10422 else if (X86::VR128RegisterClass->hasType(VT))
10423 Res.second = X86::VR128RegisterClass;