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 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66 default: llvm_unreachable("unknown subtarget type");
67 case X86Subtarget::isDarwin:
68 if (TM.getSubtarget<X86Subtarget>().is64Bit())
69 return new X8664_MachoTargetObjectFile();
70 return new TargetLoweringObjectFileMachO();
71 case X86Subtarget::isELF:
72 if (TM.getSubtarget<X86Subtarget>().is64Bit())
73 return new X8664_ELFTargetObjectFile(TM);
74 return new X8632_ELFTargetObjectFile(TM);
75 case X86Subtarget::isMingw:
76 case X86Subtarget::isCygwin:
77 case X86Subtarget::isWindows:
78 return new TargetLoweringObjectFileCOFF();
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83 : TargetLowering(TM, createTLOF(TM)) {
84 Subtarget = &TM.getSubtarget<X86Subtarget>();
85 X86ScalarSSEf64 = Subtarget->hasSSE2();
86 X86ScalarSSEf32 = Subtarget->hasSSE1();
87 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89 RegInfo = TM.getRegisterInfo();
92 // Set up the TargetLowering object.
94 // X86 is weird, it always uses i8 for shift amounts and setcc results.
95 setShiftAmountType(MVT::i8);
96 setBooleanContents(ZeroOrOneBooleanContent);
97 setSchedulingPreference(Sched::RegPressure);
98 setStackPointerRegisterToSaveRestore(X86StackPtr);
100 if (Subtarget->isTargetDarwin()) {
101 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102 setUseUnderscoreSetJmp(false);
103 setUseUnderscoreLongJmp(false);
104 } else if (Subtarget->isTargetMingw()) {
105 // MS runtime is weird: it exports _setjmp, but longjmp!
106 setUseUnderscoreSetJmp(true);
107 setUseUnderscoreLongJmp(false);
109 setUseUnderscoreSetJmp(true);
110 setUseUnderscoreLongJmp(true);
113 // Set up the register classes.
114 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117 if (Subtarget->is64Bit())
118 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
120 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
122 // We don't accept any truncstore of integer registers.
123 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
130 // SETOEQ and SETUNE require checking two conditions.
131 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
138 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
140 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
141 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
142 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
144 if (Subtarget->is64Bit()) {
145 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
146 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
147 } else if (!UseSoftFloat) {
148 // We have an algorithm for SSE2->double, and we turn this into a
149 // 64-bit FILD followed by conditional FADD for other targets.
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
151 // We have an algorithm for SSE2, and we turn this into a 64-bit
152 // FILD for other targets.
153 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
156 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
158 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
159 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
162 // SSE has no i16 to fp conversion, only i32
163 if (X86ScalarSSEf32) {
164 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
165 // f32 and f64 cases are Legal, f80 case is not
166 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
168 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
169 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
172 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
176 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
177 // are Legal, f80 is custom lowered.
178 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
179 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
181 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
183 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
184 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
186 if (X86ScalarSSEf32) {
187 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
188 // f32 and f64 cases are Legal, f80 case is not
189 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
191 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
192 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
195 // Handle FP_TO_UINT by promoting the destination to a larger signed
197 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
198 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
199 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
201 if (Subtarget->is64Bit()) {
202 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
203 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
204 } else if (!UseSoftFloat) {
205 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
206 // Expand FP_TO_UINT into a select.
207 // FIXME: We would like to use a Custom expander here eventually to do
208 // the optimal thing for SSE vs. the default expansion in the legalizer.
209 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
211 // With SSE3 we can use fisttpll to convert to a signed i64; without
212 // SSE, we're stuck with a fistpll.
213 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
216 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
217 if (!X86ScalarSSEf64) {
218 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
219 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
222 // Scalar integer divide and remainder are lowered to use operations that
223 // produce two results, to match the available instructions. This exposes
224 // the two-result form to trivial CSE, which is able to combine x/y and x%y
225 // into a single instruction.
227 // Scalar integer multiply-high is also lowered to use two-result
228 // operations, to match the available instructions. However, plain multiply
229 // (low) operations are left as Legal, as there are single-result
230 // instructions for this in x86. Using the two-result multiply instructions
231 // when both high and low results are needed must be arranged by dagcombine.
232 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
233 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
234 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
235 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
236 setOperationAction(ISD::SREM , MVT::i8 , Expand);
237 setOperationAction(ISD::UREM , MVT::i8 , Expand);
238 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
239 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
240 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
241 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
242 setOperationAction(ISD::SREM , MVT::i16 , Expand);
243 setOperationAction(ISD::UREM , MVT::i16 , Expand);
244 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
245 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
246 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
247 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
248 setOperationAction(ISD::SREM , MVT::i32 , Expand);
249 setOperationAction(ISD::UREM , MVT::i32 , Expand);
250 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
251 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
252 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
253 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
254 setOperationAction(ISD::SREM , MVT::i64 , Expand);
255 setOperationAction(ISD::UREM , MVT::i64 , Expand);
257 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
258 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
259 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
260 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
261 if (Subtarget->is64Bit())
262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
266 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
267 setOperationAction(ISD::FREM , MVT::f32 , Expand);
268 setOperationAction(ISD::FREM , MVT::f64 , Expand);
269 setOperationAction(ISD::FREM , MVT::f80 , Expand);
270 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
272 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
273 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
274 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
275 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
276 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
277 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
278 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
279 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
280 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
281 if (Subtarget->is64Bit()) {
282 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
283 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
284 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
287 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
288 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
290 // These should be promoted to a larger select which is supported.
291 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
292 // X86 wants to expand cmov itself.
293 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
294 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
295 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
296 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
297 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
298 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
299 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
300 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
301 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
302 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
303 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
304 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
305 if (Subtarget->is64Bit()) {
306 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
307 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
309 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
312 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
313 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
314 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
315 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
316 if (Subtarget->is64Bit())
317 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
318 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
319 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
320 if (Subtarget->is64Bit()) {
321 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
322 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
323 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
324 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
325 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
327 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
328 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
329 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
330 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
331 if (Subtarget->is64Bit()) {
332 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
333 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
334 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
337 if (Subtarget->hasSSE1())
338 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
340 if (!Subtarget->hasSSE2())
341 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
343 // Expand certain atomics
344 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
345 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
346 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
347 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
349 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
350 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
351 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
352 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
354 if (!Subtarget->is64Bit()) {
355 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
356 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
357 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
358 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
359 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
360 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
361 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
364 // FIXME - use subtarget debug flags
365 if (!Subtarget->isTargetDarwin() &&
366 !Subtarget->isTargetELF() &&
367 !Subtarget->isTargetCygMing()) {
368 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
371 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
372 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
373 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
374 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
375 if (Subtarget->is64Bit()) {
376 setExceptionPointerRegister(X86::RAX);
377 setExceptionSelectorRegister(X86::RDX);
379 setExceptionPointerRegister(X86::EAX);
380 setExceptionSelectorRegister(X86::EDX);
382 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
383 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
385 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
387 setOperationAction(ISD::TRAP, MVT::Other, Legal);
389 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
390 setOperationAction(ISD::VASTART , MVT::Other, Custom);
391 setOperationAction(ISD::VAEND , MVT::Other, Expand);
392 if (Subtarget->is64Bit()) {
393 setOperationAction(ISD::VAARG , MVT::Other, Custom);
394 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
396 setOperationAction(ISD::VAARG , MVT::Other, Expand);
397 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
400 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
401 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
402 if (Subtarget->is64Bit())
403 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
404 if (Subtarget->isTargetCygMing())
405 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
407 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
409 if (!UseSoftFloat && X86ScalarSSEf64) {
410 // f32 and f64 use SSE.
411 // Set up the FP register classes.
412 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
413 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
415 // Use ANDPD to simulate FABS.
416 setOperationAction(ISD::FABS , MVT::f64, Custom);
417 setOperationAction(ISD::FABS , MVT::f32, Custom);
419 // Use XORP to simulate FNEG.
420 setOperationAction(ISD::FNEG , MVT::f64, Custom);
421 setOperationAction(ISD::FNEG , MVT::f32, Custom);
423 // Use ANDPD and ORPD to simulate FCOPYSIGN.
424 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
425 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
427 // We don't support sin/cos/fmod
428 setOperationAction(ISD::FSIN , MVT::f64, Expand);
429 setOperationAction(ISD::FCOS , MVT::f64, Expand);
430 setOperationAction(ISD::FSIN , MVT::f32, Expand);
431 setOperationAction(ISD::FCOS , MVT::f32, Expand);
433 // Expand FP immediates into loads from the stack, except for the special
435 addLegalFPImmediate(APFloat(+0.0)); // xorpd
436 addLegalFPImmediate(APFloat(+0.0f)); // xorps
437 } else if (!UseSoftFloat && X86ScalarSSEf32) {
438 // Use SSE for f32, x87 for f64.
439 // Set up the FP register classes.
440 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
441 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
443 // Use ANDPS to simulate FABS.
444 setOperationAction(ISD::FABS , MVT::f32, Custom);
446 // Use XORP to simulate FNEG.
447 setOperationAction(ISD::FNEG , MVT::f32, Custom);
449 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
451 // Use ANDPS and ORPS to simulate FCOPYSIGN.
452 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
453 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
455 // We don't support sin/cos/fmod
456 setOperationAction(ISD::FSIN , MVT::f32, Expand);
457 setOperationAction(ISD::FCOS , MVT::f32, Expand);
459 // Special cases we handle for FP constants.
460 addLegalFPImmediate(APFloat(+0.0f)); // xorps
461 addLegalFPImmediate(APFloat(+0.0)); // FLD0
462 addLegalFPImmediate(APFloat(+1.0)); // FLD1
463 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
464 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
467 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
468 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
470 } else if (!UseSoftFloat) {
471 // f32 and f64 in x87.
472 // Set up the FP register classes.
473 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
474 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
476 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
477 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
478 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
479 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
482 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
483 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
485 addLegalFPImmediate(APFloat(+0.0)); // FLD0
486 addLegalFPImmediate(APFloat(+1.0)); // FLD1
487 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
488 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
489 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
495 // Long double always uses X87.
497 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
498 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
499 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
502 APFloat TmpFlt(+0.0);
503 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
505 addLegalFPImmediate(TmpFlt); // FLD0
507 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
508 APFloat TmpFlt2(+1.0);
509 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
511 addLegalFPImmediate(TmpFlt2); // FLD1
512 TmpFlt2.changeSign();
513 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
517 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
518 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
522 // Always use a library call for pow.
523 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
524 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
525 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
527 setOperationAction(ISD::FLOG, MVT::f80, Expand);
528 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
529 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
530 setOperationAction(ISD::FEXP, MVT::f80, Expand);
531 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
533 // First set operation action for all vector types to either promote
534 // (for widening) or expand (for scalarization). Then we will selectively
535 // turn on ones that can be effectively codegen'd.
536 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
537 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
538 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
553 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
554 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
587 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
591 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
592 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
593 setTruncStoreAction((MVT::SimpleValueType)VT,
594 (MVT::SimpleValueType)InnerVT, Expand);
595 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
596 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
597 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
600 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
601 // with -msoft-float, disable use of MMX as well.
602 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
603 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass, false);
604 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
605 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
606 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
607 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
609 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
610 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
611 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
612 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
614 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
615 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
616 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
617 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
619 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
620 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
622 setOperationAction(ISD::AND, MVT::v8i8, Promote);
623 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
624 setOperationAction(ISD::AND, MVT::v4i16, Promote);
625 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
626 setOperationAction(ISD::AND, MVT::v2i32, Promote);
627 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
628 setOperationAction(ISD::AND, MVT::v1i64, Legal);
630 setOperationAction(ISD::OR, MVT::v8i8, Promote);
631 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
632 setOperationAction(ISD::OR, MVT::v4i16, Promote);
633 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
634 setOperationAction(ISD::OR, MVT::v2i32, Promote);
635 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
636 setOperationAction(ISD::OR, MVT::v1i64, Legal);
638 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
639 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
640 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
641 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
642 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
643 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
644 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
646 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
647 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
648 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
649 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
650 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
651 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
652 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
653 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
654 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
656 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
657 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
659 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
662 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
663 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
667 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
669 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
672 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
674 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
675 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
676 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
677 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
678 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
679 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
680 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
683 if (!UseSoftFloat && Subtarget->hasSSE1()) {
684 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
686 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
687 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
688 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
689 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
690 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
691 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
692 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
693 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
694 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
695 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
696 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
697 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
700 if (!UseSoftFloat && Subtarget->hasSSE2()) {
701 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
703 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
704 // registers cannot be used even for integer operations.
705 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
706 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
707 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
708 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
710 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
711 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
712 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
713 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
714 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
715 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
716 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
717 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
718 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
719 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
720 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
721 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
722 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
723 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
724 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
725 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
727 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
728 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
729 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
730 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
732 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
733 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
734 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
735 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
738 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
739 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
740 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
741 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
742 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
744 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
745 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
746 EVT VT = (MVT::SimpleValueType)i;
747 // Do not attempt to custom lower non-power-of-2 vectors
748 if (!isPowerOf2_32(VT.getVectorNumElements()))
750 // Do not attempt to custom lower non-128-bit vectors
751 if (!VT.is128BitVector())
753 setOperationAction(ISD::BUILD_VECTOR,
754 VT.getSimpleVT().SimpleTy, Custom);
755 setOperationAction(ISD::VECTOR_SHUFFLE,
756 VT.getSimpleVT().SimpleTy, Custom);
757 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
758 VT.getSimpleVT().SimpleTy, Custom);
761 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
762 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
763 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
764 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
765 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
766 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
768 if (Subtarget->is64Bit()) {
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
773 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
774 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
775 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
778 // Do not attempt to promote non-128-bit vectors
779 if (!VT.is128BitVector()) {
783 setOperationAction(ISD::AND, SVT, Promote);
784 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
785 setOperationAction(ISD::OR, SVT, Promote);
786 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
787 setOperationAction(ISD::XOR, SVT, Promote);
788 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
789 setOperationAction(ISD::LOAD, SVT, Promote);
790 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
791 setOperationAction(ISD::SELECT, SVT, Promote);
792 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
795 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
797 // Custom lower v2i64 and v2f64 selects.
798 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
799 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
800 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
801 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
803 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
804 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
805 if (!DisableMMX && Subtarget->hasMMX()) {
806 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
807 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
811 if (Subtarget->hasSSE41()) {
812 // FIXME: Do we need to handle scalar-to-vector here?
813 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
815 // i8 and i16 vectors are custom , because the source register and source
816 // source memory operand types are not the same width. f32 vectors are
817 // custom since the immediate controlling the insert encodes additional
819 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
820 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
821 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
822 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
824 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
826 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
827 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
829 if (Subtarget->is64Bit()) {
830 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
831 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
835 if (Subtarget->hasSSE42()) {
836 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
839 if (!UseSoftFloat && Subtarget->hasAVX()) {
840 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
841 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
842 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
843 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
845 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
846 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
847 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
848 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
849 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
850 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
851 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
852 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
853 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
854 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
855 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
856 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
857 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
858 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
859 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
861 // Operations to consider commented out -v16i16 v32i8
862 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
863 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
864 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
865 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
866 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
867 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
868 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
869 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
870 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
871 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
872 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
873 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
874 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
875 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
877 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
878 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
879 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
880 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
882 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
883 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
884 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
885 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
888 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
889 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
890 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
891 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
892 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
893 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
896 // Not sure we want to do this since there are no 256-bit integer
899 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900 // This includes 256-bit vectors
901 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
902 EVT VT = (MVT::SimpleValueType)i;
904 // Do not attempt to custom lower non-power-of-2 vectors
905 if (!isPowerOf2_32(VT.getVectorNumElements()))
908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
913 if (Subtarget->is64Bit()) {
914 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
915 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
920 // Not sure we want to do this since there are no 256-bit integer
923 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
924 // Including 256-bit vectors
925 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
926 EVT VT = (MVT::SimpleValueType)i;
928 if (!VT.is256BitVector()) {
931 setOperationAction(ISD::AND, VT, Promote);
932 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
933 setOperationAction(ISD::OR, VT, Promote);
934 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
935 setOperationAction(ISD::XOR, VT, Promote);
936 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
937 setOperationAction(ISD::LOAD, VT, Promote);
938 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
939 setOperationAction(ISD::SELECT, VT, Promote);
940 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
943 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
947 // We want to custom lower some of our intrinsics.
948 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
950 // Add/Sub/Mul with overflow operations are custom lowered.
951 setOperationAction(ISD::SADDO, MVT::i32, Custom);
952 setOperationAction(ISD::SADDO, MVT::i64, Custom);
953 setOperationAction(ISD::UADDO, MVT::i32, Custom);
954 setOperationAction(ISD::UADDO, MVT::i64, Custom);
955 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
956 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
957 setOperationAction(ISD::USUBO, MVT::i32, Custom);
958 setOperationAction(ISD::USUBO, MVT::i64, Custom);
959 setOperationAction(ISD::SMULO, MVT::i32, Custom);
960 setOperationAction(ISD::SMULO, MVT::i64, Custom);
962 if (!Subtarget->is64Bit()) {
963 // These libcalls are not available in 32-bit.
964 setLibcallName(RTLIB::SHL_I128, 0);
965 setLibcallName(RTLIB::SRL_I128, 0);
966 setLibcallName(RTLIB::SRA_I128, 0);
969 // We have target-specific dag combine patterns for the following nodes:
970 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
971 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
972 setTargetDAGCombine(ISD::BUILD_VECTOR);
973 setTargetDAGCombine(ISD::SELECT);
974 setTargetDAGCombine(ISD::SHL);
975 setTargetDAGCombine(ISD::SRA);
976 setTargetDAGCombine(ISD::SRL);
977 setTargetDAGCombine(ISD::OR);
978 setTargetDAGCombine(ISD::STORE);
979 setTargetDAGCombine(ISD::MEMBARRIER);
980 setTargetDAGCombine(ISD::ZERO_EXTEND);
981 if (Subtarget->is64Bit())
982 setTargetDAGCombine(ISD::MUL);
984 computeRegisterProperties();
986 // FIXME: These should be based on subtarget info. Plus, the values should
987 // be smaller when we are in optimizing for size mode.
988 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
989 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
990 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
991 setPrefLoopAlignment(16);
992 benefitFromCodePlacementOpt = true;
996 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1001 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1002 /// the desired ByVal argument alignment.
1003 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1006 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1007 if (VTy->getBitWidth() == 128)
1009 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1010 unsigned EltAlign = 0;
1011 getMaxByValAlign(ATy->getElementType(), EltAlign);
1012 if (EltAlign > MaxAlign)
1013 MaxAlign = EltAlign;
1014 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1015 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1016 unsigned EltAlign = 0;
1017 getMaxByValAlign(STy->getElementType(i), EltAlign);
1018 if (EltAlign > MaxAlign)
1019 MaxAlign = EltAlign;
1027 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1028 /// function arguments in the caller parameter area. For X86, aggregates
1029 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1030 /// are at 4-byte boundaries.
1031 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1032 if (Subtarget->is64Bit()) {
1033 // Max of 8 and alignment of type.
1034 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1041 if (Subtarget->hasSSE1())
1042 getMaxByValAlign(Ty, Align);
1046 /// getOptimalMemOpType - Returns the target specific optimal type for load
1047 /// and store operations as a result of memset, memcpy, and memmove
1048 /// lowering. If DstAlign is zero that means it's safe to destination
1049 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1050 /// means there isn't a need to check it against alignment requirement,
1051 /// probably because the source does not need to be loaded. If
1052 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1053 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1054 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1055 /// constant so it does not need to be loaded.
1056 /// It returns EVT::Other if the type should be determined using generic
1057 /// target-independent logic.
1059 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1060 unsigned DstAlign, unsigned SrcAlign,
1061 bool NonScalarIntSafe,
1063 MachineFunction &MF) const {
1064 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1065 // linux. This is because the stack realignment code can't handle certain
1066 // cases like PR2962. This should be removed when PR2962 is fixed.
1067 const Function *F = MF.getFunction();
1068 if (NonScalarIntSafe &&
1069 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1071 (Subtarget->isUnalignedMemAccessFast() ||
1072 ((DstAlign == 0 || DstAlign >= 16) &&
1073 (SrcAlign == 0 || SrcAlign >= 16))) &&
1074 Subtarget->getStackAlignment() >= 16) {
1075 if (Subtarget->hasSSE2())
1077 if (Subtarget->hasSSE1())
1079 } else if (!MemcpyStrSrc && Size >= 8 &&
1080 !Subtarget->is64Bit() &&
1081 Subtarget->getStackAlignment() >= 8 &&
1082 Subtarget->hasSSE2()) {
1083 // Do not use f64 to lower memcpy if source is string constant. It's
1084 // better to use i32 to avoid the loads.
1088 if (Subtarget->is64Bit() && Size >= 8)
1093 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1094 /// current function. The returned value is a member of the
1095 /// MachineJumpTableInfo::JTEntryKind enum.
1096 unsigned X86TargetLowering::getJumpTableEncoding() const {
1097 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1099 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1100 Subtarget->isPICStyleGOT())
1101 return MachineJumpTableInfo::EK_Custom32;
1103 // Otherwise, use the normal jump table encoding heuristics.
1104 return TargetLowering::getJumpTableEncoding();
1107 /// getPICBaseSymbol - Return the X86-32 PIC base.
1109 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1110 MCContext &Ctx) const {
1111 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1112 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1113 Twine(MF->getFunctionNumber())+"$pb");
1118 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1119 const MachineBasicBlock *MBB,
1120 unsigned uid,MCContext &Ctx) const{
1121 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1122 Subtarget->isPICStyleGOT());
1123 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1125 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1126 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1129 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1131 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1132 SelectionDAG &DAG) const {
1133 if (!Subtarget->is64Bit())
1134 // This doesn't have DebugLoc associated with it, but is not really the
1135 // same as a Register.
1136 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1140 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1141 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1143 const MCExpr *X86TargetLowering::
1144 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1145 MCContext &Ctx) const {
1146 // X86-64 uses RIP relative addressing based on the jump table label.
1147 if (Subtarget->isPICStyleRIPRel())
1148 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1150 // Otherwise, the reference is relative to the PIC base.
1151 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1154 /// getFunctionAlignment - Return the Log2 alignment of this function.
1155 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1156 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1159 //===----------------------------------------------------------------------===//
1160 // Return Value Calling Convention Implementation
1161 //===----------------------------------------------------------------------===//
1163 #include "X86GenCallingConv.inc"
1166 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1167 const SmallVectorImpl<EVT> &OutTys,
1168 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1169 SelectionDAG &DAG) const {
1170 SmallVector<CCValAssign, 16> RVLocs;
1171 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1172 RVLocs, *DAG.getContext());
1173 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1177 X86TargetLowering::LowerReturn(SDValue Chain,
1178 CallingConv::ID CallConv, bool isVarArg,
1179 const SmallVectorImpl<ISD::OutputArg> &Outs,
1180 DebugLoc dl, SelectionDAG &DAG) const {
1181 MachineFunction &MF = DAG.getMachineFunction();
1182 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1184 SmallVector<CCValAssign, 16> RVLocs;
1185 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1186 RVLocs, *DAG.getContext());
1187 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1189 // Add the regs to the liveout set for the function.
1190 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1191 for (unsigned i = 0; i != RVLocs.size(); ++i)
1192 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1193 MRI.addLiveOut(RVLocs[i].getLocReg());
1197 SmallVector<SDValue, 6> RetOps;
1198 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1199 // Operand #1 = Bytes To Pop
1200 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1203 // Copy the result values into the output registers.
1204 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1205 CCValAssign &VA = RVLocs[i];
1206 assert(VA.isRegLoc() && "Can only return in registers!");
1207 SDValue ValToCopy = Outs[i].Val;
1209 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1210 // the RET instruction and handled by the FP Stackifier.
1211 if (VA.getLocReg() == X86::ST0 ||
1212 VA.getLocReg() == X86::ST1) {
1213 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1214 // change the value to the FP stack register class.
1215 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1216 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1217 RetOps.push_back(ValToCopy);
1218 // Don't emit a copytoreg.
1222 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1223 // which is returned in RAX / RDX.
1224 if (Subtarget->is64Bit()) {
1225 EVT ValVT = ValToCopy.getValueType();
1226 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1227 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1228 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1229 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1233 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1234 Flag = Chain.getValue(1);
1237 // The x86-64 ABI for returning structs by value requires that we copy
1238 // the sret argument into %rax for the return. We saved the argument into
1239 // a virtual register in the entry block, so now we copy the value out
1241 if (Subtarget->is64Bit() &&
1242 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1243 MachineFunction &MF = DAG.getMachineFunction();
1244 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1245 unsigned Reg = FuncInfo->getSRetReturnReg();
1247 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1248 FuncInfo->setSRetReturnReg(Reg);
1250 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1252 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1253 Flag = Chain.getValue(1);
1255 // RAX now acts like a return value.
1256 MRI.addLiveOut(X86::RAX);
1259 RetOps[0] = Chain; // Update chain.
1261 // Add the flag if we have it.
1263 RetOps.push_back(Flag);
1265 return DAG.getNode(X86ISD::RET_FLAG, dl,
1266 MVT::Other, &RetOps[0], RetOps.size());
1269 /// LowerCallResult - Lower the result values of a call into the
1270 /// appropriate copies out of appropriate physical registers.
1273 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1274 CallingConv::ID CallConv, bool isVarArg,
1275 const SmallVectorImpl<ISD::InputArg> &Ins,
1276 DebugLoc dl, SelectionDAG &DAG,
1277 SmallVectorImpl<SDValue> &InVals) const {
1279 // Assign locations to each value returned by this call.
1280 SmallVector<CCValAssign, 16> RVLocs;
1281 bool Is64Bit = Subtarget->is64Bit();
1282 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1283 RVLocs, *DAG.getContext());
1284 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1286 // Copy all of the result registers out of their specified physreg.
1287 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1288 CCValAssign &VA = RVLocs[i];
1289 EVT CopyVT = VA.getValVT();
1291 // If this is x86-64, and we disabled SSE, we can't return FP values
1292 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1293 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1294 report_fatal_error("SSE register return with SSE disabled");
1297 // If this is a call to a function that returns an fp value on the floating
1298 // point stack, but where we prefer to use the value in xmm registers, copy
1299 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1300 if ((VA.getLocReg() == X86::ST0 ||
1301 VA.getLocReg() == X86::ST1) &&
1302 isScalarFPTypeInSSEReg(VA.getValVT())) {
1307 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1308 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1309 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1310 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1311 MVT::v2i64, InFlag).getValue(1);
1312 Val = Chain.getValue(0);
1313 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1314 Val, DAG.getConstant(0, MVT::i64));
1316 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1317 MVT::i64, InFlag).getValue(1);
1318 Val = Chain.getValue(0);
1320 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1322 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1323 CopyVT, InFlag).getValue(1);
1324 Val = Chain.getValue(0);
1326 InFlag = Chain.getValue(2);
1328 if (CopyVT != VA.getValVT()) {
1329 // Round the F80 the right size, which also moves to the appropriate xmm
1331 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1332 // This truncation won't change the value.
1333 DAG.getIntPtrConstant(1));
1336 InVals.push_back(Val);
1343 //===----------------------------------------------------------------------===//
1344 // C & StdCall & Fast Calling Convention implementation
1345 //===----------------------------------------------------------------------===//
1346 // StdCall calling convention seems to be standard for many Windows' API
1347 // routines and around. It differs from C calling convention just a little:
1348 // callee should clean up the stack, not caller. Symbols should be also
1349 // decorated in some fancy way :) It doesn't support any vector arguments.
1350 // For info on fast calling convention see Fast Calling Convention (tail call)
1351 // implementation LowerX86_32FastCCCallTo.
1353 /// CallIsStructReturn - Determines whether a call uses struct return
1355 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1359 return Outs[0].Flags.isSRet();
1362 /// ArgsAreStructReturn - Determines whether a function uses struct
1363 /// return semantics.
1365 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1369 return Ins[0].Flags.isSRet();
1372 /// IsCalleePop - Determines whether the callee is required to pop its
1373 /// own arguments. Callee pop is necessary to support tail calls.
1374 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1375 CallingConv::ID CallingConv) const {
1379 switch (CallingConv) {
1382 case CallingConv::X86_StdCall:
1383 return !Subtarget->is64Bit();
1384 case CallingConv::X86_FastCall:
1385 return !Subtarget->is64Bit();
1386 case CallingConv::X86_ThisCall:
1387 return !Subtarget->is64Bit();
1388 case CallingConv::Fast:
1389 return GuaranteedTailCallOpt;
1390 case CallingConv::GHC:
1391 return GuaranteedTailCallOpt;
1395 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1396 /// given CallingConvention value.
1397 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1398 if (Subtarget->is64Bit()) {
1399 if (CC == CallingConv::GHC)
1400 return CC_X86_64_GHC;
1401 else if (Subtarget->isTargetWin64())
1402 return CC_X86_Win64_C;
1407 if (CC == CallingConv::X86_FastCall)
1408 return CC_X86_32_FastCall;
1409 else if (CC == CallingConv::X86_ThisCall)
1410 return CC_X86_32_ThisCall;
1411 else if (CC == CallingConv::Fast)
1412 return CC_X86_32_FastCC;
1413 else if (CC == CallingConv::GHC)
1414 return CC_X86_32_GHC;
1419 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1420 /// by "Src" to address "Dst" with size and alignment information specified by
1421 /// the specific parameter attribute. The copy will be passed as a byval
1422 /// function parameter.
1424 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1425 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1427 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1428 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1429 /*isVolatile*/false, /*AlwaysInline=*/true,
1433 /// IsTailCallConvention - Return true if the calling convention is one that
1434 /// supports tail call optimization.
1435 static bool IsTailCallConvention(CallingConv::ID CC) {
1436 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1439 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1440 /// a tailcall target by changing its ABI.
1441 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1442 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1446 X86TargetLowering::LowerMemArgument(SDValue Chain,
1447 CallingConv::ID CallConv,
1448 const SmallVectorImpl<ISD::InputArg> &Ins,
1449 DebugLoc dl, SelectionDAG &DAG,
1450 const CCValAssign &VA,
1451 MachineFrameInfo *MFI,
1453 // Create the nodes corresponding to a load from this parameter slot.
1454 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1455 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1456 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1459 // If value is passed by pointer we have address passed instead of the value
1461 if (VA.getLocInfo() == CCValAssign::Indirect)
1462 ValVT = VA.getLocVT();
1464 ValVT = VA.getValVT();
1466 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1467 // changed with more analysis.
1468 // In case of tail call optimization mark all arguments mutable. Since they
1469 // could be overwritten by lowering of arguments in case of a tail call.
1470 if (Flags.isByVal()) {
1471 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1472 VA.getLocMemOffset(), isImmutable, false);
1473 return DAG.getFrameIndex(FI, getPointerTy());
1475 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1476 VA.getLocMemOffset(), isImmutable, false);
1477 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1478 return DAG.getLoad(ValVT, dl, Chain, FIN,
1479 PseudoSourceValue::getFixedStack(FI), 0,
1485 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1486 CallingConv::ID CallConv,
1488 const SmallVectorImpl<ISD::InputArg> &Ins,
1491 SmallVectorImpl<SDValue> &InVals)
1493 MachineFunction &MF = DAG.getMachineFunction();
1494 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1496 const Function* Fn = MF.getFunction();
1497 if (Fn->hasExternalLinkage() &&
1498 Subtarget->isTargetCygMing() &&
1499 Fn->getName() == "main")
1500 FuncInfo->setForceFramePointer(true);
1502 MachineFrameInfo *MFI = MF.getFrameInfo();
1503 bool Is64Bit = Subtarget->is64Bit();
1504 bool IsWin64 = Subtarget->isTargetWin64();
1506 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1507 "Var args not supported with calling convention fastcc or ghc");
1509 // Assign locations to all of the incoming arguments.
1510 SmallVector<CCValAssign, 16> ArgLocs;
1511 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1512 ArgLocs, *DAG.getContext());
1513 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1515 unsigned LastVal = ~0U;
1517 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1518 CCValAssign &VA = ArgLocs[i];
1519 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1521 assert(VA.getValNo() != LastVal &&
1522 "Don't support value assigned to multiple locs yet");
1523 LastVal = VA.getValNo();
1525 if (VA.isRegLoc()) {
1526 EVT RegVT = VA.getLocVT();
1527 TargetRegisterClass *RC = NULL;
1528 if (RegVT == MVT::i32)
1529 RC = X86::GR32RegisterClass;
1530 else if (Is64Bit && RegVT == MVT::i64)
1531 RC = X86::GR64RegisterClass;
1532 else if (RegVT == MVT::f32)
1533 RC = X86::FR32RegisterClass;
1534 else if (RegVT == MVT::f64)
1535 RC = X86::FR64RegisterClass;
1536 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1537 RC = X86::VR128RegisterClass;
1538 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1539 RC = X86::VR64RegisterClass;
1541 llvm_unreachable("Unknown argument type!");
1543 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1544 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1546 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1547 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1549 if (VA.getLocInfo() == CCValAssign::SExt)
1550 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1551 DAG.getValueType(VA.getValVT()));
1552 else if (VA.getLocInfo() == CCValAssign::ZExt)
1553 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1554 DAG.getValueType(VA.getValVT()));
1555 else if (VA.getLocInfo() == CCValAssign::BCvt)
1556 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1558 if (VA.isExtInLoc()) {
1559 // Handle MMX values passed in XMM regs.
1560 if (RegVT.isVector()) {
1561 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1562 ArgValue, DAG.getConstant(0, MVT::i64));
1563 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1565 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1568 assert(VA.isMemLoc());
1569 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1572 // If value is passed via pointer - do a load.
1573 if (VA.getLocInfo() == CCValAssign::Indirect)
1574 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1577 InVals.push_back(ArgValue);
1580 // The x86-64 ABI for returning structs by value requires that we copy
1581 // the sret argument into %rax for the return. Save the argument into
1582 // a virtual register so that we can access it from the return points.
1583 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1584 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1585 unsigned Reg = FuncInfo->getSRetReturnReg();
1587 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1588 FuncInfo->setSRetReturnReg(Reg);
1590 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1591 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1594 unsigned StackSize = CCInfo.getNextStackOffset();
1595 // Align stack specially for tail calls.
1596 if (FuncIsMadeTailCallSafe(CallConv))
1597 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1599 // If the function takes variable number of arguments, make a frame index for
1600 // the start of the first vararg value... for expansion of llvm.va_start.
1602 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1603 CallConv != CallingConv::X86_ThisCall)) {
1604 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1608 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1610 // FIXME: We should really autogenerate these arrays
1611 static const unsigned GPR64ArgRegsWin64[] = {
1612 X86::RCX, X86::RDX, X86::R8, X86::R9
1614 static const unsigned XMMArgRegsWin64[] = {
1615 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1617 static const unsigned GPR64ArgRegs64Bit[] = {
1618 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1620 static const unsigned XMMArgRegs64Bit[] = {
1621 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1622 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1624 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1627 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1628 GPR64ArgRegs = GPR64ArgRegsWin64;
1629 XMMArgRegs = XMMArgRegsWin64;
1631 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1632 GPR64ArgRegs = GPR64ArgRegs64Bit;
1633 XMMArgRegs = XMMArgRegs64Bit;
1635 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1637 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1640 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1641 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1642 "SSE register cannot be used when SSE is disabled!");
1643 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1644 "SSE register cannot be used when SSE is disabled!");
1645 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1646 // Kernel mode asks for SSE to be disabled, so don't push them
1648 TotalNumXMMRegs = 0;
1650 // For X86-64, if there are vararg parameters that are passed via
1651 // registers, then we must store them to their spots on the stack so they
1652 // may be loaded by deferencing the result of va_next.
1653 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1654 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1655 FuncInfo->setRegSaveFrameIndex(
1656 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1659 // Store the integer parameter registers.
1660 SmallVector<SDValue, 8> MemOps;
1661 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1663 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1664 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1665 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1666 DAG.getIntPtrConstant(Offset));
1667 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1668 X86::GR64RegisterClass);
1669 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1671 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1672 PseudoSourceValue::getFixedStack(
1673 FuncInfo->getRegSaveFrameIndex()),
1674 Offset, false, false, 0);
1675 MemOps.push_back(Store);
1679 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1680 // Now store the XMM (fp + vector) parameter registers.
1681 SmallVector<SDValue, 11> SaveXMMOps;
1682 SaveXMMOps.push_back(Chain);
1684 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1685 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1686 SaveXMMOps.push_back(ALVal);
1688 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1689 FuncInfo->getRegSaveFrameIndex()));
1690 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1691 FuncInfo->getVarArgsFPOffset()));
1693 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1694 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1695 X86::VR128RegisterClass);
1696 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1697 SaveXMMOps.push_back(Val);
1699 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1701 &SaveXMMOps[0], SaveXMMOps.size()));
1704 if (!MemOps.empty())
1705 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1706 &MemOps[0], MemOps.size());
1710 // Some CCs need callee pop.
1711 if (IsCalleePop(isVarArg, CallConv)) {
1712 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1714 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1715 // If this is an sret function, the return should pop the hidden pointer.
1716 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1717 FuncInfo->setBytesToPopOnReturn(4);
1721 // RegSaveFrameIndex is X86-64 only.
1722 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1723 if (CallConv == CallingConv::X86_FastCall ||
1724 CallConv == CallingConv::X86_ThisCall)
1725 // fastcc functions can't have varargs.
1726 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1733 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1734 SDValue StackPtr, SDValue Arg,
1735 DebugLoc dl, SelectionDAG &DAG,
1736 const CCValAssign &VA,
1737 ISD::ArgFlagsTy Flags) const {
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) const {
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) const {
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(), getPointerTy()),
1936 InFlag = Chain.getValue(1);
1938 // If we are tail calling and generating PIC/GOT style code load the
1939 // address of the callee into ECX. The value in ecx is used as target of
1940 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1941 // for tail calls on PIC/GOT architectures. Normally we would just put the
1942 // address of GOT into ebx and then call target@PLT. But for tail calls
1943 // ebx would be restored (since ebx is callee saved) before jumping to the
1946 // Note: The actual moving to ECX is done further down.
1947 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1948 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1949 !G->getGlobal()->hasProtectedVisibility())
1950 Callee = LowerGlobalAddress(Callee, DAG);
1951 else if (isa<ExternalSymbolSDNode>(Callee))
1952 Callee = LowerExternalSymbol(Callee, DAG);
1956 if (Is64Bit && isVarArg) {
1957 // From AMD64 ABI document:
1958 // For calls that may call functions that use varargs or stdargs
1959 // (prototype-less calls or calls to functions containing ellipsis (...) in
1960 // the declaration) %al is used as hidden argument to specify the number
1961 // of SSE registers used. The contents of %al do not need to match exactly
1962 // the number of registers, but must be an ubound on the number of SSE
1963 // registers used and is in the range 0 - 8 inclusive.
1965 // FIXME: Verify this on Win64
1966 // Count the number of XMM registers allocated.
1967 static const unsigned XMMArgRegs[] = {
1968 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1969 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1971 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1972 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1973 && "SSE registers cannot be used when SSE is disabled");
1975 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1976 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1977 InFlag = Chain.getValue(1);
1981 // For tail calls lower the arguments to the 'real' stack slot.
1983 // Force all the incoming stack arguments to be loaded from the stack
1984 // before any new outgoing arguments are stored to the stack, because the
1985 // outgoing stack slots may alias the incoming argument stack slots, and
1986 // the alias isn't otherwise explicit. This is slightly more conservative
1987 // than necessary, because it means that each store effectively depends
1988 // on every argument instead of just those arguments it would clobber.
1989 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1991 SmallVector<SDValue, 8> MemOpChains2;
1994 // Do not flag preceeding copytoreg stuff together with the following stuff.
1996 if (GuaranteedTailCallOpt) {
1997 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1998 CCValAssign &VA = ArgLocs[i];
2001 assert(VA.isMemLoc());
2002 SDValue Arg = Outs[i].Val;
2003 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2004 // Create frame index.
2005 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2006 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2007 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2008 FIN = DAG.getFrameIndex(FI, getPointerTy());
2010 if (Flags.isByVal()) {
2011 // Copy relative to framepointer.
2012 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2013 if (StackPtr.getNode() == 0)
2014 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2016 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2018 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2022 // Store relative to framepointer.
2023 MemOpChains2.push_back(
2024 DAG.getStore(ArgChain, dl, Arg, FIN,
2025 PseudoSourceValue::getFixedStack(FI), 0,
2031 if (!MemOpChains2.empty())
2032 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2033 &MemOpChains2[0], MemOpChains2.size());
2035 // Copy arguments to their registers.
2036 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2037 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2038 RegsToPass[i].second, InFlag);
2039 InFlag = Chain.getValue(1);
2043 // Store the return address to the appropriate stack slot.
2044 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2048 bool WasGlobalOrExternal = false;
2049 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2050 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2051 // In the 64-bit large code model, we have to make all calls
2052 // through a register, since the call instruction's 32-bit
2053 // pc-relative offset may not be large enough to hold the whole
2055 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2056 WasGlobalOrExternal = true;
2057 // If the callee is a GlobalAddress node (quite common, every direct call
2058 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2061 // We should use extra load for direct calls to dllimported functions in
2063 const GlobalValue *GV = G->getGlobal();
2064 if (!GV->hasDLLImportLinkage()) {
2065 unsigned char OpFlags = 0;
2067 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2068 // external symbols most go through the PLT in PIC mode. If the symbol
2069 // has hidden or protected visibility, or if it is static or local, then
2070 // we don't need to use the PLT - we can directly call it.
2071 if (Subtarget->isTargetELF() &&
2072 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2073 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2074 OpFlags = X86II::MO_PLT;
2075 } else if (Subtarget->isPICStyleStubAny() &&
2076 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2077 Subtarget->getDarwinVers() < 9) {
2078 // PC-relative references to external symbols should go through $stub,
2079 // unless we're building with the leopard linker or later, which
2080 // automatically synthesizes these stubs.
2081 OpFlags = X86II::MO_DARWIN_STUB;
2084 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2085 G->getOffset(), OpFlags);
2087 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2088 WasGlobalOrExternal = true;
2089 unsigned char OpFlags = 0;
2091 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2092 // symbols should go through the PLT.
2093 if (Subtarget->isTargetELF() &&
2094 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2095 OpFlags = X86II::MO_PLT;
2096 } else if (Subtarget->isPICStyleStubAny() &&
2097 Subtarget->getDarwinVers() < 9) {
2098 // PC-relative references to external symbols should go through $stub,
2099 // unless we're building with the leopard linker or later, which
2100 // automatically synthesizes these stubs.
2101 OpFlags = X86II::MO_DARWIN_STUB;
2104 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2108 // Returns a chain & a flag for retval copy to use.
2109 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2110 SmallVector<SDValue, 8> Ops;
2112 if (!IsSibcall && isTailCall) {
2113 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2114 DAG.getIntPtrConstant(0, true), InFlag);
2115 InFlag = Chain.getValue(1);
2118 Ops.push_back(Chain);
2119 Ops.push_back(Callee);
2122 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2124 // Add argument registers to the end of the list so that they are known live
2126 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2127 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2128 RegsToPass[i].second.getValueType()));
2130 // Add an implicit use GOT pointer in EBX.
2131 if (!isTailCall && Subtarget->isPICStyleGOT())
2132 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2134 // Add an implicit use of AL for x86 vararg functions.
2135 if (Is64Bit && isVarArg)
2136 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2138 if (InFlag.getNode())
2139 Ops.push_back(InFlag);
2142 // If this is the first return lowered for this function, add the regs
2143 // to the liveout set for the function.
2144 if (MF.getRegInfo().liveout_empty()) {
2145 SmallVector<CCValAssign, 16> RVLocs;
2146 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2148 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2149 for (unsigned i = 0; i != RVLocs.size(); ++i)
2150 if (RVLocs[i].isRegLoc())
2151 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2153 return DAG.getNode(X86ISD::TC_RETURN, dl,
2154 NodeTys, &Ops[0], Ops.size());
2157 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2158 InFlag = Chain.getValue(1);
2160 // Create the CALLSEQ_END node.
2161 unsigned NumBytesForCalleeToPush;
2162 if (IsCalleePop(isVarArg, CallConv))
2163 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2164 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2165 // If this is a call to a struct-return function, the callee
2166 // pops the hidden struct pointer, so we have to push it back.
2167 // This is common for Darwin/X86, Linux & Mingw32 targets.
2168 NumBytesForCalleeToPush = 4;
2170 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2172 // Returns a flag for retval copy to use.
2174 Chain = DAG.getCALLSEQ_END(Chain,
2175 DAG.getIntPtrConstant(NumBytes, true),
2176 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2179 InFlag = Chain.getValue(1);
2182 // Handle result values, copying them out of physregs into vregs that we
2184 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2185 Ins, dl, DAG, InVals);
2189 //===----------------------------------------------------------------------===//
2190 // Fast Calling Convention (tail call) implementation
2191 //===----------------------------------------------------------------------===//
2193 // Like std call, callee cleans arguments, convention except that ECX is
2194 // reserved for storing the tail called function address. Only 2 registers are
2195 // free for argument passing (inreg). Tail call optimization is performed
2197 // * tailcallopt is enabled
2198 // * caller/callee are fastcc
2199 // On X86_64 architecture with GOT-style position independent code only local
2200 // (within module) calls are supported at the moment.
2201 // To keep the stack aligned according to platform abi the function
2202 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2203 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2204 // If a tail called function callee has more arguments than the caller the
2205 // caller needs to make sure that there is room to move the RETADDR to. This is
2206 // achieved by reserving an area the size of the argument delta right after the
2207 // original REtADDR, but before the saved framepointer or the spilled registers
2208 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2220 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2221 /// for a 16 byte align requirement.
2223 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2224 SelectionDAG& DAG) const {
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 CallingConv::ID CallerCC = CallerF->getCallingConv();
2313 bool CCMatch = CallerCC == CalleeCC;
2315 if (GuaranteedTailCallOpt) {
2316 if (IsTailCallConvention(CalleeCC) && CCMatch)
2321 // Look for obvious safe cases to perform tail call optimization that does not
2322 // requite ABI changes. This is what gcc calls sibcall.
2324 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2325 // emit a special epilogue.
2326 if (RegInfo->needsStackRealignment(MF))
2329 // Do not sibcall optimize vararg calls unless the call site is not passing any
2331 if (isVarArg && !Outs.empty())
2334 // Also avoid sibcall optimization if either caller or callee uses struct
2335 // return semantics.
2336 if (isCalleeStructRet || isCallerStructRet)
2339 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2340 // Therefore if it's not used by the call it is not safe to optimize this into
2342 bool Unused = false;
2343 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2350 SmallVector<CCValAssign, 16> RVLocs;
2351 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2352 RVLocs, *DAG.getContext());
2353 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2354 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2355 CCValAssign &VA = RVLocs[i];
2356 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2361 // If the calling conventions do not match, then we'd better make sure the
2362 // results are returned in the same way as what the caller expects.
2364 SmallVector<CCValAssign, 16> RVLocs1;
2365 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2366 RVLocs1, *DAG.getContext());
2367 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2369 SmallVector<CCValAssign, 16> RVLocs2;
2370 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2371 RVLocs2, *DAG.getContext());
2372 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2374 if (RVLocs1.size() != RVLocs2.size())
2376 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2377 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2379 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2381 if (RVLocs1[i].isRegLoc()) {
2382 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2385 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2391 // If the callee takes no arguments then go on to check the results of the
2393 if (!Outs.empty()) {
2394 // Check if stack adjustment is needed. For now, do not do this if any
2395 // argument is passed on the stack.
2396 SmallVector<CCValAssign, 16> ArgLocs;
2397 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2398 ArgLocs, *DAG.getContext());
2399 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2400 if (CCInfo.getNextStackOffset()) {
2401 MachineFunction &MF = DAG.getMachineFunction();
2402 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2404 if (Subtarget->isTargetWin64())
2405 // Win64 ABI has additional complications.
2408 // Check if the arguments are already laid out in the right way as
2409 // the caller's fixed stack objects.
2410 MachineFrameInfo *MFI = MF.getFrameInfo();
2411 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2412 const X86InstrInfo *TII =
2413 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2414 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2415 CCValAssign &VA = ArgLocs[i];
2416 EVT RegVT = VA.getLocVT();
2417 SDValue Arg = Outs[i].Val;
2418 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2419 if (VA.getLocInfo() == CCValAssign::Indirect)
2421 if (!VA.isRegLoc()) {
2422 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2434 X86TargetLowering::createFastISel(MachineFunction &mf,
2435 DenseMap<const Value *, unsigned> &vm,
2436 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2437 DenseMap<const AllocaInst *, int> &am,
2438 std::vector<std::pair<MachineInstr*, unsigned> > &pn
2440 , SmallSet<const Instruction *, 8> &cil
2443 return X86::createFastISel(mf, vm, bm, am, pn
2451 //===----------------------------------------------------------------------===//
2452 // Other Lowering Hooks
2453 //===----------------------------------------------------------------------===//
2456 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2457 MachineFunction &MF = DAG.getMachineFunction();
2458 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2459 int ReturnAddrIndex = FuncInfo->getRAIndex();
2461 if (ReturnAddrIndex == 0) {
2462 // Set up a frame object for the return address.
2463 uint64_t SlotSize = TD->getPointerSize();
2464 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2466 FuncInfo->setRAIndex(ReturnAddrIndex);
2469 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2473 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2474 bool hasSymbolicDisplacement) {
2475 // Offset should fit into 32 bit immediate field.
2476 if (!isInt<32>(Offset))
2479 // If we don't have a symbolic displacement - we don't have any extra
2481 if (!hasSymbolicDisplacement)
2484 // FIXME: Some tweaks might be needed for medium code model.
2485 if (M != CodeModel::Small && M != CodeModel::Kernel)
2488 // For small code model we assume that latest object is 16MB before end of 31
2489 // bits boundary. We may also accept pretty large negative constants knowing
2490 // that all objects are in the positive half of address space.
2491 if (M == CodeModel::Small && Offset < 16*1024*1024)
2494 // For kernel code model we know that all object resist in the negative half
2495 // of 32bits address space. We may not accept negative offsets, since they may
2496 // be just off and we may accept pretty large positive ones.
2497 if (M == CodeModel::Kernel && Offset > 0)
2503 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2504 /// specific condition code, returning the condition code and the LHS/RHS of the
2505 /// comparison to make.
2506 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2507 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2509 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2510 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2511 // X > -1 -> X == 0, jump !sign.
2512 RHS = DAG.getConstant(0, RHS.getValueType());
2513 return X86::COND_NS;
2514 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2515 // X < 0 -> X == 0, jump on sign.
2517 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2519 RHS = DAG.getConstant(0, RHS.getValueType());
2520 return X86::COND_LE;
2524 switch (SetCCOpcode) {
2525 default: llvm_unreachable("Invalid integer condition!");
2526 case ISD::SETEQ: return X86::COND_E;
2527 case ISD::SETGT: return X86::COND_G;
2528 case ISD::SETGE: return X86::COND_GE;
2529 case ISD::SETLT: return X86::COND_L;
2530 case ISD::SETLE: return X86::COND_LE;
2531 case ISD::SETNE: return X86::COND_NE;
2532 case ISD::SETULT: return X86::COND_B;
2533 case ISD::SETUGT: return X86::COND_A;
2534 case ISD::SETULE: return X86::COND_BE;
2535 case ISD::SETUGE: return X86::COND_AE;
2539 // First determine if it is required or is profitable to flip the operands.
2541 // If LHS is a foldable load, but RHS is not, flip the condition.
2542 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2543 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2544 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2545 std::swap(LHS, RHS);
2548 switch (SetCCOpcode) {
2554 std::swap(LHS, RHS);
2558 // On a floating point condition, the flags are set as follows:
2560 // 0 | 0 | 0 | X > Y
2561 // 0 | 0 | 1 | X < Y
2562 // 1 | 0 | 0 | X == Y
2563 // 1 | 1 | 1 | unordered
2564 switch (SetCCOpcode) {
2565 default: llvm_unreachable("Condcode should be pre-legalized away");
2567 case ISD::SETEQ: return X86::COND_E;
2568 case ISD::SETOLT: // flipped
2570 case ISD::SETGT: return X86::COND_A;
2571 case ISD::SETOLE: // flipped
2573 case ISD::SETGE: return X86::COND_AE;
2574 case ISD::SETUGT: // flipped
2576 case ISD::SETLT: return X86::COND_B;
2577 case ISD::SETUGE: // flipped
2579 case ISD::SETLE: return X86::COND_BE;
2581 case ISD::SETNE: return X86::COND_NE;
2582 case ISD::SETUO: return X86::COND_P;
2583 case ISD::SETO: return X86::COND_NP;
2585 case ISD::SETUNE: return X86::COND_INVALID;
2589 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2590 /// code. Current x86 isa includes the following FP cmov instructions:
2591 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2592 static bool hasFPCMov(unsigned X86CC) {
2608 /// isFPImmLegal - Returns true if the target can instruction select the
2609 /// specified FP immediate natively. If false, the legalizer will
2610 /// materialize the FP immediate as a load from a constant pool.
2611 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2612 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2613 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2619 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2620 /// the specified range (L, H].
2621 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2622 return (Val < 0) || (Val >= Low && Val < Hi);
2625 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2626 /// specified value.
2627 static bool isUndefOrEqual(int Val, int CmpVal) {
2628 if (Val < 0 || Val == CmpVal)
2633 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2634 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2635 /// the second operand.
2636 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2637 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2638 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2639 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2640 return (Mask[0] < 2 && Mask[1] < 2);
2644 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2645 SmallVector<int, 8> M;
2647 return ::isPSHUFDMask(M, N->getValueType(0));
2650 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2651 /// is suitable for input to PSHUFHW.
2652 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2653 if (VT != MVT::v8i16)
2656 // Lower quadword copied in order or undef.
2657 for (int i = 0; i != 4; ++i)
2658 if (Mask[i] >= 0 && Mask[i] != i)
2661 // Upper quadword shuffled.
2662 for (int i = 4; i != 8; ++i)
2663 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2669 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2670 SmallVector<int, 8> M;
2672 return ::isPSHUFHWMask(M, N->getValueType(0));
2675 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2676 /// is suitable for input to PSHUFLW.
2677 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2678 if (VT != MVT::v8i16)
2681 // Upper quadword copied in order.
2682 for (int i = 4; i != 8; ++i)
2683 if (Mask[i] >= 0 && Mask[i] != i)
2686 // Lower quadword shuffled.
2687 for (int i = 0; i != 4; ++i)
2694 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2695 SmallVector<int, 8> M;
2697 return ::isPSHUFLWMask(M, N->getValueType(0));
2700 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2701 /// is suitable for input to PALIGNR.
2702 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2704 int i, e = VT.getVectorNumElements();
2706 // Do not handle v2i64 / v2f64 shuffles with palignr.
2707 if (e < 4 || !hasSSSE3)
2710 for (i = 0; i != e; ++i)
2714 // All undef, not a palignr.
2718 // Determine if it's ok to perform a palignr with only the LHS, since we
2719 // don't have access to the actual shuffle elements to see if RHS is undef.
2720 bool Unary = Mask[i] < (int)e;
2721 bool NeedsUnary = false;
2723 int s = Mask[i] - i;
2725 // Check the rest of the elements to see if they are consecutive.
2726 for (++i; i != e; ++i) {
2731 Unary = Unary && (m < (int)e);
2732 NeedsUnary = NeedsUnary || (m < s);
2734 if (NeedsUnary && !Unary)
2736 if (Unary && m != ((s+i) & (e-1)))
2738 if (!Unary && m != (s+i))
2744 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2745 SmallVector<int, 8> M;
2747 return ::isPALIGNRMask(M, N->getValueType(0), true);
2750 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2751 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2752 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2753 int NumElems = VT.getVectorNumElements();
2754 if (NumElems != 2 && NumElems != 4)
2757 int Half = NumElems / 2;
2758 for (int i = 0; i < Half; ++i)
2759 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2761 for (int i = Half; i < NumElems; ++i)
2762 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2768 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2769 SmallVector<int, 8> M;
2771 return ::isSHUFPMask(M, N->getValueType(0));
2774 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2775 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2776 /// half elements to come from vector 1 (which would equal the dest.) and
2777 /// the upper half to come from vector 2.
2778 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2779 int NumElems = VT.getVectorNumElements();
2781 if (NumElems != 2 && NumElems != 4)
2784 int Half = NumElems / 2;
2785 for (int i = 0; i < Half; ++i)
2786 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2788 for (int i = Half; i < NumElems; ++i)
2789 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2794 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2795 SmallVector<int, 8> M;
2797 return isCommutedSHUFPMask(M, N->getValueType(0));
2800 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2801 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2802 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2803 if (N->getValueType(0).getVectorNumElements() != 4)
2806 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2807 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2808 isUndefOrEqual(N->getMaskElt(1), 7) &&
2809 isUndefOrEqual(N->getMaskElt(2), 2) &&
2810 isUndefOrEqual(N->getMaskElt(3), 3);
2813 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2814 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2816 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2817 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2822 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2823 isUndefOrEqual(N->getMaskElt(1), 3) &&
2824 isUndefOrEqual(N->getMaskElt(2), 2) &&
2825 isUndefOrEqual(N->getMaskElt(3), 3);
2828 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2829 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2830 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2831 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2833 if (NumElems != 2 && NumElems != 4)
2836 for (unsigned i = 0; i < NumElems/2; ++i)
2837 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2840 for (unsigned i = NumElems/2; i < NumElems; ++i)
2841 if (!isUndefOrEqual(N->getMaskElt(i), i))
2847 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2848 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2849 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2850 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2852 if (NumElems != 2 && NumElems != 4)
2855 for (unsigned i = 0; i < NumElems/2; ++i)
2856 if (!isUndefOrEqual(N->getMaskElt(i), i))
2859 for (unsigned i = 0; i < NumElems/2; ++i)
2860 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2866 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2867 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2868 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2869 bool V2IsSplat = false) {
2870 int NumElts = VT.getVectorNumElements();
2871 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2874 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2876 int BitI1 = Mask[i+1];
2877 if (!isUndefOrEqual(BitI, j))
2880 if (!isUndefOrEqual(BitI1, NumElts))
2883 if (!isUndefOrEqual(BitI1, j + NumElts))
2890 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2891 SmallVector<int, 8> M;
2893 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2896 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2897 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2898 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2899 bool V2IsSplat = false) {
2900 int NumElts = VT.getVectorNumElements();
2901 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2904 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2906 int BitI1 = Mask[i+1];
2907 if (!isUndefOrEqual(BitI, j + NumElts/2))
2910 if (isUndefOrEqual(BitI1, NumElts))
2913 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2920 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2921 SmallVector<int, 8> M;
2923 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2926 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2927 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2929 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2930 int NumElems = VT.getVectorNumElements();
2931 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2934 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2936 int BitI1 = Mask[i+1];
2937 if (!isUndefOrEqual(BitI, j))
2939 if (!isUndefOrEqual(BitI1, j))
2945 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2946 SmallVector<int, 8> M;
2948 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2951 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2952 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2954 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2955 int NumElems = VT.getVectorNumElements();
2956 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2959 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2961 int BitI1 = Mask[i+1];
2962 if (!isUndefOrEqual(BitI, j))
2964 if (!isUndefOrEqual(BitI1, j))
2970 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2971 SmallVector<int, 8> M;
2973 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2976 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2977 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2978 /// MOVSD, and MOVD, i.e. setting the lowest element.
2979 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2980 if (VT.getVectorElementType().getSizeInBits() < 32)
2983 int NumElts = VT.getVectorNumElements();
2985 if (!isUndefOrEqual(Mask[0], NumElts))
2988 for (int i = 1; i < NumElts; ++i)
2989 if (!isUndefOrEqual(Mask[i], i))
2995 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2996 SmallVector<int, 8> M;
2998 return ::isMOVLMask(M, N->getValueType(0));
3001 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3002 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3003 /// element of vector 2 and the other elements to come from vector 1 in order.
3004 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3005 bool V2IsSplat = false, bool V2IsUndef = false) {
3006 int NumOps = VT.getVectorNumElements();
3007 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3010 if (!isUndefOrEqual(Mask[0], 0))
3013 for (int i = 1; i < NumOps; ++i)
3014 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3015 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3016 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3022 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3023 bool V2IsUndef = false) {
3024 SmallVector<int, 8> M;
3026 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3029 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3030 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3031 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3032 if (N->getValueType(0).getVectorNumElements() != 4)
3035 // Expect 1, 1, 3, 3
3036 for (unsigned i = 0; i < 2; ++i) {
3037 int Elt = N->getMaskElt(i);
3038 if (Elt >= 0 && Elt != 1)
3043 for (unsigned i = 2; i < 4; ++i) {
3044 int Elt = N->getMaskElt(i);
3045 if (Elt >= 0 && Elt != 3)
3050 // Don't use movshdup if it can be done with a shufps.
3051 // FIXME: verify that matching u, u, 3, 3 is what we want.
3055 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3056 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3057 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3058 if (N->getValueType(0).getVectorNumElements() != 4)
3061 // Expect 0, 0, 2, 2
3062 for (unsigned i = 0; i < 2; ++i)
3063 if (N->getMaskElt(i) > 0)
3067 for (unsigned i = 2; i < 4; ++i) {
3068 int Elt = N->getMaskElt(i);
3069 if (Elt >= 0 && Elt != 2)
3074 // Don't use movsldup if it can be done with a shufps.
3078 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3079 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3080 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3081 int e = N->getValueType(0).getVectorNumElements() / 2;
3083 for (int i = 0; i < e; ++i)
3084 if (!isUndefOrEqual(N->getMaskElt(i), i))
3086 for (int i = 0; i < e; ++i)
3087 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3092 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3093 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3094 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3095 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3096 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3098 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3100 for (int i = 0; i < NumOperands; ++i) {
3101 int Val = SVOp->getMaskElt(NumOperands-i-1);
3102 if (Val < 0) Val = 0;
3103 if (Val >= NumOperands) Val -= NumOperands;
3105 if (i != NumOperands - 1)
3111 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3112 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3113 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3114 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3116 // 8 nodes, but we only care about the last 4.
3117 for (unsigned i = 7; i >= 4; --i) {
3118 int Val = SVOp->getMaskElt(i);
3127 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3128 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3129 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3130 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3132 // 8 nodes, but we only care about the first 4.
3133 for (int i = 3; i >= 0; --i) {
3134 int Val = SVOp->getMaskElt(i);
3143 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3144 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3145 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3146 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3147 EVT VVT = N->getValueType(0);
3148 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3152 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3153 Val = SVOp->getMaskElt(i);
3157 return (Val - i) * EltSize;
3160 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3162 bool X86::isZeroNode(SDValue Elt) {
3163 return ((isa<ConstantSDNode>(Elt) &&
3164 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3165 (isa<ConstantFPSDNode>(Elt) &&
3166 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3169 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3170 /// their permute mask.
3171 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3172 SelectionDAG &DAG) {
3173 EVT VT = SVOp->getValueType(0);
3174 unsigned NumElems = VT.getVectorNumElements();
3175 SmallVector<int, 8> MaskVec;
3177 for (unsigned i = 0; i != NumElems; ++i) {
3178 int idx = SVOp->getMaskElt(i);
3180 MaskVec.push_back(idx);
3181 else if (idx < (int)NumElems)
3182 MaskVec.push_back(idx + NumElems);
3184 MaskVec.push_back(idx - NumElems);
3186 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3187 SVOp->getOperand(0), &MaskVec[0]);
3190 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3191 /// the two vector operands have swapped position.
3192 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3193 unsigned NumElems = VT.getVectorNumElements();
3194 for (unsigned i = 0; i != NumElems; ++i) {
3198 else if (idx < (int)NumElems)
3199 Mask[i] = idx + NumElems;
3201 Mask[i] = idx - NumElems;
3205 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3206 /// match movhlps. The lower half elements should come from upper half of
3207 /// V1 (and in order), and the upper half elements should come from the upper
3208 /// half of V2 (and in order).
3209 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3210 if (Op->getValueType(0).getVectorNumElements() != 4)
3212 for (unsigned i = 0, e = 2; i != e; ++i)
3213 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3215 for (unsigned i = 2; i != 4; ++i)
3216 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3221 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3222 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3224 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3225 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3227 N = N->getOperand(0).getNode();
3228 if (!ISD::isNON_EXTLoad(N))
3231 *LD = cast<LoadSDNode>(N);
3235 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3236 /// match movlp{s|d}. The lower half elements should come from lower half of
3237 /// V1 (and in order), and the upper half elements should come from the upper
3238 /// half of V2 (and in order). And since V1 will become the source of the
3239 /// MOVLP, it must be either a vector load or a scalar load to vector.
3240 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3241 ShuffleVectorSDNode *Op) {
3242 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3244 // Is V2 is a vector load, don't do this transformation. We will try to use
3245 // load folding shufps op.
3246 if (ISD::isNON_EXTLoad(V2))
3249 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3251 if (NumElems != 2 && NumElems != 4)
3253 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3254 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3256 for (unsigned i = NumElems/2; i != NumElems; ++i)
3257 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3262 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3264 static bool isSplatVector(SDNode *N) {
3265 if (N->getOpcode() != ISD::BUILD_VECTOR)
3268 SDValue SplatValue = N->getOperand(0);
3269 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3270 if (N->getOperand(i) != SplatValue)
3275 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3276 /// to an zero vector.
3277 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3278 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3279 SDValue V1 = N->getOperand(0);
3280 SDValue V2 = N->getOperand(1);
3281 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3282 for (unsigned i = 0; i != NumElems; ++i) {
3283 int Idx = N->getMaskElt(i);
3284 if (Idx >= (int)NumElems) {
3285 unsigned Opc = V2.getOpcode();
3286 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3288 if (Opc != ISD::BUILD_VECTOR ||
3289 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3291 } else if (Idx >= 0) {
3292 unsigned Opc = V1.getOpcode();
3293 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3295 if (Opc != ISD::BUILD_VECTOR ||
3296 !X86::isZeroNode(V1.getOperand(Idx)))
3303 /// getZeroVector - Returns a vector of specified type with all zero elements.
3305 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3307 assert(VT.isVector() && "Expected a vector type");
3309 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3310 // type. This ensures they get CSE'd.
3312 if (VT.getSizeInBits() == 64) { // MMX
3313 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3314 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3315 } else if (HasSSE2) { // SSE2
3316 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3317 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3319 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3320 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3322 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3325 /// getOnesVector - Returns a vector of specified type with all bits set.
3327 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3328 assert(VT.isVector() && "Expected a vector type");
3330 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3331 // type. This ensures they get CSE'd.
3332 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3334 if (VT.getSizeInBits() == 64) // MMX
3335 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3337 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3338 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3342 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3343 /// that point to V2 points to its first element.
3344 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3345 EVT VT = SVOp->getValueType(0);
3346 unsigned NumElems = VT.getVectorNumElements();
3348 bool Changed = false;
3349 SmallVector<int, 8> MaskVec;
3350 SVOp->getMask(MaskVec);
3352 for (unsigned i = 0; i != NumElems; ++i) {
3353 if (MaskVec[i] > (int)NumElems) {
3354 MaskVec[i] = NumElems;
3359 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3360 SVOp->getOperand(1), &MaskVec[0]);
3361 return SDValue(SVOp, 0);
3364 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3365 /// operation of specified width.
3366 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3368 unsigned NumElems = VT.getVectorNumElements();
3369 SmallVector<int, 8> Mask;
3370 Mask.push_back(NumElems);
3371 for (unsigned i = 1; i != NumElems; ++i)
3373 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3376 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3377 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3379 unsigned NumElems = VT.getVectorNumElements();
3380 SmallVector<int, 8> Mask;
3381 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3383 Mask.push_back(i + NumElems);
3385 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3388 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3389 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3391 unsigned NumElems = VT.getVectorNumElements();
3392 unsigned Half = NumElems/2;
3393 SmallVector<int, 8> Mask;
3394 for (unsigned i = 0; i != Half; ++i) {
3395 Mask.push_back(i + Half);
3396 Mask.push_back(i + NumElems + Half);
3398 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3401 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3402 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3404 if (SV->getValueType(0).getVectorNumElements() <= 4)
3405 return SDValue(SV, 0);
3407 EVT PVT = MVT::v4f32;
3408 EVT VT = SV->getValueType(0);
3409 DebugLoc dl = SV->getDebugLoc();
3410 SDValue V1 = SV->getOperand(0);
3411 int NumElems = VT.getVectorNumElements();
3412 int EltNo = SV->getSplatIndex();
3414 // unpack elements to the correct location
3415 while (NumElems > 4) {
3416 if (EltNo < NumElems/2) {
3417 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3419 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3420 EltNo -= NumElems/2;
3425 // Perform the splat.
3426 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3427 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3428 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3429 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3432 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3433 /// vector of zero or undef vector. This produces a shuffle where the low
3434 /// element of V2 is swizzled into the zero/undef vector, landing at element
3435 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3436 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3437 bool isZero, bool HasSSE2,
3438 SelectionDAG &DAG) {
3439 EVT VT = V2.getValueType();
3441 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3442 unsigned NumElems = VT.getVectorNumElements();
3443 SmallVector<int, 16> MaskVec;
3444 for (unsigned i = 0; i != NumElems; ++i)
3445 // If this is the insertion idx, put the low elt of V2 here.
3446 MaskVec.push_back(i == Idx ? NumElems : i);
3447 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3450 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3451 /// a shuffle that is zero.
3453 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3454 bool Low, SelectionDAG &DAG) {
3455 unsigned NumZeros = 0;
3456 for (int i = 0; i < NumElems; ++i) {
3457 unsigned Index = Low ? i : NumElems-i-1;
3458 int Idx = SVOp->getMaskElt(Index);
3463 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3464 if (Elt.getNode() && X86::isZeroNode(Elt))
3472 /// isVectorShift - Returns true if the shuffle can be implemented as a
3473 /// logical left or right shift of a vector.
3474 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3475 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3476 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3477 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3480 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3483 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3487 bool SeenV1 = false;
3488 bool SeenV2 = false;
3489 for (unsigned i = NumZeros; i < NumElems; ++i) {
3490 unsigned Val = isLeft ? (i - NumZeros) : i;
3491 int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3494 unsigned Idx = (unsigned) Idx_;
3504 if (SeenV1 && SeenV2)
3507 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3513 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3515 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3516 unsigned NumNonZero, unsigned NumZero,
3518 const TargetLowering &TLI) {
3522 DebugLoc dl = Op.getDebugLoc();
3525 for (unsigned i = 0; i < 16; ++i) {
3526 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3527 if (ThisIsNonZero && First) {
3529 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3531 V = DAG.getUNDEF(MVT::v8i16);
3536 SDValue ThisElt(0, 0), LastElt(0, 0);
3537 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3538 if (LastIsNonZero) {
3539 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3540 MVT::i16, Op.getOperand(i-1));
3542 if (ThisIsNonZero) {
3543 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3544 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3545 ThisElt, DAG.getConstant(8, MVT::i8));
3547 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3551 if (ThisElt.getNode())
3552 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3553 DAG.getIntPtrConstant(i/2));
3557 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3560 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3562 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3563 unsigned NumNonZero, unsigned NumZero,
3565 const TargetLowering &TLI) {
3569 DebugLoc dl = Op.getDebugLoc();
3572 for (unsigned i = 0; i < 8; ++i) {
3573 bool isNonZero = (NonZeros & (1 << i)) != 0;
3577 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3579 V = DAG.getUNDEF(MVT::v8i16);
3582 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3583 MVT::v8i16, V, Op.getOperand(i),
3584 DAG.getIntPtrConstant(i));
3591 /// getVShift - Return a vector logical shift node.
3593 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3594 unsigned NumBits, SelectionDAG &DAG,
3595 const TargetLowering &TLI, DebugLoc dl) {
3596 bool isMMX = VT.getSizeInBits() == 64;
3597 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3598 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3599 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3600 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3601 DAG.getNode(Opc, dl, ShVT, SrcOp,
3602 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3606 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3607 SelectionDAG &DAG) const {
3609 // Check if the scalar load can be widened into a vector load. And if
3610 // the address is "base + cst" see if the cst can be "absorbed" into
3611 // the shuffle mask.
3612 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3613 SDValue Ptr = LD->getBasePtr();
3614 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3616 EVT PVT = LD->getValueType(0);
3617 if (PVT != MVT::i32 && PVT != MVT::f32)
3622 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3623 FI = FINode->getIndex();
3625 } else if (Ptr.getOpcode() == ISD::ADD &&
3626 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3627 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3628 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3629 Offset = Ptr.getConstantOperandVal(1);
3630 Ptr = Ptr.getOperand(0);
3635 SDValue Chain = LD->getChain();
3636 // Make sure the stack object alignment is at least 16.
3637 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3638 if (DAG.InferPtrAlignment(Ptr) < 16) {
3639 if (MFI->isFixedObjectIndex(FI)) {
3640 // Can't change the alignment. FIXME: It's possible to compute
3641 // the exact stack offset and reference FI + adjust offset instead.
3642 // If someone *really* cares about this. That's the way to implement it.
3645 MFI->setObjectAlignment(FI, 16);
3649 // (Offset % 16) must be multiple of 4. Then address is then
3650 // Ptr + (Offset & ~15).
3653 if ((Offset % 16) & 3)
3655 int64_t StartOffset = Offset & ~15;
3657 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3658 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3660 int EltNo = (Offset - StartOffset) >> 2;
3661 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3662 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3663 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3665 // Canonicalize it to a v4i32 shuffle.
3666 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3667 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3668 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3669 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3675 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3676 /// vector of type 'VT', see if the elements can be replaced by a single large
3677 /// load which has the same value as a build_vector whose operands are 'elts'.
3679 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3681 /// FIXME: we'd also like to handle the case where the last elements are zero
3682 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3683 /// There's even a handy isZeroNode for that purpose.
3684 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3685 DebugLoc &dl, SelectionDAG &DAG) {
3686 EVT EltVT = VT.getVectorElementType();
3687 unsigned NumElems = Elts.size();
3689 LoadSDNode *LDBase = NULL;
3690 unsigned LastLoadedElt = -1U;
3692 // For each element in the initializer, see if we've found a load or an undef.
3693 // If we don't find an initial load element, or later load elements are
3694 // non-consecutive, bail out.
3695 for (unsigned i = 0; i < NumElems; ++i) {
3696 SDValue Elt = Elts[i];
3698 if (!Elt.getNode() ||
3699 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3702 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3704 LDBase = cast<LoadSDNode>(Elt.getNode());
3708 if (Elt.getOpcode() == ISD::UNDEF)
3711 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3712 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3717 // If we have found an entire vector of loads and undefs, then return a large
3718 // load of the entire vector width starting at the base pointer. If we found
3719 // consecutive loads for the low half, generate a vzext_load node.
3720 if (LastLoadedElt == NumElems - 1) {
3721 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3722 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3723 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3724 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3725 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3726 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3727 LDBase->isVolatile(), LDBase->isNonTemporal(),
3728 LDBase->getAlignment());
3729 } else if (NumElems == 4 && LastLoadedElt == 1) {
3730 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3731 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3732 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3733 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3739 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3740 DebugLoc dl = Op.getDebugLoc();
3741 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3742 if (ISD::isBuildVectorAllZeros(Op.getNode())
3743 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3744 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3745 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3746 // eliminated on x86-32 hosts.
3747 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3750 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3751 return getOnesVector(Op.getValueType(), DAG, dl);
3752 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3755 EVT VT = Op.getValueType();
3756 EVT ExtVT = VT.getVectorElementType();
3757 unsigned EVTBits = ExtVT.getSizeInBits();
3759 unsigned NumElems = Op.getNumOperands();
3760 unsigned NumZero = 0;
3761 unsigned NumNonZero = 0;
3762 unsigned NonZeros = 0;
3763 bool IsAllConstants = true;
3764 SmallSet<SDValue, 8> Values;
3765 for (unsigned i = 0; i < NumElems; ++i) {
3766 SDValue Elt = Op.getOperand(i);
3767 if (Elt.getOpcode() == ISD::UNDEF)
3770 if (Elt.getOpcode() != ISD::Constant &&
3771 Elt.getOpcode() != ISD::ConstantFP)
3772 IsAllConstants = false;
3773 if (X86::isZeroNode(Elt))
3776 NonZeros |= (1 << i);
3781 if (NumNonZero == 0) {
3782 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3783 return DAG.getUNDEF(VT);
3786 // Special case for single non-zero, non-undef, element.
3787 if (NumNonZero == 1) {
3788 unsigned Idx = CountTrailingZeros_32(NonZeros);
3789 SDValue Item = Op.getOperand(Idx);
3791 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3792 // the value are obviously zero, truncate the value to i32 and do the
3793 // insertion that way. Only do this if the value is non-constant or if the
3794 // value is a constant being inserted into element 0. It is cheaper to do
3795 // a constant pool load than it is to do a movd + shuffle.
3796 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3797 (!IsAllConstants || Idx == 0)) {
3798 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3799 // Handle MMX and SSE both.
3800 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3801 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3803 // Truncate the value (which may itself be a constant) to i32, and
3804 // convert it to a vector with movd (S2V+shuffle to zero extend).
3805 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3806 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3807 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3808 Subtarget->hasSSE2(), DAG);
3810 // Now we have our 32-bit value zero extended in the low element of
3811 // a vector. If Idx != 0, swizzle it into place.
3813 SmallVector<int, 4> Mask;
3814 Mask.push_back(Idx);
3815 for (unsigned i = 1; i != VecElts; ++i)
3817 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3818 DAG.getUNDEF(Item.getValueType()),
3821 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3825 // If we have a constant or non-constant insertion into the low element of
3826 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3827 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3828 // depending on what the source datatype is.
3831 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3832 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3833 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3834 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3835 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3836 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3838 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3839 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3840 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3841 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3842 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3843 Subtarget->hasSSE2(), DAG);
3844 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3848 // Is it a vector logical left shift?
3849 if (NumElems == 2 && Idx == 1 &&
3850 X86::isZeroNode(Op.getOperand(0)) &&
3851 !X86::isZeroNode(Op.getOperand(1))) {
3852 unsigned NumBits = VT.getSizeInBits();
3853 return getVShift(true, VT,
3854 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3855 VT, Op.getOperand(1)),
3856 NumBits/2, DAG, *this, dl);
3859 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3862 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3863 // is a non-constant being inserted into an element other than the low one,
3864 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3865 // movd/movss) to move this into the low element, then shuffle it into
3867 if (EVTBits == 32) {
3868 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3870 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3871 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3872 Subtarget->hasSSE2(), DAG);
3873 SmallVector<int, 8> MaskVec;
3874 for (unsigned i = 0; i < NumElems; i++)
3875 MaskVec.push_back(i == Idx ? 0 : 1);
3876 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3880 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3881 if (Values.size() == 1) {
3882 if (EVTBits == 32) {
3883 // Instead of a shuffle like this:
3884 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3885 // Check if it's possible to issue this instead.
3886 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3887 unsigned Idx = CountTrailingZeros_32(NonZeros);
3888 SDValue Item = Op.getOperand(Idx);
3889 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3890 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3895 // A vector full of immediates; various special cases are already
3896 // handled, so this is best done with a single constant-pool load.
3900 // Let legalizer expand 2-wide build_vectors.
3901 if (EVTBits == 64) {
3902 if (NumNonZero == 1) {
3903 // One half is zero or undef.
3904 unsigned Idx = CountTrailingZeros_32(NonZeros);
3905 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3906 Op.getOperand(Idx));
3907 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3908 Subtarget->hasSSE2(), DAG);
3913 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3914 if (EVTBits == 8 && NumElems == 16) {
3915 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3917 if (V.getNode()) return V;
3920 if (EVTBits == 16 && NumElems == 8) {
3921 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3923 if (V.getNode()) return V;
3926 // If element VT is == 32 bits, turn it into a number of shuffles.
3927 SmallVector<SDValue, 8> V;
3929 if (NumElems == 4 && NumZero > 0) {
3930 for (unsigned i = 0; i < 4; ++i) {
3931 bool isZero = !(NonZeros & (1 << i));
3933 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3935 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3938 for (unsigned i = 0; i < 2; ++i) {
3939 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3942 V[i] = V[i*2]; // Must be a zero vector.
3945 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3948 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3951 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3956 SmallVector<int, 8> MaskVec;
3957 bool Reverse = (NonZeros & 0x3) == 2;
3958 for (unsigned i = 0; i < 2; ++i)
3959 MaskVec.push_back(Reverse ? 1-i : i);
3960 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3961 for (unsigned i = 0; i < 2; ++i)
3962 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3963 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3966 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3967 // Check for a build vector of consecutive loads.
3968 for (unsigned i = 0; i < NumElems; ++i)
3969 V[i] = Op.getOperand(i);
3971 // Check for elements which are consecutive loads.
3972 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3976 // For SSE 4.1, use inserts into undef.
3977 if (getSubtarget()->hasSSE41()) {
3978 V[0] = DAG.getUNDEF(VT);
3979 for (unsigned i = 0; i < NumElems; ++i)
3980 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3981 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3982 Op.getOperand(i), DAG.getIntPtrConstant(i));
3986 // Otherwise, expand into a number of unpckl*
3988 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3989 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3990 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3991 for (unsigned i = 0; i < NumElems; ++i)
3992 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3994 while (NumElems != 0) {
3995 for (unsigned i = 0; i < NumElems; ++i)
3996 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4005 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4006 // We support concatenate two MMX registers and place them in a MMX
4007 // register. This is better than doing a stack convert.
4008 DebugLoc dl = Op.getDebugLoc();
4009 EVT ResVT = Op.getValueType();
4010 assert(Op.getNumOperands() == 2);
4011 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4012 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4014 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4015 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4016 InVec = Op.getOperand(1);
4017 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4018 unsigned NumElts = ResVT.getVectorNumElements();
4019 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4020 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4021 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4023 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4024 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4025 Mask[0] = 0; Mask[1] = 2;
4026 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4028 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4031 // v8i16 shuffles - Prefer shuffles in the following order:
4032 // 1. [all] pshuflw, pshufhw, optional move
4033 // 2. [ssse3] 1 x pshufb
4034 // 3. [ssse3] 2 x pshufb + 1 x por
4035 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4037 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4039 const X86TargetLowering &TLI) {
4040 SDValue V1 = SVOp->getOperand(0);
4041 SDValue V2 = SVOp->getOperand(1);
4042 DebugLoc dl = SVOp->getDebugLoc();
4043 SmallVector<int, 8> MaskVals;
4045 // Determine if more than 1 of the words in each of the low and high quadwords
4046 // of the result come from the same quadword of one of the two inputs. Undef
4047 // mask values count as coming from any quadword, for better codegen.
4048 SmallVector<unsigned, 4> LoQuad(4);
4049 SmallVector<unsigned, 4> HiQuad(4);
4050 BitVector InputQuads(4);
4051 for (unsigned i = 0; i < 8; ++i) {
4052 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4053 int EltIdx = SVOp->getMaskElt(i);
4054 MaskVals.push_back(EltIdx);
4063 InputQuads.set(EltIdx / 4);
4066 int BestLoQuad = -1;
4067 unsigned MaxQuad = 1;
4068 for (unsigned i = 0; i < 4; ++i) {
4069 if (LoQuad[i] > MaxQuad) {
4071 MaxQuad = LoQuad[i];
4075 int BestHiQuad = -1;
4077 for (unsigned i = 0; i < 4; ++i) {
4078 if (HiQuad[i] > MaxQuad) {
4080 MaxQuad = HiQuad[i];
4084 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4085 // of the two input vectors, shuffle them into one input vector so only a
4086 // single pshufb instruction is necessary. If There are more than 2 input
4087 // quads, disable the next transformation since it does not help SSSE3.
4088 bool V1Used = InputQuads[0] || InputQuads[1];
4089 bool V2Used = InputQuads[2] || InputQuads[3];
4090 if (TLI.getSubtarget()->hasSSSE3()) {
4091 if (InputQuads.count() == 2 && V1Used && V2Used) {
4092 BestLoQuad = InputQuads.find_first();
4093 BestHiQuad = InputQuads.find_next(BestLoQuad);
4095 if (InputQuads.count() > 2) {
4101 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4102 // the shuffle mask. If a quad is scored as -1, that means that it contains
4103 // words from all 4 input quadwords.
4105 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4106 SmallVector<int, 8> MaskV;
4107 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4108 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4109 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4110 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4111 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4112 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4114 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4115 // source words for the shuffle, to aid later transformations.
4116 bool AllWordsInNewV = true;
4117 bool InOrder[2] = { true, true };
4118 for (unsigned i = 0; i != 8; ++i) {
4119 int idx = MaskVals[i];
4121 InOrder[i/4] = false;
4122 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4124 AllWordsInNewV = false;
4128 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4129 if (AllWordsInNewV) {
4130 for (int i = 0; i != 8; ++i) {
4131 int idx = MaskVals[i];
4134 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4135 if ((idx != i) && idx < 4)
4137 if ((idx != i) && idx > 3)
4146 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4147 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4148 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4149 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4150 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4154 // If we have SSSE3, and all words of the result are from 1 input vector,
4155 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4156 // is present, fall back to case 4.
4157 if (TLI.getSubtarget()->hasSSSE3()) {
4158 SmallVector<SDValue,16> pshufbMask;
4160 // If we have elements from both input vectors, set the high bit of the
4161 // shuffle mask element to zero out elements that come from V2 in the V1
4162 // mask, and elements that come from V1 in the V2 mask, so that the two
4163 // results can be OR'd together.
4164 bool TwoInputs = V1Used && V2Used;
4165 for (unsigned i = 0; i != 8; ++i) {
4166 int EltIdx = MaskVals[i] * 2;
4167 if (TwoInputs && (EltIdx >= 16)) {
4168 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4169 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4172 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4173 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4175 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4176 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4177 DAG.getNode(ISD::BUILD_VECTOR, dl,
4178 MVT::v16i8, &pshufbMask[0], 16));
4180 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4182 // Calculate the shuffle mask for the second input, shuffle it, and
4183 // OR it with the first shuffled input.
4185 for (unsigned i = 0; i != 8; ++i) {
4186 int EltIdx = MaskVals[i] * 2;
4188 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4189 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4192 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4193 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4195 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4196 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4197 DAG.getNode(ISD::BUILD_VECTOR, dl,
4198 MVT::v16i8, &pshufbMask[0], 16));
4199 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4200 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4203 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4204 // and update MaskVals with new element order.
4205 BitVector InOrder(8);
4206 if (BestLoQuad >= 0) {
4207 SmallVector<int, 8> MaskV;
4208 for (int i = 0; i != 4; ++i) {
4209 int idx = MaskVals[i];
4211 MaskV.push_back(-1);
4213 } else if ((idx / 4) == BestLoQuad) {
4214 MaskV.push_back(idx & 3);
4217 MaskV.push_back(-1);
4220 for (unsigned i = 4; i != 8; ++i)
4222 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4226 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4227 // and update MaskVals with the new element order.
4228 if (BestHiQuad >= 0) {
4229 SmallVector<int, 8> MaskV;
4230 for (unsigned i = 0; i != 4; ++i)
4232 for (unsigned i = 4; i != 8; ++i) {
4233 int idx = MaskVals[i];
4235 MaskV.push_back(-1);
4237 } else if ((idx / 4) == BestHiQuad) {
4238 MaskV.push_back((idx & 3) + 4);
4241 MaskV.push_back(-1);
4244 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4248 // In case BestHi & BestLo were both -1, which means each quadword has a word
4249 // from each of the four input quadwords, calculate the InOrder bitvector now
4250 // before falling through to the insert/extract cleanup.
4251 if (BestLoQuad == -1 && BestHiQuad == -1) {
4253 for (int i = 0; i != 8; ++i)
4254 if (MaskVals[i] < 0 || MaskVals[i] == i)
4258 // The other elements are put in the right place using pextrw and pinsrw.
4259 for (unsigned i = 0; i != 8; ++i) {
4262 int EltIdx = MaskVals[i];
4265 SDValue ExtOp = (EltIdx < 8)
4266 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4267 DAG.getIntPtrConstant(EltIdx))
4268 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4269 DAG.getIntPtrConstant(EltIdx - 8));
4270 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4271 DAG.getIntPtrConstant(i));
4276 // v16i8 shuffles - Prefer shuffles in the following order:
4277 // 1. [ssse3] 1 x pshufb
4278 // 2. [ssse3] 2 x pshufb + 1 x por
4279 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4281 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4283 const X86TargetLowering &TLI) {
4284 SDValue V1 = SVOp->getOperand(0);
4285 SDValue V2 = SVOp->getOperand(1);
4286 DebugLoc dl = SVOp->getDebugLoc();
4287 SmallVector<int, 16> MaskVals;
4288 SVOp->getMask(MaskVals);
4290 // If we have SSSE3, case 1 is generated when all result bytes come from
4291 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4292 // present, fall back to case 3.
4293 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4296 for (unsigned i = 0; i < 16; ++i) {
4297 int EltIdx = MaskVals[i];
4306 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4307 if (TLI.getSubtarget()->hasSSSE3()) {
4308 SmallVector<SDValue,16> pshufbMask;
4310 // If all result elements are from one input vector, then only translate
4311 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4313 // Otherwise, we have elements from both input vectors, and must zero out
4314 // elements that come from V2 in the first mask, and V1 in the second mask
4315 // so that we can OR them together.
4316 bool TwoInputs = !(V1Only || V2Only);
4317 for (unsigned i = 0; i != 16; ++i) {
4318 int EltIdx = MaskVals[i];
4319 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4320 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4323 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4325 // If all the elements are from V2, assign it to V1 and return after
4326 // building the first pshufb.
4329 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4330 DAG.getNode(ISD::BUILD_VECTOR, dl,
4331 MVT::v16i8, &pshufbMask[0], 16));
4335 // Calculate the shuffle mask for the second input, shuffle it, and
4336 // OR it with the first shuffled input.
4338 for (unsigned i = 0; i != 16; ++i) {
4339 int EltIdx = MaskVals[i];
4341 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4344 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4346 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4347 DAG.getNode(ISD::BUILD_VECTOR, dl,
4348 MVT::v16i8, &pshufbMask[0], 16));
4349 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4352 // No SSSE3 - Calculate in place words and then fix all out of place words
4353 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4354 // the 16 different words that comprise the two doublequadword input vectors.
4355 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4356 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4357 SDValue NewV = V2Only ? V2 : V1;
4358 for (int i = 0; i != 8; ++i) {
4359 int Elt0 = MaskVals[i*2];
4360 int Elt1 = MaskVals[i*2+1];
4362 // This word of the result is all undef, skip it.
4363 if (Elt0 < 0 && Elt1 < 0)
4366 // This word of the result is already in the correct place, skip it.
4367 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4369 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4372 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4373 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4376 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4377 // using a single extract together, load it and store it.
4378 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4379 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4380 DAG.getIntPtrConstant(Elt1 / 2));
4381 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4382 DAG.getIntPtrConstant(i));
4386 // If Elt1 is defined, extract it from the appropriate source. If the
4387 // source byte is not also odd, shift the extracted word left 8 bits
4388 // otherwise clear the bottom 8 bits if we need to do an or.
4390 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4391 DAG.getIntPtrConstant(Elt1 / 2));
4392 if ((Elt1 & 1) == 0)
4393 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4394 DAG.getConstant(8, TLI.getShiftAmountTy()));
4396 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4397 DAG.getConstant(0xFF00, MVT::i16));
4399 // If Elt0 is defined, extract it from the appropriate source. If the
4400 // source byte is not also even, shift the extracted word right 8 bits. If
4401 // Elt1 was also defined, OR the extracted values together before
4402 // inserting them in the result.
4404 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4405 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4406 if ((Elt0 & 1) != 0)
4407 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4408 DAG.getConstant(8, TLI.getShiftAmountTy()));
4410 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4411 DAG.getConstant(0x00FF, MVT::i16));
4412 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4415 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4416 DAG.getIntPtrConstant(i));
4418 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4421 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4422 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4423 /// done when every pair / quad of shuffle mask elements point to elements in
4424 /// the right sequence. e.g.
4425 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4427 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4429 const TargetLowering &TLI, DebugLoc dl) {
4430 EVT VT = SVOp->getValueType(0);
4431 SDValue V1 = SVOp->getOperand(0);
4432 SDValue V2 = SVOp->getOperand(1);
4433 unsigned NumElems = VT.getVectorNumElements();
4434 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4435 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4436 EVT MaskEltVT = MaskVT.getVectorElementType();
4438 switch (VT.getSimpleVT().SimpleTy) {
4439 default: assert(false && "Unexpected!");
4440 case MVT::v4f32: NewVT = MVT::v2f64; break;
4441 case MVT::v4i32: NewVT = MVT::v2i64; break;
4442 case MVT::v8i16: NewVT = MVT::v4i32; break;
4443 case MVT::v16i8: NewVT = MVT::v4i32; break;
4446 if (NewWidth == 2) {
4452 int Scale = NumElems / NewWidth;
4453 SmallVector<int, 8> MaskVec;
4454 for (unsigned i = 0; i < NumElems; i += Scale) {
4456 for (int j = 0; j < Scale; ++j) {
4457 int EltIdx = SVOp->getMaskElt(i+j);
4461 StartIdx = EltIdx - (EltIdx % Scale);
4462 if (EltIdx != StartIdx + j)
4466 MaskVec.push_back(-1);
4468 MaskVec.push_back(StartIdx / Scale);
4471 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4472 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4473 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4476 /// getVZextMovL - Return a zero-extending vector move low node.
4478 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4479 SDValue SrcOp, SelectionDAG &DAG,
4480 const X86Subtarget *Subtarget, DebugLoc dl) {
4481 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4482 LoadSDNode *LD = NULL;
4483 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4484 LD = dyn_cast<LoadSDNode>(SrcOp);
4486 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4488 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4489 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4490 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4491 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4492 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4494 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4495 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4496 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4497 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4505 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4506 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4507 DAG.getNode(ISD::BIT_CONVERT, dl,
4511 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4514 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4515 SDValue V1 = SVOp->getOperand(0);
4516 SDValue V2 = SVOp->getOperand(1);
4517 DebugLoc dl = SVOp->getDebugLoc();
4518 EVT VT = SVOp->getValueType(0);
4520 SmallVector<std::pair<int, int>, 8> Locs;
4522 SmallVector<int, 8> Mask1(4U, -1);
4523 SmallVector<int, 8> PermMask;
4524 SVOp->getMask(PermMask);
4528 for (unsigned i = 0; i != 4; ++i) {
4529 int Idx = PermMask[i];
4531 Locs[i] = std::make_pair(-1, -1);
4533 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4535 Locs[i] = std::make_pair(0, NumLo);
4539 Locs[i] = std::make_pair(1, NumHi);
4541 Mask1[2+NumHi] = Idx;
4547 if (NumLo <= 2 && NumHi <= 2) {
4548 // If no more than two elements come from either vector. This can be
4549 // implemented with two shuffles. First shuffle gather the elements.
4550 // The second shuffle, which takes the first shuffle as both of its
4551 // vector operands, put the elements into the right order.
4552 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4554 SmallVector<int, 8> Mask2(4U, -1);
4556 for (unsigned i = 0; i != 4; ++i) {
4557 if (Locs[i].first == -1)
4560 unsigned Idx = (i < 2) ? 0 : 4;
4561 Idx += Locs[i].first * 2 + Locs[i].second;
4566 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4567 } else if (NumLo == 3 || NumHi == 3) {
4568 // Otherwise, we must have three elements from one vector, call it X, and
4569 // one element from the other, call it Y. First, use a shufps to build an
4570 // intermediate vector with the one element from Y and the element from X
4571 // that will be in the same half in the final destination (the indexes don't
4572 // matter). Then, use a shufps to build the final vector, taking the half
4573 // containing the element from Y from the intermediate, and the other half
4576 // Normalize it so the 3 elements come from V1.
4577 CommuteVectorShuffleMask(PermMask, VT);
4581 // Find the element from V2.
4583 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4584 int Val = PermMask[HiIndex];
4591 Mask1[0] = PermMask[HiIndex];
4593 Mask1[2] = PermMask[HiIndex^1];
4595 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4598 Mask1[0] = PermMask[0];
4599 Mask1[1] = PermMask[1];
4600 Mask1[2] = HiIndex & 1 ? 6 : 4;
4601 Mask1[3] = HiIndex & 1 ? 4 : 6;
4602 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4604 Mask1[0] = HiIndex & 1 ? 2 : 0;
4605 Mask1[1] = HiIndex & 1 ? 0 : 2;
4606 Mask1[2] = PermMask[2];
4607 Mask1[3] = PermMask[3];
4612 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4616 // Break it into (shuffle shuffle_hi, shuffle_lo).
4618 SmallVector<int,8> LoMask(4U, -1);
4619 SmallVector<int,8> HiMask(4U, -1);
4621 SmallVector<int,8> *MaskPtr = &LoMask;
4622 unsigned MaskIdx = 0;
4625 for (unsigned i = 0; i != 4; ++i) {
4632 int Idx = PermMask[i];
4634 Locs[i] = std::make_pair(-1, -1);
4635 } else if (Idx < 4) {
4636 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4637 (*MaskPtr)[LoIdx] = Idx;
4640 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4641 (*MaskPtr)[HiIdx] = Idx;
4646 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4647 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4648 SmallVector<int, 8> MaskOps;
4649 for (unsigned i = 0; i != 4; ++i) {
4650 if (Locs[i].first == -1) {
4651 MaskOps.push_back(-1);
4653 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4654 MaskOps.push_back(Idx);
4657 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4661 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4662 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4663 SDValue V1 = Op.getOperand(0);
4664 SDValue V2 = Op.getOperand(1);
4665 EVT VT = Op.getValueType();
4666 DebugLoc dl = Op.getDebugLoc();
4667 unsigned NumElems = VT.getVectorNumElements();
4668 bool isMMX = VT.getSizeInBits() == 64;
4669 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4670 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4671 bool V1IsSplat = false;
4672 bool V2IsSplat = false;
4674 if (isZeroShuffle(SVOp))
4675 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4677 // Promote splats to v4f32.
4678 if (SVOp->isSplat()) {
4679 if (isMMX || NumElems < 4)
4681 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4684 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4686 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4687 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4688 if (NewOp.getNode())
4689 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4690 LowerVECTOR_SHUFFLE(NewOp, DAG));
4691 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4692 // FIXME: Figure out a cleaner way to do this.
4693 // Try to make use of movq to zero out the top part.
4694 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4695 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4696 if (NewOp.getNode()) {
4697 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4698 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4699 DAG, Subtarget, dl);
4701 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4702 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4703 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4704 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4705 DAG, Subtarget, dl);
4709 if (X86::isPSHUFDMask(SVOp))
4712 // Check if this can be converted into a logical shift.
4713 bool isLeft = false;
4716 bool isShift = getSubtarget()->hasSSE2() &&
4717 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4718 if (isShift && ShVal.hasOneUse()) {
4719 // If the shifted value has multiple uses, it may be cheaper to use
4720 // v_set0 + movlhps or movhlps, etc.
4721 EVT EltVT = VT.getVectorElementType();
4722 ShAmt *= EltVT.getSizeInBits();
4723 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4726 if (X86::isMOVLMask(SVOp)) {
4729 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4730 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4735 // FIXME: fold these into legal mask.
4736 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4737 X86::isMOVSLDUPMask(SVOp) ||
4738 X86::isMOVHLPSMask(SVOp) ||
4739 X86::isMOVLHPSMask(SVOp) ||
4740 X86::isMOVLPMask(SVOp)))
4743 if (ShouldXformToMOVHLPS(SVOp) ||
4744 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4745 return CommuteVectorShuffle(SVOp, DAG);
4748 // No better options. Use a vshl / vsrl.
4749 EVT EltVT = VT.getVectorElementType();
4750 ShAmt *= EltVT.getSizeInBits();
4751 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4754 bool Commuted = false;
4755 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4756 // 1,1,1,1 -> v8i16 though.
4757 V1IsSplat = isSplatVector(V1.getNode());
4758 V2IsSplat = isSplatVector(V2.getNode());
4760 // Canonicalize the splat or undef, if present, to be on the RHS.
4761 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4762 Op = CommuteVectorShuffle(SVOp, DAG);
4763 SVOp = cast<ShuffleVectorSDNode>(Op);
4764 V1 = SVOp->getOperand(0);
4765 V2 = SVOp->getOperand(1);
4766 std::swap(V1IsSplat, V2IsSplat);
4767 std::swap(V1IsUndef, V2IsUndef);
4771 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4772 // Shuffling low element of v1 into undef, just return v1.
4775 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4776 // the instruction selector will not match, so get a canonical MOVL with
4777 // swapped operands to undo the commute.
4778 return getMOVL(DAG, dl, VT, V2, V1);
4781 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4782 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4783 X86::isUNPCKLMask(SVOp) ||
4784 X86::isUNPCKHMask(SVOp))
4788 // Normalize mask so all entries that point to V2 points to its first
4789 // element then try to match unpck{h|l} again. If match, return a
4790 // new vector_shuffle with the corrected mask.
4791 SDValue NewMask = NormalizeMask(SVOp, DAG);
4792 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4793 if (NSVOp != SVOp) {
4794 if (X86::isUNPCKLMask(NSVOp, true)) {
4796 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4803 // Commute is back and try unpck* again.
4804 // FIXME: this seems wrong.
4805 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4806 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4807 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4808 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4809 X86::isUNPCKLMask(NewSVOp) ||
4810 X86::isUNPCKHMask(NewSVOp))
4814 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4816 // Normalize the node to match x86 shuffle ops if needed
4817 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4818 return CommuteVectorShuffle(SVOp, DAG);
4820 // Check for legal shuffle and return?
4821 SmallVector<int, 16> PermMask;
4822 SVOp->getMask(PermMask);
4823 if (isShuffleMaskLegal(PermMask, VT))
4826 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4827 if (VT == MVT::v8i16) {
4828 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4829 if (NewOp.getNode())
4833 if (VT == MVT::v16i8) {
4834 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4835 if (NewOp.getNode())
4839 // Handle all 4 wide cases with a number of shuffles except for MMX.
4840 if (NumElems == 4 && !isMMX)
4841 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4847 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4848 SelectionDAG &DAG) const {
4849 EVT VT = Op.getValueType();
4850 DebugLoc dl = Op.getDebugLoc();
4851 if (VT.getSizeInBits() == 8) {
4852 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4853 Op.getOperand(0), Op.getOperand(1));
4854 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4855 DAG.getValueType(VT));
4856 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4857 } else if (VT.getSizeInBits() == 16) {
4858 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4859 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4861 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4862 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4863 DAG.getNode(ISD::BIT_CONVERT, dl,
4867 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4868 Op.getOperand(0), Op.getOperand(1));
4869 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4870 DAG.getValueType(VT));
4871 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4872 } else if (VT == MVT::f32) {
4873 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4874 // the result back to FR32 register. It's only worth matching if the
4875 // result has a single use which is a store or a bitcast to i32. And in
4876 // the case of a store, it's not worth it if the index is a constant 0,
4877 // because a MOVSSmr can be used instead, which is smaller and faster.
4878 if (!Op.hasOneUse())
4880 SDNode *User = *Op.getNode()->use_begin();
4881 if ((User->getOpcode() != ISD::STORE ||
4882 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4883 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4884 (User->getOpcode() != ISD::BIT_CONVERT ||
4885 User->getValueType(0) != MVT::i32))
4887 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4888 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4891 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4892 } else if (VT == MVT::i32) {
4893 // ExtractPS works with constant index.
4894 if (isa<ConstantSDNode>(Op.getOperand(1)))
4902 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4903 SelectionDAG &DAG) const {
4904 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4907 if (Subtarget->hasSSE41()) {
4908 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4913 EVT VT = Op.getValueType();
4914 DebugLoc dl = Op.getDebugLoc();
4915 // TODO: handle v16i8.
4916 if (VT.getSizeInBits() == 16) {
4917 SDValue Vec = Op.getOperand(0);
4918 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4920 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4921 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4922 DAG.getNode(ISD::BIT_CONVERT, dl,
4925 // Transform it so it match pextrw which produces a 32-bit result.
4926 EVT EltVT = MVT::i32;
4927 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4928 Op.getOperand(0), Op.getOperand(1));
4929 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4930 DAG.getValueType(VT));
4931 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4932 } else if (VT.getSizeInBits() == 32) {
4933 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4937 // SHUFPS the element to the lowest double word, then movss.
4938 int Mask[4] = { Idx, -1, -1, -1 };
4939 EVT VVT = Op.getOperand(0).getValueType();
4940 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4941 DAG.getUNDEF(VVT), Mask);
4942 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4943 DAG.getIntPtrConstant(0));
4944 } else if (VT.getSizeInBits() == 64) {
4945 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4946 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4947 // to match extract_elt for f64.
4948 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4952 // UNPCKHPD the element to the lowest double word, then movsd.
4953 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4954 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4955 int Mask[2] = { 1, -1 };
4956 EVT VVT = Op.getOperand(0).getValueType();
4957 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4958 DAG.getUNDEF(VVT), Mask);
4959 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4960 DAG.getIntPtrConstant(0));
4967 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4968 SelectionDAG &DAG) const {
4969 EVT VT = Op.getValueType();
4970 EVT EltVT = VT.getVectorElementType();
4971 DebugLoc dl = Op.getDebugLoc();
4973 SDValue N0 = Op.getOperand(0);
4974 SDValue N1 = Op.getOperand(1);
4975 SDValue N2 = Op.getOperand(2);
4977 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4978 isa<ConstantSDNode>(N2)) {
4980 if (VT == MVT::v8i16)
4981 Opc = X86ISD::PINSRW;
4982 else if (VT == MVT::v4i16)
4983 Opc = X86ISD::MMX_PINSRW;
4984 else if (VT == MVT::v16i8)
4985 Opc = X86ISD::PINSRB;
4987 Opc = X86ISD::PINSRB;
4989 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4991 if (N1.getValueType() != MVT::i32)
4992 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4993 if (N2.getValueType() != MVT::i32)
4994 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4995 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4996 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4997 // Bits [7:6] of the constant are the source select. This will always be
4998 // zero here. The DAG Combiner may combine an extract_elt index into these
4999 // bits. For example (insert (extract, 3), 2) could be matched by putting
5000 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5001 // Bits [5:4] of the constant are the destination select. This is the
5002 // value of the incoming immediate.
5003 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5004 // combine either bitwise AND or insert of float 0.0 to set these bits.
5005 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5006 // Create this as a scalar to vector..
5007 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5008 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5009 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5010 // PINSR* works with constant index.
5017 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5018 EVT VT = Op.getValueType();
5019 EVT EltVT = VT.getVectorElementType();
5021 if (Subtarget->hasSSE41())
5022 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5024 if (EltVT == MVT::i8)
5027 DebugLoc dl = Op.getDebugLoc();
5028 SDValue N0 = Op.getOperand(0);
5029 SDValue N1 = Op.getOperand(1);
5030 SDValue N2 = Op.getOperand(2);
5032 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5033 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5034 // as its second argument.
5035 if (N1.getValueType() != MVT::i32)
5036 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5037 if (N2.getValueType() != MVT::i32)
5038 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5039 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5040 dl, VT, N0, N1, N2);
5046 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5047 DebugLoc dl = Op.getDebugLoc();
5048 if (Op.getValueType() == MVT::v2f32)
5049 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5050 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5051 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5052 Op.getOperand(0))));
5054 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5055 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5057 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5058 EVT VT = MVT::v2i32;
5059 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5066 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5067 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5070 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5071 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5072 // one of the above mentioned nodes. It has to be wrapped because otherwise
5073 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5074 // be used to form addressing mode. These wrapped nodes will be selected
5077 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5078 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5080 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5082 unsigned char OpFlag = 0;
5083 unsigned WrapperKind = X86ISD::Wrapper;
5084 CodeModel::Model M = getTargetMachine().getCodeModel();
5086 if (Subtarget->isPICStyleRIPRel() &&
5087 (M == CodeModel::Small || M == CodeModel::Kernel))
5088 WrapperKind = X86ISD::WrapperRIP;
5089 else if (Subtarget->isPICStyleGOT())
5090 OpFlag = X86II::MO_GOTOFF;
5091 else if (Subtarget->isPICStyleStubPIC())
5092 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5094 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5096 CP->getOffset(), OpFlag);
5097 DebugLoc DL = CP->getDebugLoc();
5098 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5099 // With PIC, the address is actually $g + Offset.
5101 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5102 DAG.getNode(X86ISD::GlobalBaseReg,
5103 DebugLoc(), getPointerTy()),
5110 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5111 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5113 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5115 unsigned char OpFlag = 0;
5116 unsigned WrapperKind = X86ISD::Wrapper;
5117 CodeModel::Model M = getTargetMachine().getCodeModel();
5119 if (Subtarget->isPICStyleRIPRel() &&
5120 (M == CodeModel::Small || M == CodeModel::Kernel))
5121 WrapperKind = X86ISD::WrapperRIP;
5122 else if (Subtarget->isPICStyleGOT())
5123 OpFlag = X86II::MO_GOTOFF;
5124 else if (Subtarget->isPICStyleStubPIC())
5125 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5127 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5129 DebugLoc DL = JT->getDebugLoc();
5130 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5132 // With PIC, the address is actually $g + Offset.
5134 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5135 DAG.getNode(X86ISD::GlobalBaseReg,
5136 DebugLoc(), getPointerTy()),
5144 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5145 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5147 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5149 unsigned char OpFlag = 0;
5150 unsigned WrapperKind = X86ISD::Wrapper;
5151 CodeModel::Model M = getTargetMachine().getCodeModel();
5153 if (Subtarget->isPICStyleRIPRel() &&
5154 (M == CodeModel::Small || M == CodeModel::Kernel))
5155 WrapperKind = X86ISD::WrapperRIP;
5156 else if (Subtarget->isPICStyleGOT())
5157 OpFlag = X86II::MO_GOTOFF;
5158 else if (Subtarget->isPICStyleStubPIC())
5159 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5161 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5163 DebugLoc DL = Op.getDebugLoc();
5164 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5167 // With PIC, the address is actually $g + Offset.
5168 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5169 !Subtarget->is64Bit()) {
5170 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5171 DAG.getNode(X86ISD::GlobalBaseReg,
5172 DebugLoc(), getPointerTy()),
5180 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5181 // Create the TargetBlockAddressAddress node.
5182 unsigned char OpFlags =
5183 Subtarget->ClassifyBlockAddressReference();
5184 CodeModel::Model M = getTargetMachine().getCodeModel();
5185 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5186 DebugLoc dl = Op.getDebugLoc();
5187 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5188 /*isTarget=*/true, OpFlags);
5190 if (Subtarget->isPICStyleRIPRel() &&
5191 (M == CodeModel::Small || M == CodeModel::Kernel))
5192 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5194 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5196 // With PIC, the address is actually $g + Offset.
5197 if (isGlobalRelativeToPICBase(OpFlags)) {
5198 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5199 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5207 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5209 SelectionDAG &DAG) const {
5210 // Create the TargetGlobalAddress node, folding in the constant
5211 // offset if it is legal.
5212 unsigned char OpFlags =
5213 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5214 CodeModel::Model M = getTargetMachine().getCodeModel();
5216 if (OpFlags == X86II::MO_NO_FLAG &&
5217 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5218 // A direct static reference to a global.
5219 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5222 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5225 if (Subtarget->isPICStyleRIPRel() &&
5226 (M == CodeModel::Small || M == CodeModel::Kernel))
5227 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5229 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5231 // With PIC, the address is actually $g + Offset.
5232 if (isGlobalRelativeToPICBase(OpFlags)) {
5233 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5234 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5238 // For globals that require a load from a stub to get the address, emit the
5240 if (isGlobalStubReference(OpFlags))
5241 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5242 PseudoSourceValue::getGOT(), 0, false, false, 0);
5244 // If there was a non-zero offset that we didn't fold, create an explicit
5247 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5248 DAG.getConstant(Offset, getPointerTy()));
5254 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5255 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5256 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5257 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5261 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5262 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5263 unsigned char OperandFlags) {
5264 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5265 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5266 DebugLoc dl = GA->getDebugLoc();
5267 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5268 GA->getValueType(0),
5272 SDValue Ops[] = { Chain, TGA, *InFlag };
5273 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5275 SDValue Ops[] = { Chain, TGA };
5276 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5279 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5280 MFI->setAdjustsStack(true);
5282 SDValue Flag = Chain.getValue(1);
5283 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5286 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5288 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5291 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5292 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5293 DAG.getNode(X86ISD::GlobalBaseReg,
5294 DebugLoc(), PtrVT), InFlag);
5295 InFlag = Chain.getValue(1);
5297 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5300 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5302 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5304 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5305 X86::RAX, X86II::MO_TLSGD);
5308 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5309 // "local exec" model.
5310 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5311 const EVT PtrVT, TLSModel::Model model,
5313 DebugLoc dl = GA->getDebugLoc();
5314 // Get the Thread Pointer
5315 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5317 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5320 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5321 NULL, 0, false, false, 0);
5323 unsigned char OperandFlags = 0;
5324 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5326 unsigned WrapperKind = X86ISD::Wrapper;
5327 if (model == TLSModel::LocalExec) {
5328 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5329 } else if (is64Bit) {
5330 assert(model == TLSModel::InitialExec);
5331 OperandFlags = X86II::MO_GOTTPOFF;
5332 WrapperKind = X86ISD::WrapperRIP;
5334 assert(model == TLSModel::InitialExec);
5335 OperandFlags = X86II::MO_INDNTPOFF;
5338 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5340 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5341 GA->getOffset(), OperandFlags);
5342 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5344 if (model == TLSModel::InitialExec)
5345 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5346 PseudoSourceValue::getGOT(), 0, false, false, 0);
5348 // The address of the thread local variable is the add of the thread
5349 // pointer with the offset of the variable.
5350 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5354 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5355 // TODO: implement the "local dynamic" model
5356 // TODO: implement the "initial exec"model for pic executables
5357 assert(Subtarget->isTargetELF() &&
5358 "TLS not implemented for non-ELF targets");
5359 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5360 const GlobalValue *GV = GA->getGlobal();
5362 // If GV is an alias then use the aliasee for determining
5363 // thread-localness.
5364 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5365 GV = GA->resolveAliasedGlobal(false);
5367 TLSModel::Model model = getTLSModel(GV,
5368 getTargetMachine().getRelocationModel());
5371 case TLSModel::GeneralDynamic:
5372 case TLSModel::LocalDynamic: // not implemented
5373 if (Subtarget->is64Bit())
5374 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5375 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5377 case TLSModel::InitialExec:
5378 case TLSModel::LocalExec:
5379 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5380 Subtarget->is64Bit());
5383 llvm_unreachable("Unreachable");
5388 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5389 /// take a 2 x i32 value to shift plus a shift amount.
5390 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5391 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5392 EVT VT = Op.getValueType();
5393 unsigned VTBits = VT.getSizeInBits();
5394 DebugLoc dl = Op.getDebugLoc();
5395 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5396 SDValue ShOpLo = Op.getOperand(0);
5397 SDValue ShOpHi = Op.getOperand(1);
5398 SDValue ShAmt = Op.getOperand(2);
5399 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5400 DAG.getConstant(VTBits - 1, MVT::i8))
5401 : DAG.getConstant(0, VT);
5404 if (Op.getOpcode() == ISD::SHL_PARTS) {
5405 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5406 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5408 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5409 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5412 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5413 DAG.getConstant(VTBits, MVT::i8));
5414 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5415 AndNode, DAG.getConstant(0, MVT::i8));
5418 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5419 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5420 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5422 if (Op.getOpcode() == ISD::SHL_PARTS) {
5423 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5424 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5426 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5427 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5430 SDValue Ops[2] = { Lo, Hi };
5431 return DAG.getMergeValues(Ops, 2, dl);
5434 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5435 SelectionDAG &DAG) const {
5436 EVT SrcVT = Op.getOperand(0).getValueType();
5438 if (SrcVT.isVector()) {
5439 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5445 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5446 "Unknown SINT_TO_FP to lower!");
5448 // These are really Legal; return the operand so the caller accepts it as
5450 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5452 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5453 Subtarget->is64Bit()) {
5457 DebugLoc dl = Op.getDebugLoc();
5458 unsigned Size = SrcVT.getSizeInBits()/8;
5459 MachineFunction &MF = DAG.getMachineFunction();
5460 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5461 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5462 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5464 PseudoSourceValue::getFixedStack(SSFI), 0,
5466 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5469 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5471 SelectionDAG &DAG) const {
5473 DebugLoc dl = Op.getDebugLoc();
5475 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5477 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5479 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5480 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5481 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5482 Tys, Ops, array_lengthof(Ops));
5485 Chain = Result.getValue(1);
5486 SDValue InFlag = Result.getValue(2);
5488 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5489 // shouldn't be necessary except that RFP cannot be live across
5490 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5491 MachineFunction &MF = DAG.getMachineFunction();
5492 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5493 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5494 Tys = DAG.getVTList(MVT::Other);
5496 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5498 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5499 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5500 PseudoSourceValue::getFixedStack(SSFI), 0,
5507 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5508 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5509 SelectionDAG &DAG) const {
5510 // This algorithm is not obvious. Here it is in C code, more or less:
5512 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5513 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5514 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5516 // Copy ints to xmm registers.
5517 __m128i xh = _mm_cvtsi32_si128( hi );
5518 __m128i xl = _mm_cvtsi32_si128( lo );
5520 // Combine into low half of a single xmm register.
5521 __m128i x = _mm_unpacklo_epi32( xh, xl );
5525 // Merge in appropriate exponents to give the integer bits the right
5527 x = _mm_unpacklo_epi32( x, exp );
5529 // Subtract away the biases to deal with the IEEE-754 double precision
5531 d = _mm_sub_pd( (__m128d) x, bias );
5533 // All conversions up to here are exact. The correctly rounded result is
5534 // calculated using the current rounding mode using the following
5536 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5537 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5538 // store doesn't really need to be here (except
5539 // maybe to zero the other double)
5544 DebugLoc dl = Op.getDebugLoc();
5545 LLVMContext *Context = DAG.getContext();
5547 // Build some magic constants.
5548 std::vector<Constant*> CV0;
5549 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5550 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5551 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5552 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5553 Constant *C0 = ConstantVector::get(CV0);
5554 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5556 std::vector<Constant*> CV1;
5558 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5560 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5561 Constant *C1 = ConstantVector::get(CV1);
5562 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5564 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5565 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5567 DAG.getIntPtrConstant(1)));
5568 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5569 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5571 DAG.getIntPtrConstant(0)));
5572 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5573 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5574 PseudoSourceValue::getConstantPool(), 0,
5576 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5577 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5578 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5579 PseudoSourceValue::getConstantPool(), 0,
5581 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5583 // Add the halves; easiest way is to swap them into another reg first.
5584 int ShufMask[2] = { 1, -1 };
5585 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5586 DAG.getUNDEF(MVT::v2f64), ShufMask);
5587 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5588 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5589 DAG.getIntPtrConstant(0));
5592 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5593 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5594 SelectionDAG &DAG) const {
5595 DebugLoc dl = Op.getDebugLoc();
5596 // FP constant to bias correct the final result.
5597 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5600 // Load the 32-bit value into an XMM register.
5601 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5602 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5604 DAG.getIntPtrConstant(0)));
5606 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5607 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5608 DAG.getIntPtrConstant(0));
5610 // Or the load with the bias.
5611 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5612 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5613 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5615 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5616 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5617 MVT::v2f64, Bias)));
5618 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5619 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5620 DAG.getIntPtrConstant(0));
5622 // Subtract the bias.
5623 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5625 // Handle final rounding.
5626 EVT DestVT = Op.getValueType();
5628 if (DestVT.bitsLT(MVT::f64)) {
5629 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5630 DAG.getIntPtrConstant(0));
5631 } else if (DestVT.bitsGT(MVT::f64)) {
5632 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5635 // Handle final rounding.
5639 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5640 SelectionDAG &DAG) const {
5641 SDValue N0 = Op.getOperand(0);
5642 DebugLoc dl = Op.getDebugLoc();
5644 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5645 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5646 // the optimization here.
5647 if (DAG.SignBitIsZero(N0))
5648 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5650 EVT SrcVT = N0.getValueType();
5651 EVT DstVT = Op.getValueType();
5652 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5653 return LowerUINT_TO_FP_i64(Op, DAG);
5654 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5655 return LowerUINT_TO_FP_i32(Op, DAG);
5657 // Make a 64-bit buffer, and use it to build an FILD.
5658 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5659 if (SrcVT == MVT::i32) {
5660 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5661 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5662 getPointerTy(), StackSlot, WordOff);
5663 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5664 StackSlot, NULL, 0, false, false, 0);
5665 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5666 OffsetSlot, NULL, 0, false, false, 0);
5667 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5671 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5672 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5673 StackSlot, NULL, 0, false, false, 0);
5674 // For i64 source, we need to add the appropriate power of 2 if the input
5675 // was negative. This is the same as the optimization in
5676 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5677 // we must be careful to do the computation in x87 extended precision, not
5678 // in SSE. (The generic code can't know it's OK to do this, or how to.)
5679 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5680 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5681 SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5683 APInt FF(32, 0x5F800000ULL);
5685 // Check whether the sign bit is set.
5686 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5687 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5690 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5691 SDValue FudgePtr = DAG.getConstantPool(
5692 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5695 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5696 SDValue Zero = DAG.getIntPtrConstant(0);
5697 SDValue Four = DAG.getIntPtrConstant(4);
5698 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5700 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5702 // Load the value out, extending it from f32 to f80.
5703 // FIXME: Avoid the extend by constructing the right constant pool?
5704 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
5705 FudgePtr, PseudoSourceValue::getConstantPool(),
5706 0, MVT::f32, false, false, 4);
5707 // Extend everything to 80 bits to force it to be done on x87.
5708 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5709 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5712 std::pair<SDValue,SDValue> X86TargetLowering::
5713 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5714 DebugLoc dl = Op.getDebugLoc();
5716 EVT DstTy = Op.getValueType();
5719 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5723 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5724 DstTy.getSimpleVT() >= MVT::i16 &&
5725 "Unknown FP_TO_SINT to lower!");
5727 // These are really Legal.
5728 if (DstTy == MVT::i32 &&
5729 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5730 return std::make_pair(SDValue(), SDValue());
5731 if (Subtarget->is64Bit() &&
5732 DstTy == MVT::i64 &&
5733 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5734 return std::make_pair(SDValue(), SDValue());
5736 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5738 MachineFunction &MF = DAG.getMachineFunction();
5739 unsigned MemSize = DstTy.getSizeInBits()/8;
5740 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5741 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5744 switch (DstTy.getSimpleVT().SimpleTy) {
5745 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5746 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5747 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5748 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5751 SDValue Chain = DAG.getEntryNode();
5752 SDValue Value = Op.getOperand(0);
5753 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5754 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5755 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5756 PseudoSourceValue::getFixedStack(SSFI), 0,
5758 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5760 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5762 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5763 Chain = Value.getValue(1);
5764 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5765 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5768 // Build the FP_TO_INT*_IN_MEM
5769 SDValue Ops[] = { Chain, Value, StackSlot };
5770 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5772 return std::make_pair(FIST, StackSlot);
5775 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5776 SelectionDAG &DAG) const {
5777 if (Op.getValueType().isVector()) {
5778 if (Op.getValueType() == MVT::v2i32 &&
5779 Op.getOperand(0).getValueType() == MVT::v2f64) {
5785 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5786 SDValue FIST = Vals.first, StackSlot = Vals.second;
5787 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5788 if (FIST.getNode() == 0) return Op;
5791 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5792 FIST, StackSlot, NULL, 0, false, false, 0);
5795 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5796 SelectionDAG &DAG) const {
5797 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5798 SDValue FIST = Vals.first, StackSlot = Vals.second;
5799 assert(FIST.getNode() && "Unexpected failure");
5802 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5803 FIST, StackSlot, NULL, 0, false, false, 0);
5806 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5807 SelectionDAG &DAG) const {
5808 LLVMContext *Context = DAG.getContext();
5809 DebugLoc dl = Op.getDebugLoc();
5810 EVT VT = Op.getValueType();
5813 EltVT = VT.getVectorElementType();
5814 std::vector<Constant*> CV;
5815 if (EltVT == MVT::f64) {
5816 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5820 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5826 Constant *C = ConstantVector::get(CV);
5827 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5828 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5829 PseudoSourceValue::getConstantPool(), 0,
5831 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5834 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5835 LLVMContext *Context = DAG.getContext();
5836 DebugLoc dl = Op.getDebugLoc();
5837 EVT VT = Op.getValueType();
5840 EltVT = VT.getVectorElementType();
5841 std::vector<Constant*> CV;
5842 if (EltVT == MVT::f64) {
5843 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5847 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5853 Constant *C = ConstantVector::get(CV);
5854 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5855 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5856 PseudoSourceValue::getConstantPool(), 0,
5858 if (VT.isVector()) {
5859 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5860 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5861 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5863 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5865 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5869 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5870 LLVMContext *Context = DAG.getContext();
5871 SDValue Op0 = Op.getOperand(0);
5872 SDValue Op1 = Op.getOperand(1);
5873 DebugLoc dl = Op.getDebugLoc();
5874 EVT VT = Op.getValueType();
5875 EVT SrcVT = Op1.getValueType();
5877 // If second operand is smaller, extend it first.
5878 if (SrcVT.bitsLT(VT)) {
5879 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5882 // And if it is bigger, shrink it first.
5883 if (SrcVT.bitsGT(VT)) {
5884 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5888 // At this point the operands and the result should have the same
5889 // type, and that won't be f80 since that is not custom lowered.
5891 // First get the sign bit of second operand.
5892 std::vector<Constant*> CV;
5893 if (SrcVT == MVT::f64) {
5894 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5895 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5897 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5898 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5899 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5900 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5902 Constant *C = ConstantVector::get(CV);
5903 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5904 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5905 PseudoSourceValue::getConstantPool(), 0,
5907 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5909 // Shift sign bit right or left if the two operands have different types.
5910 if (SrcVT.bitsGT(VT)) {
5911 // Op0 is MVT::f32, Op1 is MVT::f64.
5912 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5913 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5914 DAG.getConstant(32, MVT::i32));
5915 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5916 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5917 DAG.getIntPtrConstant(0));
5920 // Clear first operand sign bit.
5922 if (VT == MVT::f64) {
5923 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5924 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5926 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5927 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5928 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5929 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5931 C = ConstantVector::get(CV);
5932 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5933 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5934 PseudoSourceValue::getConstantPool(), 0,
5936 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5938 // Or the value with the sign bit.
5939 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5942 /// Emit nodes that will be selected as "test Op0,Op0", or something
5944 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5945 SelectionDAG &DAG) const {
5946 DebugLoc dl = Op.getDebugLoc();
5948 // CF and OF aren't always set the way we want. Determine which
5949 // of these we need.
5950 bool NeedCF = false;
5951 bool NeedOF = false;
5953 case X86::COND_A: case X86::COND_AE:
5954 case X86::COND_B: case X86::COND_BE:
5957 case X86::COND_G: case X86::COND_GE:
5958 case X86::COND_L: case X86::COND_LE:
5959 case X86::COND_O: case X86::COND_NO:
5965 // See if we can use the EFLAGS value from the operand instead of
5966 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5967 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5968 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5969 unsigned Opcode = 0;
5970 unsigned NumOperands = 0;
5971 switch (Op.getNode()->getOpcode()) {
5973 // Due to an isel shortcoming, be conservative if this add is
5974 // likely to be selected as part of a load-modify-store
5975 // instruction. When the root node in a match is a store, isel
5976 // doesn't know how to remap non-chain non-flag uses of other
5977 // nodes in the match, such as the ADD in this case. This leads
5978 // to the ADD being left around and reselected, with the result
5979 // being two adds in the output. Alas, even if none our users
5980 // are stores, that doesn't prove we're O.K. Ergo, if we have
5981 // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5982 // A better fix seems to require climbing the DAG back to the
5983 // root, and it doesn't seem to be worth the effort.
5984 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5985 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5986 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5988 if (ConstantSDNode *C =
5989 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5990 // An add of one will be selected as an INC.
5991 if (C->getAPIntValue() == 1) {
5992 Opcode = X86ISD::INC;
5996 // An add of negative one (subtract of one) will be selected as a DEC.
5997 if (C->getAPIntValue().isAllOnesValue()) {
5998 Opcode = X86ISD::DEC;
6003 // Otherwise use a regular EFLAGS-setting add.
6004 Opcode = X86ISD::ADD;
6008 // If the primary and result isn't used, don't bother using X86ISD::AND,
6009 // because a TEST instruction will be better.
6010 bool NonFlagUse = false;
6011 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6012 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6014 unsigned UOpNo = UI.getOperandNo();
6015 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6016 // Look pass truncate.
6017 UOpNo = User->use_begin().getOperandNo();
6018 User = *User->use_begin();
6020 if (User->getOpcode() != ISD::BRCOND &&
6021 User->getOpcode() != ISD::SETCC &&
6022 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6034 // Due to the ISEL shortcoming noted above, be conservative if this op is
6035 // likely to be selected as part of a load-modify-store instruction.
6036 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6037 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6038 if (UI->getOpcode() == ISD::STORE)
6040 // Otherwise use a regular EFLAGS-setting instruction.
6041 switch (Op.getNode()->getOpcode()) {
6042 case ISD::SUB: Opcode = X86ISD::SUB; break;
6043 case ISD::OR: Opcode = X86ISD::OR; break;
6044 case ISD::XOR: Opcode = X86ISD::XOR; break;
6045 case ISD::AND: Opcode = X86ISD::AND; break;
6046 default: llvm_unreachable("unexpected operator!");
6057 return SDValue(Op.getNode(), 1);
6063 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6064 SmallVector<SDValue, 4> Ops;
6065 for (unsigned i = 0; i != NumOperands; ++i)
6066 Ops.push_back(Op.getOperand(i));
6067 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6068 DAG.ReplaceAllUsesWith(Op, New);
6069 return SDValue(New.getNode(), 1);
6073 // Otherwise just emit a CMP with 0, which is the TEST pattern.
6074 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6075 DAG.getConstant(0, Op.getValueType()));
6078 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6080 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6081 SelectionDAG &DAG) const {
6082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6083 if (C->getAPIntValue() == 0)
6084 return EmitTest(Op0, X86CC, DAG);
6086 DebugLoc dl = Op0.getDebugLoc();
6087 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6090 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6091 /// if it's possible.
6092 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6093 DebugLoc dl, SelectionDAG &DAG) const {
6094 SDValue Op0 = And.getOperand(0);
6095 SDValue Op1 = And.getOperand(1);
6096 if (Op0.getOpcode() == ISD::TRUNCATE)
6097 Op0 = Op0.getOperand(0);
6098 if (Op1.getOpcode() == ISD::TRUNCATE)
6099 Op1 = Op1.getOperand(0);
6102 if (Op1.getOpcode() == ISD::SHL) {
6103 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6104 if (And10C->getZExtValue() == 1) {
6106 RHS = Op1.getOperand(1);
6108 } else if (Op0.getOpcode() == ISD::SHL) {
6109 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6110 if (And00C->getZExtValue() == 1) {
6112 RHS = Op0.getOperand(1);
6114 } else if (Op1.getOpcode() == ISD::Constant) {
6115 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6116 SDValue AndLHS = Op0;
6117 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6118 LHS = AndLHS.getOperand(0);
6119 RHS = AndLHS.getOperand(1);
6123 if (LHS.getNode()) {
6124 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6125 // instruction. Since the shift amount is in-range-or-undefined, we know
6126 // that doing a bittest on the i32 value is ok. We extend to i32 because
6127 // the encoding for the i16 version is larger than the i32 version.
6128 // Also promote i16 to i32 for performance / code size reason.
6129 if (LHS.getValueType() == MVT::i8 ||
6130 LHS.getValueType() == MVT::i16)
6131 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6133 // If the operand types disagree, extend the shift amount to match. Since
6134 // BT ignores high bits (like shifts) we can use anyextend.
6135 if (LHS.getValueType() != RHS.getValueType())
6136 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6138 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6139 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6140 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6141 DAG.getConstant(Cond, MVT::i8), BT);
6147 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6148 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6149 SDValue Op0 = Op.getOperand(0);
6150 SDValue Op1 = Op.getOperand(1);
6151 DebugLoc dl = Op.getDebugLoc();
6152 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6154 // Optimize to BT if possible.
6155 // Lower (X & (1 << N)) == 0 to BT(X, N).
6156 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6157 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6158 if (Op0.getOpcode() == ISD::AND &&
6160 Op1.getOpcode() == ISD::Constant &&
6161 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6162 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6163 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6164 if (NewSetCC.getNode())
6168 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6169 if (Op0.getOpcode() == X86ISD::SETCC &&
6170 Op1.getOpcode() == ISD::Constant &&
6171 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6172 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6173 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6174 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6175 bool Invert = (CC == ISD::SETNE) ^
6176 cast<ConstantSDNode>(Op1)->isNullValue();
6178 CCode = X86::GetOppositeBranchCondition(CCode);
6179 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6180 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6183 bool isFP = Op1.getValueType().isFloatingPoint();
6184 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6185 if (X86CC == X86::COND_INVALID)
6188 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6190 // Use sbb x, x to materialize carry bit into a GPR.
6191 if (X86CC == X86::COND_B)
6192 return DAG.getNode(ISD::AND, dl, MVT::i8,
6193 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6194 DAG.getConstant(X86CC, MVT::i8), Cond),
6195 DAG.getConstant(1, MVT::i8));
6197 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6198 DAG.getConstant(X86CC, MVT::i8), Cond);
6201 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6203 SDValue Op0 = Op.getOperand(0);
6204 SDValue Op1 = Op.getOperand(1);
6205 SDValue CC = Op.getOperand(2);
6206 EVT VT = Op.getValueType();
6207 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6208 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6209 DebugLoc dl = Op.getDebugLoc();
6213 EVT VT0 = Op0.getValueType();
6214 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6215 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6218 switch (SetCCOpcode) {
6221 case ISD::SETEQ: SSECC = 0; break;
6223 case ISD::SETGT: Swap = true; // Fallthrough
6225 case ISD::SETOLT: SSECC = 1; break;
6227 case ISD::SETGE: Swap = true; // Fallthrough
6229 case ISD::SETOLE: SSECC = 2; break;
6230 case ISD::SETUO: SSECC = 3; break;
6232 case ISD::SETNE: SSECC = 4; break;
6233 case ISD::SETULE: Swap = true;
6234 case ISD::SETUGE: SSECC = 5; break;
6235 case ISD::SETULT: Swap = true;
6236 case ISD::SETUGT: SSECC = 6; break;
6237 case ISD::SETO: SSECC = 7; break;
6240 std::swap(Op0, Op1);
6242 // In the two special cases we can't handle, emit two comparisons.
6244 if (SetCCOpcode == ISD::SETUEQ) {
6246 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6247 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6248 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6250 else if (SetCCOpcode == ISD::SETONE) {
6252 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6253 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6254 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6256 llvm_unreachable("Illegal FP comparison");
6258 // Handle all other FP comparisons here.
6259 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6262 // We are handling one of the integer comparisons here. Since SSE only has
6263 // GT and EQ comparisons for integer, swapping operands and multiple
6264 // operations may be required for some comparisons.
6265 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6266 bool Swap = false, Invert = false, FlipSigns = false;
6268 switch (VT.getSimpleVT().SimpleTy) {
6271 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6273 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6275 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6276 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6279 switch (SetCCOpcode) {
6281 case ISD::SETNE: Invert = true;
6282 case ISD::SETEQ: Opc = EQOpc; break;
6283 case ISD::SETLT: Swap = true;
6284 case ISD::SETGT: Opc = GTOpc; break;
6285 case ISD::SETGE: Swap = true;
6286 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6287 case ISD::SETULT: Swap = true;
6288 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6289 case ISD::SETUGE: Swap = true;
6290 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6293 std::swap(Op0, Op1);
6295 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6296 // bits of the inputs before performing those operations.
6298 EVT EltVT = VT.getVectorElementType();
6299 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6301 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6302 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6304 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6305 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6308 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6310 // If the logical-not of the result is required, perform that now.
6312 Result = DAG.getNOT(dl, Result, VT);
6317 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6318 static bool isX86LogicalCmp(SDValue Op) {
6319 unsigned Opc = Op.getNode()->getOpcode();
6320 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6322 if (Op.getResNo() == 1 &&
6323 (Opc == X86ISD::ADD ||
6324 Opc == X86ISD::SUB ||
6325 Opc == X86ISD::SMUL ||
6326 Opc == X86ISD::UMUL ||
6327 Opc == X86ISD::INC ||
6328 Opc == X86ISD::DEC ||
6329 Opc == X86ISD::OR ||
6330 Opc == X86ISD::XOR ||
6331 Opc == X86ISD::AND))
6337 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6338 bool addTest = true;
6339 SDValue Cond = Op.getOperand(0);
6340 DebugLoc dl = Op.getDebugLoc();
6343 if (Cond.getOpcode() == ISD::SETCC) {
6344 SDValue NewCond = LowerSETCC(Cond, DAG);
6345 if (NewCond.getNode())
6349 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6350 SDValue Op1 = Op.getOperand(1);
6351 SDValue Op2 = Op.getOperand(2);
6352 if (Cond.getOpcode() == X86ISD::SETCC &&
6353 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6354 SDValue Cmp = Cond.getOperand(1);
6355 if (Cmp.getOpcode() == X86ISD::CMP) {
6356 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6357 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6358 ConstantSDNode *RHSC =
6359 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6360 if (N1C && N1C->isAllOnesValue() &&
6361 N2C && N2C->isNullValue() &&
6362 RHSC && RHSC->isNullValue()) {
6363 SDValue CmpOp0 = Cmp.getOperand(0);
6364 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6365 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6366 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6367 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6372 // Look pass (and (setcc_carry (cmp ...)), 1).
6373 if (Cond.getOpcode() == ISD::AND &&
6374 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6375 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6376 if (C && C->getAPIntValue() == 1)
6377 Cond = Cond.getOperand(0);
6380 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6381 // setting operand in place of the X86ISD::SETCC.
6382 if (Cond.getOpcode() == X86ISD::SETCC ||
6383 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6384 CC = Cond.getOperand(0);
6386 SDValue Cmp = Cond.getOperand(1);
6387 unsigned Opc = Cmp.getOpcode();
6388 EVT VT = Op.getValueType();
6390 bool IllegalFPCMov = false;
6391 if (VT.isFloatingPoint() && !VT.isVector() &&
6392 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6393 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6395 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6396 Opc == X86ISD::BT) { // FIXME
6403 // Look pass the truncate.
6404 if (Cond.getOpcode() == ISD::TRUNCATE)
6405 Cond = Cond.getOperand(0);
6407 // We know the result of AND is compared against zero. Try to match
6409 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6410 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6411 if (NewSetCC.getNode()) {
6412 CC = NewSetCC.getOperand(0);
6413 Cond = NewSetCC.getOperand(1);
6420 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6421 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6424 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6425 // condition is true.
6426 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6427 SDValue Ops[] = { Op2, Op1, CC, Cond };
6428 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6431 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6432 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6433 // from the AND / OR.
6434 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6435 Opc = Op.getOpcode();
6436 if (Opc != ISD::OR && Opc != ISD::AND)
6438 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6439 Op.getOperand(0).hasOneUse() &&
6440 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6441 Op.getOperand(1).hasOneUse());
6444 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6445 // 1 and that the SETCC node has a single use.
6446 static bool isXor1OfSetCC(SDValue Op) {
6447 if (Op.getOpcode() != ISD::XOR)
6449 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6450 if (N1C && N1C->getAPIntValue() == 1) {
6451 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6452 Op.getOperand(0).hasOneUse();
6457 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6458 bool addTest = true;
6459 SDValue Chain = Op.getOperand(0);
6460 SDValue Cond = Op.getOperand(1);
6461 SDValue Dest = Op.getOperand(2);
6462 DebugLoc dl = Op.getDebugLoc();
6465 if (Cond.getOpcode() == ISD::SETCC) {
6466 SDValue NewCond = LowerSETCC(Cond, DAG);
6467 if (NewCond.getNode())
6471 // FIXME: LowerXALUO doesn't handle these!!
6472 else if (Cond.getOpcode() == X86ISD::ADD ||
6473 Cond.getOpcode() == X86ISD::SUB ||
6474 Cond.getOpcode() == X86ISD::SMUL ||
6475 Cond.getOpcode() == X86ISD::UMUL)
6476 Cond = LowerXALUO(Cond, DAG);
6479 // Look pass (and (setcc_carry (cmp ...)), 1).
6480 if (Cond.getOpcode() == ISD::AND &&
6481 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6482 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6483 if (C && C->getAPIntValue() == 1)
6484 Cond = Cond.getOperand(0);
6487 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6488 // setting operand in place of the X86ISD::SETCC.
6489 if (Cond.getOpcode() == X86ISD::SETCC ||
6490 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6491 CC = Cond.getOperand(0);
6493 SDValue Cmp = Cond.getOperand(1);
6494 unsigned Opc = Cmp.getOpcode();
6495 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6496 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6500 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6504 // These can only come from an arithmetic instruction with overflow,
6505 // e.g. SADDO, UADDO.
6506 Cond = Cond.getNode()->getOperand(1);
6513 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6514 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6515 if (CondOpc == ISD::OR) {
6516 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6517 // two branches instead of an explicit OR instruction with a
6519 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6520 isX86LogicalCmp(Cmp)) {
6521 CC = Cond.getOperand(0).getOperand(0);
6522 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6523 Chain, Dest, CC, Cmp);
6524 CC = Cond.getOperand(1).getOperand(0);
6528 } else { // ISD::AND
6529 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6530 // two branches instead of an explicit AND instruction with a
6531 // separate test. However, we only do this if this block doesn't
6532 // have a fall-through edge, because this requires an explicit
6533 // jmp when the condition is false.
6534 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6535 isX86LogicalCmp(Cmp) &&
6536 Op.getNode()->hasOneUse()) {
6537 X86::CondCode CCode =
6538 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6539 CCode = X86::GetOppositeBranchCondition(CCode);
6540 CC = DAG.getConstant(CCode, MVT::i8);
6541 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6542 // Look for an unconditional branch following this conditional branch.
6543 // We need this because we need to reverse the successors in order
6544 // to implement FCMP_OEQ.
6545 if (User.getOpcode() == ISD::BR) {
6546 SDValue FalseBB = User.getOperand(1);
6548 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6549 assert(NewBR == User);
6552 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6553 Chain, Dest, CC, Cmp);
6554 X86::CondCode CCode =
6555 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6556 CCode = X86::GetOppositeBranchCondition(CCode);
6557 CC = DAG.getConstant(CCode, MVT::i8);
6563 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6564 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6565 // It should be transformed during dag combiner except when the condition
6566 // is set by a arithmetics with overflow node.
6567 X86::CondCode CCode =
6568 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6569 CCode = X86::GetOppositeBranchCondition(CCode);
6570 CC = DAG.getConstant(CCode, MVT::i8);
6571 Cond = Cond.getOperand(0).getOperand(1);
6577 // Look pass the truncate.
6578 if (Cond.getOpcode() == ISD::TRUNCATE)
6579 Cond = Cond.getOperand(0);
6581 // We know the result of AND is compared against zero. Try to match
6583 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6584 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6585 if (NewSetCC.getNode()) {
6586 CC = NewSetCC.getOperand(0);
6587 Cond = NewSetCC.getOperand(1);
6594 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6595 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6597 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6598 Chain, Dest, CC, Cond);
6602 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6603 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6604 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6605 // that the guard pages used by the OS virtual memory manager are allocated in
6606 // correct sequence.
6608 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6609 SelectionDAG &DAG) const {
6610 assert(Subtarget->isTargetCygMing() &&
6611 "This should be used only on Cygwin/Mingw targets");
6612 DebugLoc dl = Op.getDebugLoc();
6615 SDValue Chain = Op.getOperand(0);
6616 SDValue Size = Op.getOperand(1);
6617 // FIXME: Ensure alignment here
6621 EVT IntPtr = getPointerTy();
6622 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6624 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6625 Flag = Chain.getValue(1);
6627 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6629 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6630 Flag = Chain.getValue(1);
6632 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6634 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6635 return DAG.getMergeValues(Ops1, 2, dl);
6638 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6639 MachineFunction &MF = DAG.getMachineFunction();
6640 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6642 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6643 DebugLoc dl = Op.getDebugLoc();
6645 if (!Subtarget->is64Bit()) {
6646 // vastart just stores the address of the VarArgsFrameIndex slot into the
6647 // memory location argument.
6648 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6650 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6655 // gp_offset (0 - 6 * 8)
6656 // fp_offset (48 - 48 + 8 * 16)
6657 // overflow_arg_area (point to parameters coming in memory).
6659 SmallVector<SDValue, 8> MemOps;
6660 SDValue FIN = Op.getOperand(1);
6662 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6663 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6665 FIN, SV, 0, false, false, 0);
6666 MemOps.push_back(Store);
6669 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6670 FIN, DAG.getIntPtrConstant(4));
6671 Store = DAG.getStore(Op.getOperand(0), dl,
6672 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6674 FIN, SV, 0, false, false, 0);
6675 MemOps.push_back(Store);
6677 // Store ptr to overflow_arg_area
6678 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6679 FIN, DAG.getIntPtrConstant(4));
6680 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6682 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6684 MemOps.push_back(Store);
6686 // Store ptr to reg_save_area.
6687 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6688 FIN, DAG.getIntPtrConstant(8));
6689 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6691 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6693 MemOps.push_back(Store);
6694 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6695 &MemOps[0], MemOps.size());
6698 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6699 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6700 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6701 SDValue Chain = Op.getOperand(0);
6702 SDValue SrcPtr = Op.getOperand(1);
6703 SDValue SrcSV = Op.getOperand(2);
6705 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6709 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6710 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6711 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6712 SDValue Chain = Op.getOperand(0);
6713 SDValue DstPtr = Op.getOperand(1);
6714 SDValue SrcPtr = Op.getOperand(2);
6715 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6716 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6717 DebugLoc dl = Op.getDebugLoc();
6719 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6720 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6721 false, DstSV, 0, SrcSV, 0);
6725 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6726 DebugLoc dl = Op.getDebugLoc();
6727 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6729 default: return SDValue(); // Don't custom lower most intrinsics.
6730 // Comparison intrinsics.
6731 case Intrinsic::x86_sse_comieq_ss:
6732 case Intrinsic::x86_sse_comilt_ss:
6733 case Intrinsic::x86_sse_comile_ss:
6734 case Intrinsic::x86_sse_comigt_ss:
6735 case Intrinsic::x86_sse_comige_ss:
6736 case Intrinsic::x86_sse_comineq_ss:
6737 case Intrinsic::x86_sse_ucomieq_ss:
6738 case Intrinsic::x86_sse_ucomilt_ss:
6739 case Intrinsic::x86_sse_ucomile_ss:
6740 case Intrinsic::x86_sse_ucomigt_ss:
6741 case Intrinsic::x86_sse_ucomige_ss:
6742 case Intrinsic::x86_sse_ucomineq_ss:
6743 case Intrinsic::x86_sse2_comieq_sd:
6744 case Intrinsic::x86_sse2_comilt_sd:
6745 case Intrinsic::x86_sse2_comile_sd:
6746 case Intrinsic::x86_sse2_comigt_sd:
6747 case Intrinsic::x86_sse2_comige_sd:
6748 case Intrinsic::x86_sse2_comineq_sd:
6749 case Intrinsic::x86_sse2_ucomieq_sd:
6750 case Intrinsic::x86_sse2_ucomilt_sd:
6751 case Intrinsic::x86_sse2_ucomile_sd:
6752 case Intrinsic::x86_sse2_ucomigt_sd:
6753 case Intrinsic::x86_sse2_ucomige_sd:
6754 case Intrinsic::x86_sse2_ucomineq_sd: {
6756 ISD::CondCode CC = ISD::SETCC_INVALID;
6759 case Intrinsic::x86_sse_comieq_ss:
6760 case Intrinsic::x86_sse2_comieq_sd:
6764 case Intrinsic::x86_sse_comilt_ss:
6765 case Intrinsic::x86_sse2_comilt_sd:
6769 case Intrinsic::x86_sse_comile_ss:
6770 case Intrinsic::x86_sse2_comile_sd:
6774 case Intrinsic::x86_sse_comigt_ss:
6775 case Intrinsic::x86_sse2_comigt_sd:
6779 case Intrinsic::x86_sse_comige_ss:
6780 case Intrinsic::x86_sse2_comige_sd:
6784 case Intrinsic::x86_sse_comineq_ss:
6785 case Intrinsic::x86_sse2_comineq_sd:
6789 case Intrinsic::x86_sse_ucomieq_ss:
6790 case Intrinsic::x86_sse2_ucomieq_sd:
6791 Opc = X86ISD::UCOMI;
6794 case Intrinsic::x86_sse_ucomilt_ss:
6795 case Intrinsic::x86_sse2_ucomilt_sd:
6796 Opc = X86ISD::UCOMI;
6799 case Intrinsic::x86_sse_ucomile_ss:
6800 case Intrinsic::x86_sse2_ucomile_sd:
6801 Opc = X86ISD::UCOMI;
6804 case Intrinsic::x86_sse_ucomigt_ss:
6805 case Intrinsic::x86_sse2_ucomigt_sd:
6806 Opc = X86ISD::UCOMI;
6809 case Intrinsic::x86_sse_ucomige_ss:
6810 case Intrinsic::x86_sse2_ucomige_sd:
6811 Opc = X86ISD::UCOMI;
6814 case Intrinsic::x86_sse_ucomineq_ss:
6815 case Intrinsic::x86_sse2_ucomineq_sd:
6816 Opc = X86ISD::UCOMI;
6821 SDValue LHS = Op.getOperand(1);
6822 SDValue RHS = Op.getOperand(2);
6823 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6824 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6825 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6826 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6827 DAG.getConstant(X86CC, MVT::i8), Cond);
6828 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6830 // ptest intrinsics. The intrinsic these come from are designed to return
6831 // an integer value, not just an instruction so lower it to the ptest
6832 // pattern and a setcc for the result.
6833 case Intrinsic::x86_sse41_ptestz:
6834 case Intrinsic::x86_sse41_ptestc:
6835 case Intrinsic::x86_sse41_ptestnzc:{
6838 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6839 case Intrinsic::x86_sse41_ptestz:
6841 X86CC = X86::COND_E;
6843 case Intrinsic::x86_sse41_ptestc:
6845 X86CC = X86::COND_B;
6847 case Intrinsic::x86_sse41_ptestnzc:
6849 X86CC = X86::COND_A;
6853 SDValue LHS = Op.getOperand(1);
6854 SDValue RHS = Op.getOperand(2);
6855 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6856 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6857 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6858 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6861 // Fix vector shift instructions where the last operand is a non-immediate
6863 case Intrinsic::x86_sse2_pslli_w:
6864 case Intrinsic::x86_sse2_pslli_d:
6865 case Intrinsic::x86_sse2_pslli_q:
6866 case Intrinsic::x86_sse2_psrli_w:
6867 case Intrinsic::x86_sse2_psrli_d:
6868 case Intrinsic::x86_sse2_psrli_q:
6869 case Intrinsic::x86_sse2_psrai_w:
6870 case Intrinsic::x86_sse2_psrai_d:
6871 case Intrinsic::x86_mmx_pslli_w:
6872 case Intrinsic::x86_mmx_pslli_d:
6873 case Intrinsic::x86_mmx_pslli_q:
6874 case Intrinsic::x86_mmx_psrli_w:
6875 case Intrinsic::x86_mmx_psrli_d:
6876 case Intrinsic::x86_mmx_psrli_q:
6877 case Intrinsic::x86_mmx_psrai_w:
6878 case Intrinsic::x86_mmx_psrai_d: {
6879 SDValue ShAmt = Op.getOperand(2);
6880 if (isa<ConstantSDNode>(ShAmt))
6883 unsigned NewIntNo = 0;
6884 EVT ShAmtVT = MVT::v4i32;
6886 case Intrinsic::x86_sse2_pslli_w:
6887 NewIntNo = Intrinsic::x86_sse2_psll_w;
6889 case Intrinsic::x86_sse2_pslli_d:
6890 NewIntNo = Intrinsic::x86_sse2_psll_d;
6892 case Intrinsic::x86_sse2_pslli_q:
6893 NewIntNo = Intrinsic::x86_sse2_psll_q;
6895 case Intrinsic::x86_sse2_psrli_w:
6896 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6898 case Intrinsic::x86_sse2_psrli_d:
6899 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6901 case Intrinsic::x86_sse2_psrli_q:
6902 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6904 case Intrinsic::x86_sse2_psrai_w:
6905 NewIntNo = Intrinsic::x86_sse2_psra_w;
6907 case Intrinsic::x86_sse2_psrai_d:
6908 NewIntNo = Intrinsic::x86_sse2_psra_d;
6911 ShAmtVT = MVT::v2i32;
6913 case Intrinsic::x86_mmx_pslli_w:
6914 NewIntNo = Intrinsic::x86_mmx_psll_w;
6916 case Intrinsic::x86_mmx_pslli_d:
6917 NewIntNo = Intrinsic::x86_mmx_psll_d;
6919 case Intrinsic::x86_mmx_pslli_q:
6920 NewIntNo = Intrinsic::x86_mmx_psll_q;
6922 case Intrinsic::x86_mmx_psrli_w:
6923 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6925 case Intrinsic::x86_mmx_psrli_d:
6926 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6928 case Intrinsic::x86_mmx_psrli_q:
6929 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6931 case Intrinsic::x86_mmx_psrai_w:
6932 NewIntNo = Intrinsic::x86_mmx_psra_w;
6934 case Intrinsic::x86_mmx_psrai_d:
6935 NewIntNo = Intrinsic::x86_mmx_psra_d;
6937 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6943 // The vector shift intrinsics with scalars uses 32b shift amounts but
6944 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6948 ShOps[1] = DAG.getConstant(0, MVT::i32);
6949 if (ShAmtVT == MVT::v4i32) {
6950 ShOps[2] = DAG.getUNDEF(MVT::i32);
6951 ShOps[3] = DAG.getUNDEF(MVT::i32);
6952 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6954 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6957 EVT VT = Op.getValueType();
6958 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6959 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6960 DAG.getConstant(NewIntNo, MVT::i32),
6961 Op.getOperand(1), ShAmt);
6966 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
6967 SelectionDAG &DAG) const {
6968 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6969 DebugLoc dl = Op.getDebugLoc();
6972 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6974 DAG.getConstant(TD->getPointerSize(),
6975 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6976 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6977 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6979 NULL, 0, false, false, 0);
6982 // Just load the return address.
6983 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6984 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6985 RetAddrFI, NULL, 0, false, false, 0);
6988 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6989 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6990 MFI->setFrameAddressIsTaken(true);
6991 EVT VT = Op.getValueType();
6992 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6993 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6994 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6995 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6997 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7002 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7003 SelectionDAG &DAG) const {
7004 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7007 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7008 MachineFunction &MF = DAG.getMachineFunction();
7009 SDValue Chain = Op.getOperand(0);
7010 SDValue Offset = Op.getOperand(1);
7011 SDValue Handler = Op.getOperand(2);
7012 DebugLoc dl = Op.getDebugLoc();
7014 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7016 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7018 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7019 DAG.getIntPtrConstant(-TD->getPointerSize()));
7020 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7021 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7022 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7023 MF.getRegInfo().addLiveOut(StoreAddrReg);
7025 return DAG.getNode(X86ISD::EH_RETURN, dl,
7027 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7030 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7031 SelectionDAG &DAG) const {
7032 SDValue Root = Op.getOperand(0);
7033 SDValue Trmp = Op.getOperand(1); // trampoline
7034 SDValue FPtr = Op.getOperand(2); // nested function
7035 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7036 DebugLoc dl = Op.getDebugLoc();
7038 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7040 if (Subtarget->is64Bit()) {
7041 SDValue OutChains[6];
7043 // Large code-model.
7044 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7045 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7047 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7048 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7050 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7052 // Load the pointer to the nested function into R11.
7053 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7054 SDValue Addr = Trmp;
7055 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7056 Addr, TrmpAddr, 0, false, false, 0);
7058 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7059 DAG.getConstant(2, MVT::i64));
7060 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7063 // Load the 'nest' parameter value into R10.
7064 // R10 is specified in X86CallingConv.td
7065 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7066 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7067 DAG.getConstant(10, MVT::i64));
7068 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7069 Addr, TrmpAddr, 10, false, false, 0);
7071 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7072 DAG.getConstant(12, MVT::i64));
7073 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7076 // Jump to the nested function.
7077 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7078 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7079 DAG.getConstant(20, MVT::i64));
7080 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7081 Addr, TrmpAddr, 20, false, false, 0);
7083 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7084 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7085 DAG.getConstant(22, MVT::i64));
7086 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7087 TrmpAddr, 22, false, false, 0);
7090 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7091 return DAG.getMergeValues(Ops, 2, dl);
7093 const Function *Func =
7094 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7095 CallingConv::ID CC = Func->getCallingConv();
7100 llvm_unreachable("Unsupported calling convention");
7101 case CallingConv::C:
7102 case CallingConv::X86_StdCall: {
7103 // Pass 'nest' parameter in ECX.
7104 // Must be kept in sync with X86CallingConv.td
7107 // Check that ECX wasn't needed by an 'inreg' parameter.
7108 const FunctionType *FTy = Func->getFunctionType();
7109 const AttrListPtr &Attrs = Func->getAttributes();
7111 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7112 unsigned InRegCount = 0;
7115 for (FunctionType::param_iterator I = FTy->param_begin(),
7116 E = FTy->param_end(); I != E; ++I, ++Idx)
7117 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7118 // FIXME: should only count parameters that are lowered to integers.
7119 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7121 if (InRegCount > 2) {
7122 report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7127 case CallingConv::X86_FastCall:
7128 case CallingConv::X86_ThisCall:
7129 case CallingConv::Fast:
7130 // Pass 'nest' parameter in EAX.
7131 // Must be kept in sync with X86CallingConv.td
7136 SDValue OutChains[4];
7139 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7140 DAG.getConstant(10, MVT::i32));
7141 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7143 // This is storing the opcode for MOV32ri.
7144 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7145 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7146 OutChains[0] = DAG.getStore(Root, dl,
7147 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7148 Trmp, TrmpAddr, 0, false, false, 0);
7150 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7151 DAG.getConstant(1, MVT::i32));
7152 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7155 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7156 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7157 DAG.getConstant(5, MVT::i32));
7158 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7159 TrmpAddr, 5, false, false, 1);
7161 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7162 DAG.getConstant(6, MVT::i32));
7163 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7167 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7168 return DAG.getMergeValues(Ops, 2, dl);
7172 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7173 SelectionDAG &DAG) const {
7175 The rounding mode is in bits 11:10 of FPSR, and has the following
7182 FLT_ROUNDS, on the other hand, expects the following:
7189 To perform the conversion, we do:
7190 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7193 MachineFunction &MF = DAG.getMachineFunction();
7194 const TargetMachine &TM = MF.getTarget();
7195 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7196 unsigned StackAlignment = TFI.getStackAlignment();
7197 EVT VT = Op.getValueType();
7198 DebugLoc dl = Op.getDebugLoc();
7200 // Save FP Control Word to stack slot
7201 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7202 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7204 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7205 DAG.getEntryNode(), StackSlot);
7207 // Load FP Control Word from stack slot
7208 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7211 // Transform as necessary
7213 DAG.getNode(ISD::SRL, dl, MVT::i16,
7214 DAG.getNode(ISD::AND, dl, MVT::i16,
7215 CWD, DAG.getConstant(0x800, MVT::i16)),
7216 DAG.getConstant(11, MVT::i8));
7218 DAG.getNode(ISD::SRL, dl, MVT::i16,
7219 DAG.getNode(ISD::AND, dl, MVT::i16,
7220 CWD, DAG.getConstant(0x400, MVT::i16)),
7221 DAG.getConstant(9, MVT::i8));
7224 DAG.getNode(ISD::AND, dl, MVT::i16,
7225 DAG.getNode(ISD::ADD, dl, MVT::i16,
7226 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7227 DAG.getConstant(1, MVT::i16)),
7228 DAG.getConstant(3, MVT::i16));
7231 return DAG.getNode((VT.getSizeInBits() < 16 ?
7232 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7235 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7236 EVT VT = Op.getValueType();
7238 unsigned NumBits = VT.getSizeInBits();
7239 DebugLoc dl = Op.getDebugLoc();
7241 Op = Op.getOperand(0);
7242 if (VT == MVT::i8) {
7243 // Zero extend to i32 since there is not an i8 bsr.
7245 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7248 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7249 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7250 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7252 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7255 DAG.getConstant(NumBits+NumBits-1, OpVT),
7256 DAG.getConstant(X86::COND_E, MVT::i8),
7259 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7261 // Finally xor with NumBits-1.
7262 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7265 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7269 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7270 EVT VT = Op.getValueType();
7272 unsigned NumBits = VT.getSizeInBits();
7273 DebugLoc dl = Op.getDebugLoc();
7275 Op = Op.getOperand(0);
7276 if (VT == MVT::i8) {
7278 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7281 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7282 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7283 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7285 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7288 DAG.getConstant(NumBits, OpVT),
7289 DAG.getConstant(X86::COND_E, MVT::i8),
7292 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7295 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7299 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7300 EVT VT = Op.getValueType();
7301 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7302 DebugLoc dl = Op.getDebugLoc();
7304 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7305 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7306 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7307 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7308 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7310 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7311 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7312 // return AloBlo + AloBhi + AhiBlo;
7314 SDValue A = Op.getOperand(0);
7315 SDValue B = Op.getOperand(1);
7317 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7318 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7319 A, DAG.getConstant(32, MVT::i32));
7320 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7321 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7322 B, DAG.getConstant(32, MVT::i32));
7323 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7324 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7326 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7327 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7329 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7330 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7332 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7333 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7334 AloBhi, DAG.getConstant(32, MVT::i32));
7335 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7336 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7337 AhiBlo, DAG.getConstant(32, MVT::i32));
7338 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7339 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7344 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7345 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7346 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7347 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7348 // has only one use.
7349 SDNode *N = Op.getNode();
7350 SDValue LHS = N->getOperand(0);
7351 SDValue RHS = N->getOperand(1);
7352 unsigned BaseOp = 0;
7354 DebugLoc dl = Op.getDebugLoc();
7356 switch (Op.getOpcode()) {
7357 default: llvm_unreachable("Unknown ovf instruction!");
7359 // A subtract of one will be selected as a INC. Note that INC doesn't
7360 // set CF, so we can't do this for UADDO.
7361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7362 if (C->getAPIntValue() == 1) {
7363 BaseOp = X86ISD::INC;
7367 BaseOp = X86ISD::ADD;
7371 BaseOp = X86ISD::ADD;
7375 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7376 // set CF, so we can't do this for USUBO.
7377 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7378 if (C->getAPIntValue() == 1) {
7379 BaseOp = X86ISD::DEC;
7383 BaseOp = X86ISD::SUB;
7387 BaseOp = X86ISD::SUB;
7391 BaseOp = X86ISD::SMUL;
7395 BaseOp = X86ISD::UMUL;
7400 // Also sets EFLAGS.
7401 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7402 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7405 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7406 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7408 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7412 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7413 EVT T = Op.getValueType();
7414 DebugLoc dl = Op.getDebugLoc();
7417 switch(T.getSimpleVT().SimpleTy) {
7419 assert(false && "Invalid value type!");
7420 case MVT::i8: Reg = X86::AL; size = 1; break;
7421 case MVT::i16: Reg = X86::AX; size = 2; break;
7422 case MVT::i32: Reg = X86::EAX; size = 4; break;
7424 assert(Subtarget->is64Bit() && "Node not type legal!");
7425 Reg = X86::RAX; size = 8;
7428 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7429 Op.getOperand(2), SDValue());
7430 SDValue Ops[] = { cpIn.getValue(0),
7433 DAG.getTargetConstant(size, MVT::i8),
7435 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7436 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7438 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7442 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7443 SelectionDAG &DAG) const {
7444 assert(Subtarget->is64Bit() && "Result not type legalized?");
7445 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7446 SDValue TheChain = Op.getOperand(0);
7447 DebugLoc dl = Op.getDebugLoc();
7448 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7449 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7450 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7452 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7453 DAG.getConstant(32, MVT::i8));
7455 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7458 return DAG.getMergeValues(Ops, 2, dl);
7461 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7462 SDNode *Node = Op.getNode();
7463 DebugLoc dl = Node->getDebugLoc();
7464 EVT T = Node->getValueType(0);
7465 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7466 DAG.getConstant(0, T), Node->getOperand(2));
7467 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7468 cast<AtomicSDNode>(Node)->getMemoryVT(),
7469 Node->getOperand(0),
7470 Node->getOperand(1), negOp,
7471 cast<AtomicSDNode>(Node)->getSrcValue(),
7472 cast<AtomicSDNode>(Node)->getAlignment());
7475 /// LowerOperation - Provide custom lowering hooks for some operations.
7477 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7478 switch (Op.getOpcode()) {
7479 default: llvm_unreachable("Should not custom lower this!");
7480 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7481 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7482 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7483 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7484 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7485 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7486 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7487 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7488 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7489 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7490 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7491 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7492 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7493 case ISD::SHL_PARTS:
7494 case ISD::SRA_PARTS:
7495 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7496 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7497 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7498 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7499 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7500 case ISD::FABS: return LowerFABS(Op, DAG);
7501 case ISD::FNEG: return LowerFNEG(Op, DAG);
7502 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7503 case ISD::SETCC: return LowerSETCC(Op, DAG);
7504 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7505 case ISD::SELECT: return LowerSELECT(Op, DAG);
7506 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7507 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7508 case ISD::VASTART: return LowerVASTART(Op, DAG);
7509 case ISD::VAARG: return LowerVAARG(Op, DAG);
7510 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7511 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7512 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7513 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7514 case ISD::FRAME_TO_ARGS_OFFSET:
7515 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7516 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7517 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7518 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7519 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7520 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7521 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7522 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7528 case ISD::UMULO: return LowerXALUO(Op, DAG);
7529 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7533 void X86TargetLowering::
7534 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7535 SelectionDAG &DAG, unsigned NewOp) const {
7536 EVT T = Node->getValueType(0);
7537 DebugLoc dl = Node->getDebugLoc();
7538 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7540 SDValue Chain = Node->getOperand(0);
7541 SDValue In1 = Node->getOperand(1);
7542 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7543 Node->getOperand(2), DAG.getIntPtrConstant(0));
7544 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7545 Node->getOperand(2), DAG.getIntPtrConstant(1));
7546 SDValue Ops[] = { Chain, In1, In2L, In2H };
7547 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7549 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7550 cast<MemSDNode>(Node)->getMemOperand());
7551 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7552 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7553 Results.push_back(Result.getValue(2));
7556 /// ReplaceNodeResults - Replace a node with an illegal result type
7557 /// with a new node built out of custom code.
7558 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7559 SmallVectorImpl<SDValue>&Results,
7560 SelectionDAG &DAG) const {
7561 DebugLoc dl = N->getDebugLoc();
7562 switch (N->getOpcode()) {
7564 assert(false && "Do not know how to custom type legalize this operation!");
7566 case ISD::FP_TO_SINT: {
7567 std::pair<SDValue,SDValue> Vals =
7568 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7569 SDValue FIST = Vals.first, StackSlot = Vals.second;
7570 if (FIST.getNode() != 0) {
7571 EVT VT = N->getValueType(0);
7572 // Return a load from the stack slot.
7573 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7578 case ISD::READCYCLECOUNTER: {
7579 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7580 SDValue TheChain = N->getOperand(0);
7581 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7582 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7584 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7586 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7587 SDValue Ops[] = { eax, edx };
7588 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7589 Results.push_back(edx.getValue(1));
7592 case ISD::ATOMIC_CMP_SWAP: {
7593 EVT T = N->getValueType(0);
7594 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7595 SDValue cpInL, cpInH;
7596 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7597 DAG.getConstant(0, MVT::i32));
7598 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7599 DAG.getConstant(1, MVT::i32));
7600 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7601 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7603 SDValue swapInL, swapInH;
7604 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7605 DAG.getConstant(0, MVT::i32));
7606 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7607 DAG.getConstant(1, MVT::i32));
7608 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7610 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7611 swapInL.getValue(1));
7612 SDValue Ops[] = { swapInH.getValue(0),
7614 swapInH.getValue(1) };
7615 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7616 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7617 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7618 MVT::i32, Result.getValue(1));
7619 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7620 MVT::i32, cpOutL.getValue(2));
7621 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7622 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7623 Results.push_back(cpOutH.getValue(1));
7626 case ISD::ATOMIC_LOAD_ADD:
7627 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7629 case ISD::ATOMIC_LOAD_AND:
7630 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7632 case ISD::ATOMIC_LOAD_NAND:
7633 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7635 case ISD::ATOMIC_LOAD_OR:
7636 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7638 case ISD::ATOMIC_LOAD_SUB:
7639 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7641 case ISD::ATOMIC_LOAD_XOR:
7642 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7644 case ISD::ATOMIC_SWAP:
7645 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7650 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7652 default: return NULL;
7653 case X86ISD::BSF: return "X86ISD::BSF";
7654 case X86ISD::BSR: return "X86ISD::BSR";
7655 case X86ISD::SHLD: return "X86ISD::SHLD";
7656 case X86ISD::SHRD: return "X86ISD::SHRD";
7657 case X86ISD::FAND: return "X86ISD::FAND";
7658 case X86ISD::FOR: return "X86ISD::FOR";
7659 case X86ISD::FXOR: return "X86ISD::FXOR";
7660 case X86ISD::FSRL: return "X86ISD::FSRL";
7661 case X86ISD::FILD: return "X86ISD::FILD";
7662 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7663 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7664 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7665 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7666 case X86ISD::FLD: return "X86ISD::FLD";
7667 case X86ISD::FST: return "X86ISD::FST";
7668 case X86ISD::CALL: return "X86ISD::CALL";
7669 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7670 case X86ISD::BT: return "X86ISD::BT";
7671 case X86ISD::CMP: return "X86ISD::CMP";
7672 case X86ISD::COMI: return "X86ISD::COMI";
7673 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7674 case X86ISD::SETCC: return "X86ISD::SETCC";
7675 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7676 case X86ISD::CMOV: return "X86ISD::CMOV";
7677 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7678 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7679 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7680 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7681 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7682 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7683 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7684 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7685 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7686 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7687 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7688 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7689 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7690 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7691 case X86ISD::FMAX: return "X86ISD::FMAX";
7692 case X86ISD::FMIN: return "X86ISD::FMIN";
7693 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7694 case X86ISD::FRCP: return "X86ISD::FRCP";
7695 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7696 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7697 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7698 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7699 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7700 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7701 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7702 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7703 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7704 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7705 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7706 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7707 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7708 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7709 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7710 case X86ISD::VSHL: return "X86ISD::VSHL";
7711 case X86ISD::VSRL: return "X86ISD::VSRL";
7712 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7713 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7714 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7715 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7716 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7717 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7718 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7719 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7720 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7721 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7722 case X86ISD::ADD: return "X86ISD::ADD";
7723 case X86ISD::SUB: return "X86ISD::SUB";
7724 case X86ISD::SMUL: return "X86ISD::SMUL";
7725 case X86ISD::UMUL: return "X86ISD::UMUL";
7726 case X86ISD::INC: return "X86ISD::INC";
7727 case X86ISD::DEC: return "X86ISD::DEC";
7728 case X86ISD::OR: return "X86ISD::OR";
7729 case X86ISD::XOR: return "X86ISD::XOR";
7730 case X86ISD::AND: return "X86ISD::AND";
7731 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7732 case X86ISD::PTEST: return "X86ISD::PTEST";
7733 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7734 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7738 // isLegalAddressingMode - Return true if the addressing mode represented
7739 // by AM is legal for this target, for a load/store of the specified type.
7740 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7741 const Type *Ty) const {
7742 // X86 supports extremely general addressing modes.
7743 CodeModel::Model M = getTargetMachine().getCodeModel();
7745 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7746 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7751 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7753 // If a reference to this global requires an extra load, we can't fold it.
7754 if (isGlobalStubReference(GVFlags))
7757 // If BaseGV requires a register for the PIC base, we cannot also have a
7758 // BaseReg specified.
7759 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7762 // If lower 4G is not available, then we must use rip-relative addressing.
7763 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7773 // These scales always work.
7778 // These scales are formed with basereg+scalereg. Only accept if there is
7783 default: // Other stuff never works.
7791 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7792 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7794 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7795 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7796 if (NumBits1 <= NumBits2)
7801 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7802 if (!VT1.isInteger() || !VT2.isInteger())
7804 unsigned NumBits1 = VT1.getSizeInBits();
7805 unsigned NumBits2 = VT2.getSizeInBits();
7806 if (NumBits1 <= NumBits2)
7811 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7812 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7813 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7816 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7817 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7818 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7821 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7822 // i16 instructions are longer (0x66 prefix) and potentially slower.
7823 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7826 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7827 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7828 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7829 /// are assumed to be legal.
7831 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7833 // Very little shuffling can be done for 64-bit vectors right now.
7834 if (VT.getSizeInBits() == 64)
7835 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7837 // FIXME: pshufb, blends, shifts.
7838 return (VT.getVectorNumElements() == 2 ||
7839 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7840 isMOVLMask(M, VT) ||
7841 isSHUFPMask(M, VT) ||
7842 isPSHUFDMask(M, VT) ||
7843 isPSHUFHWMask(M, VT) ||
7844 isPSHUFLWMask(M, VT) ||
7845 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7846 isUNPCKLMask(M, VT) ||
7847 isUNPCKHMask(M, VT) ||
7848 isUNPCKL_v_undef_Mask(M, VT) ||
7849 isUNPCKH_v_undef_Mask(M, VT));
7853 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7855 unsigned NumElts = VT.getVectorNumElements();
7856 // FIXME: This collection of masks seems suspect.
7859 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7860 return (isMOVLMask(Mask, VT) ||
7861 isCommutedMOVLMask(Mask, VT, true) ||
7862 isSHUFPMask(Mask, VT) ||
7863 isCommutedSHUFPMask(Mask, VT));
7868 //===----------------------------------------------------------------------===//
7869 // X86 Scheduler Hooks
7870 //===----------------------------------------------------------------------===//
7872 // private utility function
7874 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7875 MachineBasicBlock *MBB,
7883 TargetRegisterClass *RC,
7884 bool invSrc) const {
7885 // For the atomic bitwise operator, we generate
7888 // ld t1 = [bitinstr.addr]
7889 // op t2 = t1, [bitinstr.val]
7891 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7893 // fallthrough -->nextMBB
7894 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7895 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7896 MachineFunction::iterator MBBIter = MBB;
7899 /// First build the CFG
7900 MachineFunction *F = MBB->getParent();
7901 MachineBasicBlock *thisMBB = MBB;
7902 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7903 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7904 F->insert(MBBIter, newMBB);
7905 F->insert(MBBIter, nextMBB);
7907 // Move all successors to thisMBB to nextMBB
7908 nextMBB->transferSuccessors(thisMBB);
7910 // Update thisMBB to fall through to newMBB
7911 thisMBB->addSuccessor(newMBB);
7913 // newMBB jumps to itself and fall through to nextMBB
7914 newMBB->addSuccessor(nextMBB);
7915 newMBB->addSuccessor(newMBB);
7917 // Insert instructions into newMBB based on incoming instruction
7918 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7919 "unexpected number of operands");
7920 DebugLoc dl = bInstr->getDebugLoc();
7921 MachineOperand& destOper = bInstr->getOperand(0);
7922 MachineOperand* argOpers[2 + X86AddrNumOperands];
7923 int numArgs = bInstr->getNumOperands() - 1;
7924 for (int i=0; i < numArgs; ++i)
7925 argOpers[i] = &bInstr->getOperand(i+1);
7927 // x86 address has 4 operands: base, index, scale, and displacement
7928 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7929 int valArgIndx = lastAddrIndx + 1;
7931 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7932 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7933 for (int i=0; i <= lastAddrIndx; ++i)
7934 (*MIB).addOperand(*argOpers[i]);
7936 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7938 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7943 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7944 assert((argOpers[valArgIndx]->isReg() ||
7945 argOpers[valArgIndx]->isImm()) &&
7947 if (argOpers[valArgIndx]->isReg())
7948 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7950 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7952 (*MIB).addOperand(*argOpers[valArgIndx]);
7954 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7957 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7958 for (int i=0; i <= lastAddrIndx; ++i)
7959 (*MIB).addOperand(*argOpers[i]);
7961 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7962 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7963 bInstr->memoperands_end());
7965 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7969 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
7971 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7975 // private utility function: 64 bit atomics on 32 bit host.
7977 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7978 MachineBasicBlock *MBB,
7983 bool invSrc) const {
7984 // For the atomic bitwise operator, we generate
7985 // thisMBB (instructions are in pairs, except cmpxchg8b)
7986 // ld t1,t2 = [bitinstr.addr]
7988 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7989 // op t5, t6 <- out1, out2, [bitinstr.val]
7990 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7991 // mov ECX, EBX <- t5, t6
7992 // mov EAX, EDX <- t1, t2
7993 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7994 // mov t3, t4 <- EAX, EDX
7996 // result in out1, out2
7997 // fallthrough -->nextMBB
7999 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8000 const unsigned LoadOpc = X86::MOV32rm;
8001 const unsigned copyOpc = X86::MOV32rr;
8002 const unsigned NotOpc = X86::NOT32r;
8003 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8004 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8005 MachineFunction::iterator MBBIter = MBB;
8008 /// First build the CFG
8009 MachineFunction *F = MBB->getParent();
8010 MachineBasicBlock *thisMBB = MBB;
8011 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8012 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8013 F->insert(MBBIter, newMBB);
8014 F->insert(MBBIter, nextMBB);
8016 // Move all successors to thisMBB to nextMBB
8017 nextMBB->transferSuccessors(thisMBB);
8019 // Update thisMBB to fall through to newMBB
8020 thisMBB->addSuccessor(newMBB);
8022 // newMBB jumps to itself and fall through to nextMBB
8023 newMBB->addSuccessor(nextMBB);
8024 newMBB->addSuccessor(newMBB);
8026 DebugLoc dl = bInstr->getDebugLoc();
8027 // Insert instructions into newMBB based on incoming instruction
8028 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8029 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8030 "unexpected number of operands");
8031 MachineOperand& dest1Oper = bInstr->getOperand(0);
8032 MachineOperand& dest2Oper = bInstr->getOperand(1);
8033 MachineOperand* argOpers[2 + X86AddrNumOperands];
8034 for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
8035 argOpers[i] = &bInstr->getOperand(i+2);
8037 // We use some of the operands multiple times, so conservatively just
8038 // clear any kill flags that might be present.
8039 if (argOpers[i]->isReg() && argOpers[i]->isUse())
8040 argOpers[i]->setIsKill(false);
8043 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8044 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8046 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8047 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8048 for (int i=0; i <= lastAddrIndx; ++i)
8049 (*MIB).addOperand(*argOpers[i]);
8050 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8051 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8052 // add 4 to displacement.
8053 for (int i=0; i <= lastAddrIndx-2; ++i)
8054 (*MIB).addOperand(*argOpers[i]);
8055 MachineOperand newOp3 = *(argOpers[3]);
8057 newOp3.setImm(newOp3.getImm()+4);
8059 newOp3.setOffset(newOp3.getOffset()+4);
8060 (*MIB).addOperand(newOp3);
8061 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8063 // t3/4 are defined later, at the bottom of the loop
8064 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8065 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8066 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8067 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8068 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8069 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8071 // The subsequent operations should be using the destination registers of
8072 //the PHI instructions.
8074 t1 = F->getRegInfo().createVirtualRegister(RC);
8075 t2 = F->getRegInfo().createVirtualRegister(RC);
8076 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8077 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8079 t1 = dest1Oper.getReg();
8080 t2 = dest2Oper.getReg();
8083 int valArgIndx = lastAddrIndx + 1;
8084 assert((argOpers[valArgIndx]->isReg() ||
8085 argOpers[valArgIndx]->isImm()) &&
8087 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8088 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8089 if (argOpers[valArgIndx]->isReg())
8090 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8092 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8093 if (regOpcL != X86::MOV32rr)
8095 (*MIB).addOperand(*argOpers[valArgIndx]);
8096 assert(argOpers[valArgIndx + 1]->isReg() ==
8097 argOpers[valArgIndx]->isReg());
8098 assert(argOpers[valArgIndx + 1]->isImm() ==
8099 argOpers[valArgIndx]->isImm());
8100 if (argOpers[valArgIndx + 1]->isReg())
8101 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8103 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8104 if (regOpcH != X86::MOV32rr)
8106 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8108 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8110 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8113 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8115 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8118 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8119 for (int i=0; i <= lastAddrIndx; ++i)
8120 (*MIB).addOperand(*argOpers[i]);
8122 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8123 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8124 bInstr->memoperands_end());
8126 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8127 MIB.addReg(X86::EAX);
8128 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8129 MIB.addReg(X86::EDX);
8132 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8134 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8138 // private utility function
8140 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8141 MachineBasicBlock *MBB,
8142 unsigned cmovOpc) const {
8143 // For the atomic min/max operator, we generate
8146 // ld t1 = [min/max.addr]
8147 // mov t2 = [min/max.val]
8149 // cmov[cond] t2 = t1
8151 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8153 // fallthrough -->nextMBB
8155 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8156 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8157 MachineFunction::iterator MBBIter = MBB;
8160 /// First build the CFG
8161 MachineFunction *F = MBB->getParent();
8162 MachineBasicBlock *thisMBB = MBB;
8163 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8164 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8165 F->insert(MBBIter, newMBB);
8166 F->insert(MBBIter, nextMBB);
8168 // Move all successors of thisMBB to nextMBB
8169 nextMBB->transferSuccessors(thisMBB);
8171 // Update thisMBB to fall through to newMBB
8172 thisMBB->addSuccessor(newMBB);
8174 // newMBB jumps to newMBB and fall through to nextMBB
8175 newMBB->addSuccessor(nextMBB);
8176 newMBB->addSuccessor(newMBB);
8178 DebugLoc dl = mInstr->getDebugLoc();
8179 // Insert instructions into newMBB based on incoming instruction
8180 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8181 "unexpected number of operands");
8182 MachineOperand& destOper = mInstr->getOperand(0);
8183 MachineOperand* argOpers[2 + X86AddrNumOperands];
8184 int numArgs = mInstr->getNumOperands() - 1;
8185 for (int i=0; i < numArgs; ++i)
8186 argOpers[i] = &mInstr->getOperand(i+1);
8188 // x86 address has 4 operands: base, index, scale, and displacement
8189 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8190 int valArgIndx = lastAddrIndx + 1;
8192 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8193 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8194 for (int i=0; i <= lastAddrIndx; ++i)
8195 (*MIB).addOperand(*argOpers[i]);
8197 // We only support register and immediate values
8198 assert((argOpers[valArgIndx]->isReg() ||
8199 argOpers[valArgIndx]->isImm()) &&
8202 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8203 if (argOpers[valArgIndx]->isReg())
8204 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8206 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8207 (*MIB).addOperand(*argOpers[valArgIndx]);
8209 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8212 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8217 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8218 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8222 // Cmp and exchange if none has modified the memory location
8223 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8224 for (int i=0; i <= lastAddrIndx; ++i)
8225 (*MIB).addOperand(*argOpers[i]);
8227 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8228 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8229 mInstr->memoperands_end());
8231 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8232 MIB.addReg(X86::EAX);
8235 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8237 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8241 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8242 // all of this code can be replaced with that in the .td file.
8244 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8245 unsigned numArgs, bool memArg) const {
8247 MachineFunction *F = BB->getParent();
8248 DebugLoc dl = MI->getDebugLoc();
8249 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8253 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8255 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8257 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8259 for (unsigned i = 0; i < numArgs; ++i) {
8260 MachineOperand &Op = MI->getOperand(i+1);
8262 if (!(Op.isReg() && Op.isImplicit()))
8266 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8269 F->DeleteMachineInstr(MI);
8275 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8277 MachineBasicBlock *MBB) const {
8278 // Emit code to save XMM registers to the stack. The ABI says that the
8279 // number of registers to save is given in %al, so it's theoretically
8280 // possible to do an indirect jump trick to avoid saving all of them,
8281 // however this code takes a simpler approach and just executes all
8282 // of the stores if %al is non-zero. It's less code, and it's probably
8283 // easier on the hardware branch predictor, and stores aren't all that
8284 // expensive anyway.
8286 // Create the new basic blocks. One block contains all the XMM stores,
8287 // and one block is the final destination regardless of whether any
8288 // stores were performed.
8289 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8290 MachineFunction *F = MBB->getParent();
8291 MachineFunction::iterator MBBIter = MBB;
8293 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8294 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8295 F->insert(MBBIter, XMMSaveMBB);
8296 F->insert(MBBIter, EndMBB);
8299 // Move any original successors of MBB to the end block.
8300 EndMBB->transferSuccessors(MBB);
8301 // The original block will now fall through to the XMM save block.
8302 MBB->addSuccessor(XMMSaveMBB);
8303 // The XMMSaveMBB will fall through to the end block.
8304 XMMSaveMBB->addSuccessor(EndMBB);
8306 // Now add the instructions.
8307 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8308 DebugLoc DL = MI->getDebugLoc();
8310 unsigned CountReg = MI->getOperand(0).getReg();
8311 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8312 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8314 if (!Subtarget->isTargetWin64()) {
8315 // If %al is 0, branch around the XMM save block.
8316 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8317 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8318 MBB->addSuccessor(EndMBB);
8321 // In the XMM save block, save all the XMM argument registers.
8322 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8323 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8324 MachineMemOperand *MMO =
8325 F->getMachineMemOperand(
8326 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8327 MachineMemOperand::MOStore, Offset,
8328 /*Size=*/16, /*Align=*/16);
8329 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8330 .addFrameIndex(RegSaveFrameIndex)
8331 .addImm(/*Scale=*/1)
8332 .addReg(/*IndexReg=*/0)
8333 .addImm(/*Disp=*/Offset)
8334 .addReg(/*Segment=*/0)
8335 .addReg(MI->getOperand(i).getReg())
8336 .addMemOperand(MMO);
8339 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8345 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8346 MachineBasicBlock *BB) const {
8347 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8348 DebugLoc DL = MI->getDebugLoc();
8350 // To "insert" a SELECT_CC instruction, we actually have to insert the
8351 // diamond control-flow pattern. The incoming instruction knows the
8352 // destination vreg to set, the condition code register to branch on, the
8353 // true/false values to select between, and a branch opcode to use.
8354 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8355 MachineFunction::iterator It = BB;
8361 // cmpTY ccX, r1, r2
8363 // fallthrough --> copy0MBB
8364 MachineBasicBlock *thisMBB = BB;
8365 MachineFunction *F = BB->getParent();
8366 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8367 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8369 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8370 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8371 F->insert(It, copy0MBB);
8372 F->insert(It, sinkMBB);
8373 // Update machine-CFG edges by first adding all successors of the current
8374 // block to the new block which will contain the Phi node for the select.
8375 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8376 E = BB->succ_end(); I != E; ++I)
8377 sinkMBB->addSuccessor(*I);
8378 // Next, remove all successors of the current block, and add the true
8379 // and fallthrough blocks as its successors.
8380 while (!BB->succ_empty())
8381 BB->removeSuccessor(BB->succ_begin());
8382 // Add the true and fallthrough blocks as its successors.
8383 BB->addSuccessor(copy0MBB);
8384 BB->addSuccessor(sinkMBB);
8387 // %FalseValue = ...
8388 // # fallthrough to sinkMBB
8389 copy0MBB->addSuccessor(sinkMBB);
8392 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8394 BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8395 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8396 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8398 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8403 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8404 MachineBasicBlock *BB) const {
8405 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8406 DebugLoc DL = MI->getDebugLoc();
8407 MachineFunction *F = BB->getParent();
8409 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8410 // non-trivial part is impdef of ESP.
8411 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8414 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8415 .addExternalSymbol("_alloca")
8416 .addReg(X86::EAX, RegState::Implicit)
8417 .addReg(X86::ESP, RegState::Implicit)
8418 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8419 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8421 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8426 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8427 MachineBasicBlock *BB) const {
8428 switch (MI->getOpcode()) {
8429 default: assert(false && "Unexpected instr type to insert");
8430 case X86::MINGW_ALLOCA:
8431 return EmitLoweredMingwAlloca(MI, BB);
8433 case X86::CMOV_V1I64:
8434 case X86::CMOV_FR32:
8435 case X86::CMOV_FR64:
8436 case X86::CMOV_V4F32:
8437 case X86::CMOV_V2F64:
8438 case X86::CMOV_V2I64:
8439 case X86::CMOV_GR16:
8440 case X86::CMOV_GR32:
8441 case X86::CMOV_RFP32:
8442 case X86::CMOV_RFP64:
8443 case X86::CMOV_RFP80:
8444 return EmitLoweredSelect(MI, BB);
8446 case X86::FP32_TO_INT16_IN_MEM:
8447 case X86::FP32_TO_INT32_IN_MEM:
8448 case X86::FP32_TO_INT64_IN_MEM:
8449 case X86::FP64_TO_INT16_IN_MEM:
8450 case X86::FP64_TO_INT32_IN_MEM:
8451 case X86::FP64_TO_INT64_IN_MEM:
8452 case X86::FP80_TO_INT16_IN_MEM:
8453 case X86::FP80_TO_INT32_IN_MEM:
8454 case X86::FP80_TO_INT64_IN_MEM: {
8455 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8456 DebugLoc DL = MI->getDebugLoc();
8458 // Change the floating point control register to use "round towards zero"
8459 // mode when truncating to an integer value.
8460 MachineFunction *F = BB->getParent();
8461 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8462 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8464 // Load the old value of the high byte of the control word...
8466 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8467 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8470 // Set the high part to be round to zero...
8471 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8474 // Reload the modified control word now...
8475 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8477 // Restore the memory image of control word to original value
8478 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8481 // Get the X86 opcode to use.
8483 switch (MI->getOpcode()) {
8484 default: llvm_unreachable("illegal opcode!");
8485 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8486 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8487 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8488 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8489 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8490 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8491 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8492 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8493 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8497 MachineOperand &Op = MI->getOperand(0);
8499 AM.BaseType = X86AddressMode::RegBase;
8500 AM.Base.Reg = Op.getReg();
8502 AM.BaseType = X86AddressMode::FrameIndexBase;
8503 AM.Base.FrameIndex = Op.getIndex();
8505 Op = MI->getOperand(1);
8507 AM.Scale = Op.getImm();
8508 Op = MI->getOperand(2);
8510 AM.IndexReg = Op.getImm();
8511 Op = MI->getOperand(3);
8512 if (Op.isGlobal()) {
8513 AM.GV = Op.getGlobal();
8515 AM.Disp = Op.getImm();
8517 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8518 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8520 // Reload the original control word now.
8521 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8523 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8526 // String/text processing lowering.
8527 case X86::PCMPISTRM128REG:
8528 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8529 case X86::PCMPISTRM128MEM:
8530 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8531 case X86::PCMPESTRM128REG:
8532 return EmitPCMP(MI, BB, 5, false /* in mem */);
8533 case X86::PCMPESTRM128MEM:
8534 return EmitPCMP(MI, BB, 5, true /* in mem */);
8537 case X86::ATOMAND32:
8538 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8539 X86::AND32ri, X86::MOV32rm,
8540 X86::LCMPXCHG32, X86::MOV32rr,
8541 X86::NOT32r, X86::EAX,
8542 X86::GR32RegisterClass);
8544 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8545 X86::OR32ri, X86::MOV32rm,
8546 X86::LCMPXCHG32, X86::MOV32rr,
8547 X86::NOT32r, X86::EAX,
8548 X86::GR32RegisterClass);
8549 case X86::ATOMXOR32:
8550 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8551 X86::XOR32ri, X86::MOV32rm,
8552 X86::LCMPXCHG32, X86::MOV32rr,
8553 X86::NOT32r, X86::EAX,
8554 X86::GR32RegisterClass);
8555 case X86::ATOMNAND32:
8556 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8557 X86::AND32ri, X86::MOV32rm,
8558 X86::LCMPXCHG32, X86::MOV32rr,
8559 X86::NOT32r, X86::EAX,
8560 X86::GR32RegisterClass, true);
8561 case X86::ATOMMIN32:
8562 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8563 case X86::ATOMMAX32:
8564 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8565 case X86::ATOMUMIN32:
8566 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8567 case X86::ATOMUMAX32:
8568 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8570 case X86::ATOMAND16:
8571 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8572 X86::AND16ri, X86::MOV16rm,
8573 X86::LCMPXCHG16, X86::MOV16rr,
8574 X86::NOT16r, X86::AX,
8575 X86::GR16RegisterClass);
8577 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8578 X86::OR16ri, X86::MOV16rm,
8579 X86::LCMPXCHG16, X86::MOV16rr,
8580 X86::NOT16r, X86::AX,
8581 X86::GR16RegisterClass);
8582 case X86::ATOMXOR16:
8583 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8584 X86::XOR16ri, X86::MOV16rm,
8585 X86::LCMPXCHG16, X86::MOV16rr,
8586 X86::NOT16r, X86::AX,
8587 X86::GR16RegisterClass);
8588 case X86::ATOMNAND16:
8589 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8590 X86::AND16ri, X86::MOV16rm,
8591 X86::LCMPXCHG16, X86::MOV16rr,
8592 X86::NOT16r, X86::AX,
8593 X86::GR16RegisterClass, true);
8594 case X86::ATOMMIN16:
8595 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8596 case X86::ATOMMAX16:
8597 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8598 case X86::ATOMUMIN16:
8599 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8600 case X86::ATOMUMAX16:
8601 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8604 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8605 X86::AND8ri, X86::MOV8rm,
8606 X86::LCMPXCHG8, X86::MOV8rr,
8607 X86::NOT8r, X86::AL,
8608 X86::GR8RegisterClass);
8610 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8611 X86::OR8ri, X86::MOV8rm,
8612 X86::LCMPXCHG8, X86::MOV8rr,
8613 X86::NOT8r, X86::AL,
8614 X86::GR8RegisterClass);
8616 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8617 X86::XOR8ri, X86::MOV8rm,
8618 X86::LCMPXCHG8, X86::MOV8rr,
8619 X86::NOT8r, X86::AL,
8620 X86::GR8RegisterClass);
8621 case X86::ATOMNAND8:
8622 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8623 X86::AND8ri, X86::MOV8rm,
8624 X86::LCMPXCHG8, X86::MOV8rr,
8625 X86::NOT8r, X86::AL,
8626 X86::GR8RegisterClass, true);
8627 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8628 // This group is for 64-bit host.
8629 case X86::ATOMAND64:
8630 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8631 X86::AND64ri32, X86::MOV64rm,
8632 X86::LCMPXCHG64, X86::MOV64rr,
8633 X86::NOT64r, X86::RAX,
8634 X86::GR64RegisterClass);
8636 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8637 X86::OR64ri32, X86::MOV64rm,
8638 X86::LCMPXCHG64, X86::MOV64rr,
8639 X86::NOT64r, X86::RAX,
8640 X86::GR64RegisterClass);
8641 case X86::ATOMXOR64:
8642 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8643 X86::XOR64ri32, X86::MOV64rm,
8644 X86::LCMPXCHG64, X86::MOV64rr,
8645 X86::NOT64r, X86::RAX,
8646 X86::GR64RegisterClass);
8647 case X86::ATOMNAND64:
8648 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8649 X86::AND64ri32, X86::MOV64rm,
8650 X86::LCMPXCHG64, X86::MOV64rr,
8651 X86::NOT64r, X86::RAX,
8652 X86::GR64RegisterClass, true);
8653 case X86::ATOMMIN64:
8654 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8655 case X86::ATOMMAX64:
8656 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8657 case X86::ATOMUMIN64:
8658 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8659 case X86::ATOMUMAX64:
8660 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8662 // This group does 64-bit operations on a 32-bit host.
8663 case X86::ATOMAND6432:
8664 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8665 X86::AND32rr, X86::AND32rr,
8666 X86::AND32ri, X86::AND32ri,
8668 case X86::ATOMOR6432:
8669 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8670 X86::OR32rr, X86::OR32rr,
8671 X86::OR32ri, X86::OR32ri,
8673 case X86::ATOMXOR6432:
8674 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8675 X86::XOR32rr, X86::XOR32rr,
8676 X86::XOR32ri, X86::XOR32ri,
8678 case X86::ATOMNAND6432:
8679 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8680 X86::AND32rr, X86::AND32rr,
8681 X86::AND32ri, X86::AND32ri,
8683 case X86::ATOMADD6432:
8684 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8685 X86::ADD32rr, X86::ADC32rr,
8686 X86::ADD32ri, X86::ADC32ri,
8688 case X86::ATOMSUB6432:
8689 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8690 X86::SUB32rr, X86::SBB32rr,
8691 X86::SUB32ri, X86::SBB32ri,
8693 case X86::ATOMSWAP6432:
8694 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8695 X86::MOV32rr, X86::MOV32rr,
8696 X86::MOV32ri, X86::MOV32ri,
8698 case X86::VASTART_SAVE_XMM_REGS:
8699 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8703 //===----------------------------------------------------------------------===//
8704 // X86 Optimization Hooks
8705 //===----------------------------------------------------------------------===//
8707 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8711 const SelectionDAG &DAG,
8712 unsigned Depth) const {
8713 unsigned Opc = Op.getOpcode();
8714 assert((Opc >= ISD::BUILTIN_OP_END ||
8715 Opc == ISD::INTRINSIC_WO_CHAIN ||
8716 Opc == ISD::INTRINSIC_W_CHAIN ||
8717 Opc == ISD::INTRINSIC_VOID) &&
8718 "Should use MaskedValueIsZero if you don't know whether Op"
8719 " is a target node!");
8721 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8733 // These nodes' second result is a boolean.
8734 if (Op.getResNo() == 0)
8738 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8739 Mask.getBitWidth() - 1);
8744 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8745 /// node is a GlobalAddress + offset.
8746 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8747 const GlobalValue* &GA,
8748 int64_t &Offset) const {
8749 if (N->getOpcode() == X86ISD::Wrapper) {
8750 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8751 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8752 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8756 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8759 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8760 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8761 /// if the load addresses are consecutive, non-overlapping, and in the right
8763 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8764 const TargetLowering &TLI) {
8765 DebugLoc dl = N->getDebugLoc();
8766 EVT VT = N->getValueType(0);
8767 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8769 if (VT.getSizeInBits() != 128)
8772 SmallVector<SDValue, 16> Elts;
8773 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8774 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8776 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8779 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8780 /// and convert it from being a bunch of shuffles and extracts to a simple
8781 /// store and scalar loads to extract the elements.
8782 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8783 const TargetLowering &TLI) {
8784 SDValue InputVector = N->getOperand(0);
8786 // Only operate on vectors of 4 elements, where the alternative shuffling
8787 // gets to be more expensive.
8788 if (InputVector.getValueType() != MVT::v4i32)
8791 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8792 // single use which is a sign-extend or zero-extend, and all elements are
8794 SmallVector<SDNode *, 4> Uses;
8795 unsigned ExtractedElements = 0;
8796 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8797 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8798 if (UI.getUse().getResNo() != InputVector.getResNo())
8801 SDNode *Extract = *UI;
8802 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8805 if (Extract->getValueType(0) != MVT::i32)
8807 if (!Extract->hasOneUse())
8809 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8810 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8812 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8815 // Record which element was extracted.
8816 ExtractedElements |=
8817 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8819 Uses.push_back(Extract);
8822 // If not all the elements were used, this may not be worthwhile.
8823 if (ExtractedElements != 15)
8826 // Ok, we've now decided to do the transformation.
8827 DebugLoc dl = InputVector.getDebugLoc();
8829 // Store the value to a temporary stack slot.
8830 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8831 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8834 // Replace each use (extract) with a load of the appropriate element.
8835 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8836 UE = Uses.end(); UI != UE; ++UI) {
8837 SDNode *Extract = *UI;
8839 // Compute the element's address.
8840 SDValue Idx = Extract->getOperand(1);
8842 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8843 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8844 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8846 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8849 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8850 NULL, 0, false, false, 0);
8852 // Replace the exact with the load.
8853 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8856 // The replacement was made in place; don't return anything.
8860 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8861 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8862 const X86Subtarget *Subtarget) {
8863 DebugLoc DL = N->getDebugLoc();
8864 SDValue Cond = N->getOperand(0);
8865 // Get the LHS/RHS of the select.
8866 SDValue LHS = N->getOperand(1);
8867 SDValue RHS = N->getOperand(2);
8869 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8870 // instructions match the semantics of the common C idiom x<y?x:y but not
8871 // x<=y?x:y, because of how they handle negative zero (which can be
8872 // ignored in unsafe-math mode).
8873 if (Subtarget->hasSSE2() &&
8874 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8875 Cond.getOpcode() == ISD::SETCC) {
8876 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8878 unsigned Opcode = 0;
8879 // Check for x CC y ? x : y.
8880 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8881 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8885 // Converting this to a min would handle NaNs incorrectly, and swapping
8886 // the operands would cause it to handle comparisons between positive
8887 // and negative zero incorrectly.
8888 if (!FiniteOnlyFPMath() &&
8889 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8890 if (!UnsafeFPMath &&
8891 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8893 std::swap(LHS, RHS);
8895 Opcode = X86ISD::FMIN;
8898 // Converting this to a min would handle comparisons between positive
8899 // and negative zero incorrectly.
8900 if (!UnsafeFPMath &&
8901 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8903 Opcode = X86ISD::FMIN;
8906 // Converting this to a min would handle both negative zeros and NaNs
8907 // incorrectly, but we can swap the operands to fix both.
8908 std::swap(LHS, RHS);
8912 Opcode = X86ISD::FMIN;
8916 // Converting this to a max would handle comparisons between positive
8917 // and negative zero incorrectly.
8918 if (!UnsafeFPMath &&
8919 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8921 Opcode = X86ISD::FMAX;
8924 // Converting this to a max would handle NaNs incorrectly, and swapping
8925 // the operands would cause it to handle comparisons between positive
8926 // and negative zero incorrectly.
8927 if (!FiniteOnlyFPMath() &&
8928 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8929 if (!UnsafeFPMath &&
8930 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8932 std::swap(LHS, RHS);
8934 Opcode = X86ISD::FMAX;
8937 // Converting this to a max would handle both negative zeros and NaNs
8938 // incorrectly, but we can swap the operands to fix both.
8939 std::swap(LHS, RHS);
8943 Opcode = X86ISD::FMAX;
8946 // Check for x CC y ? y : x -- a min/max with reversed arms.
8947 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8948 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8952 // Converting this to a min would handle comparisons between positive
8953 // and negative zero incorrectly, and swapping the operands would
8954 // cause it to handle NaNs incorrectly.
8955 if (!UnsafeFPMath &&
8956 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8957 if (!FiniteOnlyFPMath() &&
8958 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8960 std::swap(LHS, RHS);
8962 Opcode = X86ISD::FMIN;
8965 // Converting this to a min would handle NaNs incorrectly.
8966 if (!UnsafeFPMath &&
8967 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8969 Opcode = X86ISD::FMIN;
8972 // Converting this to a min would handle both negative zeros and NaNs
8973 // incorrectly, but we can swap the operands to fix both.
8974 std::swap(LHS, RHS);
8978 Opcode = X86ISD::FMIN;
8982 // Converting this to a max would handle NaNs incorrectly.
8983 if (!FiniteOnlyFPMath() &&
8984 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8986 Opcode = X86ISD::FMAX;
8989 // Converting this to a max would handle comparisons between positive
8990 // and negative zero incorrectly, and swapping the operands would
8991 // cause it to handle NaNs incorrectly.
8992 if (!UnsafeFPMath &&
8993 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
8994 if (!FiniteOnlyFPMath() &&
8995 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8997 std::swap(LHS, RHS);
8999 Opcode = X86ISD::FMAX;
9002 // Converting this to a max would handle both negative zeros and NaNs
9003 // incorrectly, but we can swap the operands to fix both.
9004 std::swap(LHS, RHS);
9008 Opcode = X86ISD::FMAX;
9014 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9017 // If this is a select between two integer constants, try to do some
9019 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9020 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9021 // Don't do this for crazy integer types.
9022 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9023 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9024 // so that TrueC (the true value) is larger than FalseC.
9025 bool NeedsCondInvert = false;
9027 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9028 // Efficiently invertible.
9029 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9030 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9031 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9032 NeedsCondInvert = true;
9033 std::swap(TrueC, FalseC);
9036 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9037 if (FalseC->getAPIntValue() == 0 &&
9038 TrueC->getAPIntValue().isPowerOf2()) {
9039 if (NeedsCondInvert) // Invert the condition if needed.
9040 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9041 DAG.getConstant(1, Cond.getValueType()));
9043 // Zero extend the condition if needed.
9044 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9046 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9047 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9048 DAG.getConstant(ShAmt, MVT::i8));
9051 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9052 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9053 if (NeedsCondInvert) // Invert the condition if needed.
9054 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9055 DAG.getConstant(1, Cond.getValueType()));
9057 // Zero extend the condition if needed.
9058 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9059 FalseC->getValueType(0), Cond);
9060 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9061 SDValue(FalseC, 0));
9064 // Optimize cases that will turn into an LEA instruction. This requires
9065 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9066 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9067 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9068 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9070 bool isFastMultiplier = false;
9072 switch ((unsigned char)Diff) {
9074 case 1: // result = add base, cond
9075 case 2: // result = lea base( , cond*2)
9076 case 3: // result = lea base(cond, cond*2)
9077 case 4: // result = lea base( , cond*4)
9078 case 5: // result = lea base(cond, cond*4)
9079 case 8: // result = lea base( , cond*8)
9080 case 9: // result = lea base(cond, cond*8)
9081 isFastMultiplier = true;
9086 if (isFastMultiplier) {
9087 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9088 if (NeedsCondInvert) // Invert the condition if needed.
9089 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9090 DAG.getConstant(1, Cond.getValueType()));
9092 // Zero extend the condition if needed.
9093 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9095 // Scale the condition by the difference.
9097 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9098 DAG.getConstant(Diff, Cond.getValueType()));
9100 // Add the base if non-zero.
9101 if (FalseC->getAPIntValue() != 0)
9102 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9103 SDValue(FalseC, 0));
9113 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9114 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9115 TargetLowering::DAGCombinerInfo &DCI) {
9116 DebugLoc DL = N->getDebugLoc();
9118 // If the flag operand isn't dead, don't touch this CMOV.
9119 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9122 // If this is a select between two integer constants, try to do some
9123 // optimizations. Note that the operands are ordered the opposite of SELECT
9125 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9126 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9127 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9128 // larger than FalseC (the false value).
9129 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9131 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9132 CC = X86::GetOppositeBranchCondition(CC);
9133 std::swap(TrueC, FalseC);
9136 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9137 // This is efficient for any integer data type (including i8/i16) and
9139 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9140 SDValue Cond = N->getOperand(3);
9141 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9142 DAG.getConstant(CC, MVT::i8), Cond);
9144 // Zero extend the condition if needed.
9145 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9147 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9148 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9149 DAG.getConstant(ShAmt, MVT::i8));
9150 if (N->getNumValues() == 2) // Dead flag value?
9151 return DCI.CombineTo(N, Cond, SDValue());
9155 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9156 // for any integer data type, including i8/i16.
9157 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9158 SDValue Cond = N->getOperand(3);
9159 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9160 DAG.getConstant(CC, MVT::i8), Cond);
9162 // Zero extend the condition if needed.
9163 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9164 FalseC->getValueType(0), Cond);
9165 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9166 SDValue(FalseC, 0));
9168 if (N->getNumValues() == 2) // Dead flag value?
9169 return DCI.CombineTo(N, Cond, SDValue());
9173 // Optimize cases that will turn into an LEA instruction. This requires
9174 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9175 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9176 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9177 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9179 bool isFastMultiplier = false;
9181 switch ((unsigned char)Diff) {
9183 case 1: // result = add base, cond
9184 case 2: // result = lea base( , cond*2)
9185 case 3: // result = lea base(cond, cond*2)
9186 case 4: // result = lea base( , cond*4)
9187 case 5: // result = lea base(cond, cond*4)
9188 case 8: // result = lea base( , cond*8)
9189 case 9: // result = lea base(cond, cond*8)
9190 isFastMultiplier = true;
9195 if (isFastMultiplier) {
9196 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9197 SDValue Cond = N->getOperand(3);
9198 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9199 DAG.getConstant(CC, MVT::i8), Cond);
9200 // Zero extend the condition if needed.
9201 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9203 // Scale the condition by the difference.
9205 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9206 DAG.getConstant(Diff, Cond.getValueType()));
9208 // Add the base if non-zero.
9209 if (FalseC->getAPIntValue() != 0)
9210 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9211 SDValue(FalseC, 0));
9212 if (N->getNumValues() == 2) // Dead flag value?
9213 return DCI.CombineTo(N, Cond, SDValue());
9223 /// PerformMulCombine - Optimize a single multiply with constant into two
9224 /// in order to implement it with two cheaper instructions, e.g.
9225 /// LEA + SHL, LEA + LEA.
9226 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9227 TargetLowering::DAGCombinerInfo &DCI) {
9228 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9231 EVT VT = N->getValueType(0);
9235 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9238 uint64_t MulAmt = C->getZExtValue();
9239 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9242 uint64_t MulAmt1 = 0;
9243 uint64_t MulAmt2 = 0;
9244 if ((MulAmt % 9) == 0) {
9246 MulAmt2 = MulAmt / 9;
9247 } else if ((MulAmt % 5) == 0) {
9249 MulAmt2 = MulAmt / 5;
9250 } else if ((MulAmt % 3) == 0) {
9252 MulAmt2 = MulAmt / 3;
9255 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9256 DebugLoc DL = N->getDebugLoc();
9258 if (isPowerOf2_64(MulAmt2) &&
9259 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9260 // If second multiplifer is pow2, issue it first. We want the multiply by
9261 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9263 std::swap(MulAmt1, MulAmt2);
9266 if (isPowerOf2_64(MulAmt1))
9267 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9268 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9270 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9271 DAG.getConstant(MulAmt1, VT));
9273 if (isPowerOf2_64(MulAmt2))
9274 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9275 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9277 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9278 DAG.getConstant(MulAmt2, VT));
9280 // Do not add new nodes to DAG combiner worklist.
9281 DCI.CombineTo(N, NewMul, false);
9286 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9287 SDValue N0 = N->getOperand(0);
9288 SDValue N1 = N->getOperand(1);
9289 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9290 EVT VT = N0.getValueType();
9292 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9293 // since the result of setcc_c is all zero's or all ones.
9294 if (N1C && N0.getOpcode() == ISD::AND &&
9295 N0.getOperand(1).getOpcode() == ISD::Constant) {
9296 SDValue N00 = N0.getOperand(0);
9297 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9298 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9299 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9300 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9301 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9302 APInt ShAmt = N1C->getAPIntValue();
9303 Mask = Mask.shl(ShAmt);
9305 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9306 N00, DAG.getConstant(Mask, VT));
9313 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9315 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9316 const X86Subtarget *Subtarget) {
9317 EVT VT = N->getValueType(0);
9318 if (!VT.isVector() && VT.isInteger() &&
9319 N->getOpcode() == ISD::SHL)
9320 return PerformSHLCombine(N, DAG);
9322 // On X86 with SSE2 support, we can transform this to a vector shift if
9323 // all elements are shifted by the same amount. We can't do this in legalize
9324 // because the a constant vector is typically transformed to a constant pool
9325 // so we have no knowledge of the shift amount.
9326 if (!Subtarget->hasSSE2())
9329 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9332 SDValue ShAmtOp = N->getOperand(1);
9333 EVT EltVT = VT.getVectorElementType();
9334 DebugLoc DL = N->getDebugLoc();
9335 SDValue BaseShAmt = SDValue();
9336 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9337 unsigned NumElts = VT.getVectorNumElements();
9339 for (; i != NumElts; ++i) {
9340 SDValue Arg = ShAmtOp.getOperand(i);
9341 if (Arg.getOpcode() == ISD::UNDEF) continue;
9345 for (; i != NumElts; ++i) {
9346 SDValue Arg = ShAmtOp.getOperand(i);
9347 if (Arg.getOpcode() == ISD::UNDEF) continue;
9348 if (Arg != BaseShAmt) {
9352 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9353 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9354 SDValue InVec = ShAmtOp.getOperand(0);
9355 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9356 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9358 for (; i != NumElts; ++i) {
9359 SDValue Arg = InVec.getOperand(i);
9360 if (Arg.getOpcode() == ISD::UNDEF) continue;
9364 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9366 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9367 if (C->getZExtValue() == SplatIdx)
9368 BaseShAmt = InVec.getOperand(1);
9371 if (BaseShAmt.getNode() == 0)
9372 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9373 DAG.getIntPtrConstant(0));
9377 // The shift amount is an i32.
9378 if (EltVT.bitsGT(MVT::i32))
9379 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9380 else if (EltVT.bitsLT(MVT::i32))
9381 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9383 // The shift amount is identical so we can do a vector shift.
9384 SDValue ValOp = N->getOperand(0);
9385 switch (N->getOpcode()) {
9387 llvm_unreachable("Unknown shift opcode!");
9390 if (VT == MVT::v2i64)
9391 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9392 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9394 if (VT == MVT::v4i32)
9395 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9396 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9398 if (VT == MVT::v8i16)
9399 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9400 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9404 if (VT == MVT::v4i32)
9405 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9406 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9408 if (VT == MVT::v8i16)
9409 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9410 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9414 if (VT == MVT::v2i64)
9415 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9416 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9418 if (VT == MVT::v4i32)
9419 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9420 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9422 if (VT == MVT::v8i16)
9423 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9424 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9431 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9432 TargetLowering::DAGCombinerInfo &DCI,
9433 const X86Subtarget *Subtarget) {
9434 if (DCI.isBeforeLegalizeOps())
9437 EVT VT = N->getValueType(0);
9438 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9441 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9442 SDValue N0 = N->getOperand(0);
9443 SDValue N1 = N->getOperand(1);
9444 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9446 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9448 if (!N0.hasOneUse() || !N1.hasOneUse())
9451 SDValue ShAmt0 = N0.getOperand(1);
9452 if (ShAmt0.getValueType() != MVT::i8)
9454 SDValue ShAmt1 = N1.getOperand(1);
9455 if (ShAmt1.getValueType() != MVT::i8)
9457 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9458 ShAmt0 = ShAmt0.getOperand(0);
9459 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9460 ShAmt1 = ShAmt1.getOperand(0);
9462 DebugLoc DL = N->getDebugLoc();
9463 unsigned Opc = X86ISD::SHLD;
9464 SDValue Op0 = N0.getOperand(0);
9465 SDValue Op1 = N1.getOperand(0);
9466 if (ShAmt0.getOpcode() == ISD::SUB) {
9468 std::swap(Op0, Op1);
9469 std::swap(ShAmt0, ShAmt1);
9472 unsigned Bits = VT.getSizeInBits();
9473 if (ShAmt1.getOpcode() == ISD::SUB) {
9474 SDValue Sum = ShAmt1.getOperand(0);
9475 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9476 if (SumC->getSExtValue() == Bits &&
9477 ShAmt1.getOperand(1) == ShAmt0)
9478 return DAG.getNode(Opc, DL, VT,
9480 DAG.getNode(ISD::TRUNCATE, DL,
9483 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9484 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9486 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9487 return DAG.getNode(Opc, DL, VT,
9488 N0.getOperand(0), N1.getOperand(0),
9489 DAG.getNode(ISD::TRUNCATE, DL,
9496 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9497 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9498 const X86Subtarget *Subtarget) {
9499 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9500 // the FP state in cases where an emms may be missing.
9501 // A preferable solution to the general problem is to figure out the right
9502 // places to insert EMMS. This qualifies as a quick hack.
9504 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9505 StoreSDNode *St = cast<StoreSDNode>(N);
9506 EVT VT = St->getValue().getValueType();
9507 if (VT.getSizeInBits() != 64)
9510 const Function *F = DAG.getMachineFunction().getFunction();
9511 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9512 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9513 && Subtarget->hasSSE2();
9514 if ((VT.isVector() ||
9515 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9516 isa<LoadSDNode>(St->getValue()) &&
9517 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9518 St->getChain().hasOneUse() && !St->isVolatile()) {
9519 SDNode* LdVal = St->getValue().getNode();
9521 int TokenFactorIndex = -1;
9522 SmallVector<SDValue, 8> Ops;
9523 SDNode* ChainVal = St->getChain().getNode();
9524 // Must be a store of a load. We currently handle two cases: the load
9525 // is a direct child, and it's under an intervening TokenFactor. It is
9526 // possible to dig deeper under nested TokenFactors.
9527 if (ChainVal == LdVal)
9528 Ld = cast<LoadSDNode>(St->getChain());
9529 else if (St->getValue().hasOneUse() &&
9530 ChainVal->getOpcode() == ISD::TokenFactor) {
9531 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9532 if (ChainVal->getOperand(i).getNode() == LdVal) {
9533 TokenFactorIndex = i;
9534 Ld = cast<LoadSDNode>(St->getValue());
9536 Ops.push_back(ChainVal->getOperand(i));
9540 if (!Ld || !ISD::isNormalLoad(Ld))
9543 // If this is not the MMX case, i.e. we are just turning i64 load/store
9544 // into f64 load/store, avoid the transformation if there are multiple
9545 // uses of the loaded value.
9546 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9549 DebugLoc LdDL = Ld->getDebugLoc();
9550 DebugLoc StDL = N->getDebugLoc();
9551 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9552 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9554 if (Subtarget->is64Bit() || F64IsLegal) {
9555 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9556 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9557 Ld->getBasePtr(), Ld->getSrcValue(),
9558 Ld->getSrcValueOffset(), Ld->isVolatile(),
9559 Ld->isNonTemporal(), Ld->getAlignment());
9560 SDValue NewChain = NewLd.getValue(1);
9561 if (TokenFactorIndex != -1) {
9562 Ops.push_back(NewChain);
9563 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9566 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9567 St->getSrcValue(), St->getSrcValueOffset(),
9568 St->isVolatile(), St->isNonTemporal(),
9569 St->getAlignment());
9572 // Otherwise, lower to two pairs of 32-bit loads / stores.
9573 SDValue LoAddr = Ld->getBasePtr();
9574 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9575 DAG.getConstant(4, MVT::i32));
9577 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9578 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9579 Ld->isVolatile(), Ld->isNonTemporal(),
9580 Ld->getAlignment());
9581 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9582 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9583 Ld->isVolatile(), Ld->isNonTemporal(),
9584 MinAlign(Ld->getAlignment(), 4));
9586 SDValue NewChain = LoLd.getValue(1);
9587 if (TokenFactorIndex != -1) {
9588 Ops.push_back(LoLd);
9589 Ops.push_back(HiLd);
9590 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9594 LoAddr = St->getBasePtr();
9595 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9596 DAG.getConstant(4, MVT::i32));
9598 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9599 St->getSrcValue(), St->getSrcValueOffset(),
9600 St->isVolatile(), St->isNonTemporal(),
9601 St->getAlignment());
9602 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9604 St->getSrcValueOffset() + 4,
9606 St->isNonTemporal(),
9607 MinAlign(St->getAlignment(), 4));
9608 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9613 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9614 /// X86ISD::FXOR nodes.
9615 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9616 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9617 // F[X]OR(0.0, x) -> x
9618 // F[X]OR(x, 0.0) -> x
9619 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9620 if (C->getValueAPF().isPosZero())
9621 return N->getOperand(1);
9622 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9623 if (C->getValueAPF().isPosZero())
9624 return N->getOperand(0);
9628 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9629 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9630 // FAND(0.0, x) -> 0.0
9631 // FAND(x, 0.0) -> 0.0
9632 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9633 if (C->getValueAPF().isPosZero())
9634 return N->getOperand(0);
9635 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9636 if (C->getValueAPF().isPosZero())
9637 return N->getOperand(1);
9641 static SDValue PerformBTCombine(SDNode *N,
9643 TargetLowering::DAGCombinerInfo &DCI) {
9644 // BT ignores high bits in the bit index operand.
9645 SDValue Op1 = N->getOperand(1);
9646 if (Op1.hasOneUse()) {
9647 unsigned BitWidth = Op1.getValueSizeInBits();
9648 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9649 APInt KnownZero, KnownOne;
9650 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9651 !DCI.isBeforeLegalizeOps());
9652 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9653 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9654 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9655 DCI.CommitTargetLoweringOpt(TLO);
9660 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9661 SDValue Op = N->getOperand(0);
9662 if (Op.getOpcode() == ISD::BIT_CONVERT)
9663 Op = Op.getOperand(0);
9664 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9665 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9666 VT.getVectorElementType().getSizeInBits() ==
9667 OpVT.getVectorElementType().getSizeInBits()) {
9668 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9673 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9674 // Locked instructions, in turn, have implicit fence semantics (all memory
9675 // operations are flushed before issuing the locked instruction, and the
9676 // are not buffered), so we can fold away the common pattern of
9677 // fence-atomic-fence.
9678 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9679 SDValue atomic = N->getOperand(0);
9680 switch (atomic.getOpcode()) {
9681 case ISD::ATOMIC_CMP_SWAP:
9682 case ISD::ATOMIC_SWAP:
9683 case ISD::ATOMIC_LOAD_ADD:
9684 case ISD::ATOMIC_LOAD_SUB:
9685 case ISD::ATOMIC_LOAD_AND:
9686 case ISD::ATOMIC_LOAD_OR:
9687 case ISD::ATOMIC_LOAD_XOR:
9688 case ISD::ATOMIC_LOAD_NAND:
9689 case ISD::ATOMIC_LOAD_MIN:
9690 case ISD::ATOMIC_LOAD_MAX:
9691 case ISD::ATOMIC_LOAD_UMIN:
9692 case ISD::ATOMIC_LOAD_UMAX:
9698 SDValue fence = atomic.getOperand(0);
9699 if (fence.getOpcode() != ISD::MEMBARRIER)
9702 switch (atomic.getOpcode()) {
9703 case ISD::ATOMIC_CMP_SWAP:
9704 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9705 atomic.getOperand(1), atomic.getOperand(2),
9706 atomic.getOperand(3));
9707 case ISD::ATOMIC_SWAP:
9708 case ISD::ATOMIC_LOAD_ADD:
9709 case ISD::ATOMIC_LOAD_SUB:
9710 case ISD::ATOMIC_LOAD_AND:
9711 case ISD::ATOMIC_LOAD_OR:
9712 case ISD::ATOMIC_LOAD_XOR:
9713 case ISD::ATOMIC_LOAD_NAND:
9714 case ISD::ATOMIC_LOAD_MIN:
9715 case ISD::ATOMIC_LOAD_MAX:
9716 case ISD::ATOMIC_LOAD_UMIN:
9717 case ISD::ATOMIC_LOAD_UMAX:
9718 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9719 atomic.getOperand(1), atomic.getOperand(2));
9725 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9726 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9727 // (and (i32 x86isd::setcc_carry), 1)
9728 // This eliminates the zext. This transformation is necessary because
9729 // ISD::SETCC is always legalized to i8.
9730 DebugLoc dl = N->getDebugLoc();
9731 SDValue N0 = N->getOperand(0);
9732 EVT VT = N->getValueType(0);
9733 if (N0.getOpcode() == ISD::AND &&
9735 N0.getOperand(0).hasOneUse()) {
9736 SDValue N00 = N0.getOperand(0);
9737 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9739 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9740 if (!C || C->getZExtValue() != 1)
9742 return DAG.getNode(ISD::AND, dl, VT,
9743 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9744 N00.getOperand(0), N00.getOperand(1)),
9745 DAG.getConstant(1, VT));
9751 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9752 DAGCombinerInfo &DCI) const {
9753 SelectionDAG &DAG = DCI.DAG;
9754 switch (N->getOpcode()) {
9756 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9757 case ISD::EXTRACT_VECTOR_ELT:
9758 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9759 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9760 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9761 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9764 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9765 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
9766 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9768 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9769 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9770 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9771 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9772 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9773 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9779 /// isTypeDesirableForOp - Return true if the target has native support for
9780 /// the specified value type and it is 'desirable' to use the type for the
9781 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9782 /// instruction encodings are longer and some i16 instructions are slow.
9783 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9784 if (!isTypeLegal(VT))
9793 case ISD::SIGN_EXTEND:
9794 case ISD::ZERO_EXTEND:
9795 case ISD::ANY_EXTEND:
9808 static bool MayFoldLoad(SDValue Op) {
9809 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9812 static bool MayFoldIntoStore(SDValue Op) {
9813 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9816 /// IsDesirableToPromoteOp - This method query the target whether it is
9817 /// beneficial for dag combiner to promote the specified node. If true, it
9818 /// should return the desired promotion type by reference.
9819 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9820 EVT VT = Op.getValueType();
9824 bool Promote = false;
9825 bool Commute = false;
9826 switch (Op.getOpcode()) {
9829 LoadSDNode *LD = cast<LoadSDNode>(Op);
9830 // If the non-extending load has a single use and it's not live out, then it
9832 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9834 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9835 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9836 // The only case where we'd want to promote LOAD (rather then it being
9837 // promoted as an operand is when it's only use is liveout.
9838 if (UI->getOpcode() != ISD::CopyToReg)
9845 case ISD::SIGN_EXTEND:
9846 case ISD::ZERO_EXTEND:
9847 case ISD::ANY_EXTEND:
9852 SDValue N0 = Op.getOperand(0);
9853 // Look out for (store (shl (load), x)).
9854 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9867 SDValue N0 = Op.getOperand(0);
9868 SDValue N1 = Op.getOperand(1);
9869 if (!Commute && MayFoldLoad(N1))
9871 // Avoid disabling potential load folding opportunities.
9872 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9874 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
9884 //===----------------------------------------------------------------------===//
9885 // X86 Inline Assembly Support
9886 //===----------------------------------------------------------------------===//
9888 static bool LowerToBSwap(CallInst *CI) {
9889 // FIXME: this should verify that we are targetting a 486 or better. If not,
9890 // we will turn this bswap into something that will be lowered to logical ops
9891 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9892 // so don't worry about this.
9894 // Verify this is a simple bswap.
9895 if (CI->getNumOperands() != 2 ||
9896 CI->getType() != CI->getOperand(1)->getType() ||
9897 !CI->getType()->isIntegerTy())
9900 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9901 if (!Ty || Ty->getBitWidth() % 16 != 0)
9904 // Okay, we can do this xform, do so now.
9905 const Type *Tys[] = { Ty };
9906 Module *M = CI->getParent()->getParent()->getParent();
9907 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9909 Value *Op = CI->getOperand(1);
9910 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9912 CI->replaceAllUsesWith(Op);
9913 CI->eraseFromParent();
9917 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9918 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9919 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9921 std::string AsmStr = IA->getAsmString();
9923 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9924 SmallVector<StringRef, 4> AsmPieces;
9925 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9927 switch (AsmPieces.size()) {
9928 default: return false;
9930 AsmStr = AsmPieces[0];
9932 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9935 if (AsmPieces.size() == 2 &&
9936 (AsmPieces[0] == "bswap" ||
9937 AsmPieces[0] == "bswapq" ||
9938 AsmPieces[0] == "bswapl") &&
9939 (AsmPieces[1] == "$0" ||
9940 AsmPieces[1] == "${0:q}")) {
9941 // No need to check constraints, nothing other than the equivalent of
9942 // "=r,0" would be valid here.
9943 return LowerToBSwap(CI);
9945 // rorw $$8, ${0:w} --> llvm.bswap.i16
9946 if (CI->getType()->isIntegerTy(16) &&
9947 AsmPieces.size() == 3 &&
9948 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9949 AsmPieces[1] == "$$8," &&
9950 AsmPieces[2] == "${0:w}" &&
9951 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9953 const std::string &Constraints = IA->getConstraintString();
9954 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9955 std::sort(AsmPieces.begin(), AsmPieces.end());
9956 if (AsmPieces.size() == 4 &&
9957 AsmPieces[0] == "~{cc}" &&
9958 AsmPieces[1] == "~{dirflag}" &&
9959 AsmPieces[2] == "~{flags}" &&
9960 AsmPieces[3] == "~{fpsr}") {
9961 return LowerToBSwap(CI);
9966 if (CI->getType()->isIntegerTy(64) &&
9967 Constraints.size() >= 2 &&
9968 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9969 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9970 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9971 SmallVector<StringRef, 4> Words;
9972 SplitString(AsmPieces[0], Words, " \t");
9973 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9975 SplitString(AsmPieces[1], Words, " \t");
9976 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9978 SplitString(AsmPieces[2], Words, " \t,");
9979 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9980 Words[2] == "%edx") {
9981 return LowerToBSwap(CI);
9993 /// getConstraintType - Given a constraint letter, return the type of
9994 /// constraint it is for this target.
9995 X86TargetLowering::ConstraintType
9996 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9997 if (Constraint.size() == 1) {
9998 switch (Constraint[0]) {
10010 return C_RegisterClass;
10018 return TargetLowering::getConstraintType(Constraint);
10021 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10022 /// with another that has more specific requirements based on the type of the
10023 /// corresponding operand.
10024 const char *X86TargetLowering::
10025 LowerXConstraint(EVT ConstraintVT) const {
10026 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10027 // 'f' like normal targets.
10028 if (ConstraintVT.isFloatingPoint()) {
10029 if (Subtarget->hasSSE2())
10031 if (Subtarget->hasSSE1())
10035 return TargetLowering::LowerXConstraint(ConstraintVT);
10038 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10039 /// vector. If it is invalid, don't add anything to Ops.
10040 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10043 std::vector<SDValue>&Ops,
10044 SelectionDAG &DAG) const {
10045 SDValue Result(0, 0);
10047 switch (Constraint) {
10050 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10051 if (C->getZExtValue() <= 31) {
10052 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10058 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10059 if (C->getZExtValue() <= 63) {
10060 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10067 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10068 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10075 if (C->getZExtValue() <= 255) {
10076 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10082 // 32-bit signed value
10083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10084 const ConstantInt *CI = C->getConstantIntValue();
10085 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10086 C->getSExtValue())) {
10087 // Widen to 64 bits here to get it sign extended.
10088 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10091 // FIXME gcc accepts some relocatable values here too, but only in certain
10092 // memory models; it's complicated.
10097 // 32-bit unsigned value
10098 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10099 const ConstantInt *CI = C->getConstantIntValue();
10100 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10101 C->getZExtValue())) {
10102 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10106 // FIXME gcc accepts some relocatable values here too, but only in certain
10107 // memory models; it's complicated.
10111 // Literal immediates are always ok.
10112 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10113 // Widen to 64 bits here to get it sign extended.
10114 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10118 // If we are in non-pic codegen mode, we allow the address of a global (with
10119 // an optional displacement) to be used with 'i'.
10120 GlobalAddressSDNode *GA = 0;
10121 int64_t Offset = 0;
10123 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10125 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10126 Offset += GA->getOffset();
10128 } else if (Op.getOpcode() == ISD::ADD) {
10129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10130 Offset += C->getZExtValue();
10131 Op = Op.getOperand(0);
10134 } else if (Op.getOpcode() == ISD::SUB) {
10135 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10136 Offset += -C->getZExtValue();
10137 Op = Op.getOperand(0);
10142 // Otherwise, this isn't something we can handle, reject it.
10146 const GlobalValue *GV = GA->getGlobal();
10147 // If we require an extra load to get this address, as in PIC mode, we
10148 // can't accept it.
10149 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10150 getTargetMachine())))
10154 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10156 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10162 if (Result.getNode()) {
10163 Ops.push_back(Result);
10166 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10170 std::vector<unsigned> X86TargetLowering::
10171 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10173 if (Constraint.size() == 1) {
10174 // FIXME: not handling fp-stack yet!
10175 switch (Constraint[0]) { // GCC X86 Constraint Letters
10176 default: break; // Unknown constraint letter
10177 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10178 if (Subtarget->is64Bit()) {
10179 if (VT == MVT::i32)
10180 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10181 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10182 X86::R10D,X86::R11D,X86::R12D,
10183 X86::R13D,X86::R14D,X86::R15D,
10184 X86::EBP, X86::ESP, 0);
10185 else if (VT == MVT::i16)
10186 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10187 X86::SI, X86::DI, X86::R8W,X86::R9W,
10188 X86::R10W,X86::R11W,X86::R12W,
10189 X86::R13W,X86::R14W,X86::R15W,
10190 X86::BP, X86::SP, 0);
10191 else if (VT == MVT::i8)
10192 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10193 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10194 X86::R10B,X86::R11B,X86::R12B,
10195 X86::R13B,X86::R14B,X86::R15B,
10196 X86::BPL, X86::SPL, 0);
10198 else if (VT == MVT::i64)
10199 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10200 X86::RSI, X86::RDI, X86::R8, X86::R9,
10201 X86::R10, X86::R11, X86::R12,
10202 X86::R13, X86::R14, X86::R15,
10203 X86::RBP, X86::RSP, 0);
10207 // 32-bit fallthrough
10208 case 'Q': // Q_REGS
10209 if (VT == MVT::i32)
10210 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10211 else if (VT == MVT::i16)
10212 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10213 else if (VT == MVT::i8)
10214 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10215 else if (VT == MVT::i64)
10216 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10221 return std::vector<unsigned>();
10224 std::pair<unsigned, const TargetRegisterClass*>
10225 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10227 // First, see if this is a constraint that directly corresponds to an LLVM
10229 if (Constraint.size() == 1) {
10230 // GCC Constraint Letters
10231 switch (Constraint[0]) {
10233 case 'r': // GENERAL_REGS
10234 case 'l': // INDEX_REGS
10236 return std::make_pair(0U, X86::GR8RegisterClass);
10237 if (VT == MVT::i16)
10238 return std::make_pair(0U, X86::GR16RegisterClass);
10239 if (VT == MVT::i32 || !Subtarget->is64Bit())
10240 return std::make_pair(0U, X86::GR32RegisterClass);
10241 return std::make_pair(0U, X86::GR64RegisterClass);
10242 case 'R': // LEGACY_REGS
10244 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10245 if (VT == MVT::i16)
10246 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10247 if (VT == MVT::i32 || !Subtarget->is64Bit())
10248 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10249 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10250 case 'f': // FP Stack registers.
10251 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10252 // value to the correct fpstack register class.
10253 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10254 return std::make_pair(0U, X86::RFP32RegisterClass);
10255 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10256 return std::make_pair(0U, X86::RFP64RegisterClass);
10257 return std::make_pair(0U, X86::RFP80RegisterClass);
10258 case 'y': // MMX_REGS if MMX allowed.
10259 if (!Subtarget->hasMMX()) break;
10260 return std::make_pair(0U, X86::VR64RegisterClass);
10261 case 'Y': // SSE_REGS if SSE2 allowed
10262 if (!Subtarget->hasSSE2()) break;
10264 case 'x': // SSE_REGS if SSE1 allowed
10265 if (!Subtarget->hasSSE1()) break;
10267 switch (VT.getSimpleVT().SimpleTy) {
10269 // Scalar SSE types.
10272 return std::make_pair(0U, X86::FR32RegisterClass);
10275 return std::make_pair(0U, X86::FR64RegisterClass);
10283 return std::make_pair(0U, X86::VR128RegisterClass);
10289 // Use the default implementation in TargetLowering to convert the register
10290 // constraint into a member of a register class.
10291 std::pair<unsigned, const TargetRegisterClass*> Res;
10292 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10294 // Not found as a standard register?
10295 if (Res.second == 0) {
10296 // Map st(0) -> st(7) -> ST0
10297 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10298 tolower(Constraint[1]) == 's' &&
10299 tolower(Constraint[2]) == 't' &&
10300 Constraint[3] == '(' &&
10301 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10302 Constraint[5] == ')' &&
10303 Constraint[6] == '}') {
10305 Res.first = X86::ST0+Constraint[4]-'0';
10306 Res.second = X86::RFP80RegisterClass;
10310 // GCC allows "st(0)" to be called just plain "st".
10311 if (StringRef("{st}").equals_lower(Constraint)) {
10312 Res.first = X86::ST0;
10313 Res.second = X86::RFP80RegisterClass;
10318 if (StringRef("{flags}").equals_lower(Constraint)) {
10319 Res.first = X86::EFLAGS;
10320 Res.second = X86::CCRRegisterClass;
10324 // 'A' means EAX + EDX.
10325 if (Constraint == "A") {
10326 Res.first = X86::EAX;
10327 Res.second = X86::GR32_ADRegisterClass;
10333 // Otherwise, check to see if this is a register class of the wrong value
10334 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10335 // turn into {ax},{dx}.
10336 if (Res.second->hasType(VT))
10337 return Res; // Correct type already, nothing to do.
10339 // All of the single-register GCC register classes map their values onto
10340 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10341 // really want an 8-bit or 32-bit register, map to the appropriate register
10342 // class and return the appropriate register.
10343 if (Res.second == X86::GR16RegisterClass) {
10344 if (VT == MVT::i8) {
10345 unsigned DestReg = 0;
10346 switch (Res.first) {
10348 case X86::AX: DestReg = X86::AL; break;
10349 case X86::DX: DestReg = X86::DL; break;
10350 case X86::CX: DestReg = X86::CL; break;
10351 case X86::BX: DestReg = X86::BL; break;
10354 Res.first = DestReg;
10355 Res.second = X86::GR8RegisterClass;
10357 } else if (VT == MVT::i32) {
10358 unsigned DestReg = 0;
10359 switch (Res.first) {
10361 case X86::AX: DestReg = X86::EAX; break;
10362 case X86::DX: DestReg = X86::EDX; break;
10363 case X86::CX: DestReg = X86::ECX; break;
10364 case X86::BX: DestReg = X86::EBX; break;
10365 case X86::SI: DestReg = X86::ESI; break;
10366 case X86::DI: DestReg = X86::EDI; break;
10367 case X86::BP: DestReg = X86::EBP; break;
10368 case X86::SP: DestReg = X86::ESP; break;
10371 Res.first = DestReg;
10372 Res.second = X86::GR32RegisterClass;
10374 } else if (VT == MVT::i64) {
10375 unsigned DestReg = 0;
10376 switch (Res.first) {
10378 case X86::AX: DestReg = X86::RAX; break;
10379 case X86::DX: DestReg = X86::RDX; break;
10380 case X86::CX: DestReg = X86::RCX; break;
10381 case X86::BX: DestReg = X86::RBX; break;
10382 case X86::SI: DestReg = X86::RSI; break;
10383 case X86::DI: DestReg = X86::RDI; break;
10384 case X86::BP: DestReg = X86::RBP; break;
10385 case X86::SP: DestReg = X86::RSP; break;
10388 Res.first = DestReg;
10389 Res.second = X86::GR64RegisterClass;
10392 } else if (Res.second == X86::FR32RegisterClass ||
10393 Res.second == X86::FR64RegisterClass ||
10394 Res.second == X86::VR128RegisterClass) {
10395 // Handle references to XMM physical registers that got mapped into the
10396 // wrong class. This can happen with constraints like {xmm0} where the
10397 // target independent register mapper will just pick the first match it can
10398 // find, ignoring the required type.
10399 if (VT == MVT::f32)
10400 Res.second = X86::FR32RegisterClass;
10401 else if (VT == MVT::f64)
10402 Res.second = X86::FR64RegisterClass;
10403 else if (X86::VR128RegisterClass->hasType(VT))
10404 Res.second = X86::VR128RegisterClass;