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(SchedulingForRegPressure);
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 if (X86ScalarSSEf64) {
149 // We have an impenetrably clever algorithm for ui64->double only.
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
152 // We have an algorithm for SSE2, and we turn this into a 64-bit
153 // FILD for other targets.
154 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
157 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
159 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
160 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
163 // SSE has no i16 to fp conversion, only i32
164 if (X86ScalarSSEf32) {
165 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
166 // f32 and f64 cases are Legal, f80 case is not
167 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
169 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
174 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
177 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
178 // are Legal, f80 is custom lowered.
179 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
182 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
184 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
185 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
187 if (X86ScalarSSEf32) {
188 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
189 // f32 and f64 cases are Legal, f80 case is not
190 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
192 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
193 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
196 // Handle FP_TO_UINT by promoting the destination to a larger signed
198 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
199 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
200 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
202 if (Subtarget->is64Bit()) {
203 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
204 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
205 } else if (!UseSoftFloat) {
206 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
207 // Expand FP_TO_UINT into a select.
208 // FIXME: We would like to use a Custom expander here eventually to do
209 // the optimal thing for SSE vs. the default expansion in the legalizer.
210 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
212 // With SSE3 we can use fisttpll to convert to a signed i64; without
213 // SSE, we're stuck with a fistpll.
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
217 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
218 if (!X86ScalarSSEf64) {
219 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
220 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
223 // Scalar integer divide and remainder are lowered to use operations that
224 // produce two results, to match the available instructions. This exposes
225 // the two-result form to trivial CSE, which is able to combine x/y and x%y
226 // into a single instruction.
228 // Scalar integer multiply-high is also lowered to use two-result
229 // operations, to match the available instructions. However, plain multiply
230 // (low) operations are left as Legal, as there are single-result
231 // instructions for this in x86. Using the two-result multiply instructions
232 // when both high and low results are needed must be arranged by dagcombine.
233 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
234 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
235 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
236 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
237 setOperationAction(ISD::SREM , MVT::i8 , Expand);
238 setOperationAction(ISD::UREM , MVT::i8 , Expand);
239 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
240 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
241 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
242 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
243 setOperationAction(ISD::SREM , MVT::i16 , Expand);
244 setOperationAction(ISD::UREM , MVT::i16 , Expand);
245 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
246 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
247 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
248 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
249 setOperationAction(ISD::SREM , MVT::i32 , Expand);
250 setOperationAction(ISD::UREM , MVT::i32 , Expand);
251 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
252 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
253 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
254 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
255 setOperationAction(ISD::SREM , MVT::i64 , Expand);
256 setOperationAction(ISD::UREM , MVT::i64 , Expand);
258 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
259 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
260 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
261 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
262 if (Subtarget->is64Bit())
263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
267 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
268 setOperationAction(ISD::FREM , MVT::f32 , Expand);
269 setOperationAction(ISD::FREM , MVT::f64 , Expand);
270 setOperationAction(ISD::FREM , MVT::f80 , Expand);
271 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
273 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
274 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
275 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
276 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
277 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
278 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
279 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
280 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
281 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
282 if (Subtarget->is64Bit()) {
283 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
284 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
285 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
288 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
289 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
291 // These should be promoted to a larger select which is supported.
292 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
293 // X86 wants to expand cmov itself.
294 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
295 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
296 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
297 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
298 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
299 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
300 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
301 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
302 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
303 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
304 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
305 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
306 if (Subtarget->is64Bit()) {
307 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
308 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
310 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
313 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
314 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
315 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
316 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
317 if (Subtarget->is64Bit())
318 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
319 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
320 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
323 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
324 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
325 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
326 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
328 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
329 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
330 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
331 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
332 if (Subtarget->is64Bit()) {
333 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
334 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
335 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
338 if (Subtarget->hasSSE1())
339 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
341 if (!Subtarget->hasSSE2())
342 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
344 // Expand certain atomics
345 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
346 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
347 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
348 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
350 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
351 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
352 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
353 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
355 if (!Subtarget->is64Bit()) {
356 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
357 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
358 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
359 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
360 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
361 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
362 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
365 // FIXME - use subtarget debug flags
366 if (!Subtarget->isTargetDarwin() &&
367 !Subtarget->isTargetELF() &&
368 !Subtarget->isTargetCygMing()) {
369 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
372 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
373 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
374 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
375 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
376 if (Subtarget->is64Bit()) {
377 setExceptionPointerRegister(X86::RAX);
378 setExceptionSelectorRegister(X86::RDX);
380 setExceptionPointerRegister(X86::EAX);
381 setExceptionSelectorRegister(X86::EDX);
383 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
384 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
386 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
388 setOperationAction(ISD::TRAP, MVT::Other, Legal);
390 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
391 setOperationAction(ISD::VASTART , MVT::Other, Custom);
392 setOperationAction(ISD::VAEND , MVT::Other, Expand);
393 if (Subtarget->is64Bit()) {
394 setOperationAction(ISD::VAARG , MVT::Other, Custom);
395 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
397 setOperationAction(ISD::VAARG , MVT::Other, Expand);
398 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
401 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
402 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
403 if (Subtarget->is64Bit())
404 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
405 if (Subtarget->isTargetCygMing())
406 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
408 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
410 if (!UseSoftFloat && X86ScalarSSEf64) {
411 // f32 and f64 use SSE.
412 // Set up the FP register classes.
413 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
414 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
416 // Use ANDPD to simulate FABS.
417 setOperationAction(ISD::FABS , MVT::f64, Custom);
418 setOperationAction(ISD::FABS , MVT::f32, Custom);
420 // Use XORP to simulate FNEG.
421 setOperationAction(ISD::FNEG , MVT::f64, Custom);
422 setOperationAction(ISD::FNEG , MVT::f32, Custom);
424 // Use ANDPD and ORPD to simulate FCOPYSIGN.
425 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
426 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
428 // We don't support sin/cos/fmod
429 setOperationAction(ISD::FSIN , MVT::f64, Expand);
430 setOperationAction(ISD::FCOS , MVT::f64, Expand);
431 setOperationAction(ISD::FSIN , MVT::f32, Expand);
432 setOperationAction(ISD::FCOS , MVT::f32, Expand);
434 // Expand FP immediates into loads from the stack, except for the special
436 addLegalFPImmediate(APFloat(+0.0)); // xorpd
437 addLegalFPImmediate(APFloat(+0.0f)); // xorps
438 } else if (!UseSoftFloat && X86ScalarSSEf32) {
439 // Use SSE for f32, x87 for f64.
440 // Set up the FP register classes.
441 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
442 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
444 // Use ANDPS to simulate FABS.
445 setOperationAction(ISD::FABS , MVT::f32, Custom);
447 // Use XORP to simulate FNEG.
448 setOperationAction(ISD::FNEG , MVT::f32, Custom);
450 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
452 // Use ANDPS and ORPS to simulate FCOPYSIGN.
453 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
454 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
456 // We don't support sin/cos/fmod
457 setOperationAction(ISD::FSIN , MVT::f32, Expand);
458 setOperationAction(ISD::FCOS , MVT::f32, Expand);
460 // Special cases we handle for FP constants.
461 addLegalFPImmediate(APFloat(+0.0f)); // xorps
462 addLegalFPImmediate(APFloat(+0.0)); // FLD0
463 addLegalFPImmediate(APFloat(+1.0)); // FLD1
464 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
465 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
468 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
469 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
471 } else if (!UseSoftFloat) {
472 // f32 and f64 in x87.
473 // Set up the FP register classes.
474 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
475 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
477 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
478 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
479 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
480 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
483 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
484 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
486 addLegalFPImmediate(APFloat(+0.0)); // FLD0
487 addLegalFPImmediate(APFloat(+1.0)); // FLD1
488 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
489 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
490 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
491 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
492 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
493 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
496 // Long double always uses X87.
498 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
499 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
500 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
503 APFloat TmpFlt(+0.0);
504 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
506 addLegalFPImmediate(TmpFlt); // FLD0
508 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
509 APFloat TmpFlt2(+1.0);
510 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
512 addLegalFPImmediate(TmpFlt2); // FLD1
513 TmpFlt2.changeSign();
514 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
518 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
519 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
523 // Always use a library call for pow.
524 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
525 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
526 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
528 setOperationAction(ISD::FLOG, MVT::f80, Expand);
529 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
530 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
531 setOperationAction(ISD::FEXP, MVT::f80, Expand);
532 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
534 // First set operation action for all vector types to either promote
535 // (for widening) or expand (for scalarization). Then we will selectively
536 // turn on ones that can be effectively codegen'd.
537 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
538 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
539 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
554 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
555 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
588 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
592 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
593 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
594 setTruncStoreAction((MVT::SimpleValueType)VT,
595 (MVT::SimpleValueType)InnerVT, Expand);
596 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
597 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
598 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
601 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
602 // with -msoft-float, disable use of MMX as well.
603 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
604 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass, false);
605 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
606 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
607 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
608 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
610 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
611 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
612 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
613 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
615 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
616 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
617 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
618 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
620 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
621 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
623 setOperationAction(ISD::AND, MVT::v8i8, Promote);
624 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
625 setOperationAction(ISD::AND, MVT::v4i16, Promote);
626 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
627 setOperationAction(ISD::AND, MVT::v2i32, Promote);
628 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
629 setOperationAction(ISD::AND, MVT::v1i64, Legal);
631 setOperationAction(ISD::OR, MVT::v8i8, Promote);
632 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
633 setOperationAction(ISD::OR, MVT::v4i16, Promote);
634 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
635 setOperationAction(ISD::OR, MVT::v2i32, Promote);
636 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
637 setOperationAction(ISD::OR, MVT::v1i64, Legal);
639 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
640 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
641 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
642 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
643 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
644 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
645 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
647 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
648 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
649 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
650 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
651 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
652 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
653 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
654 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
655 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
657 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
659 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
661 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
663 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
669 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
671 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
673 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
675 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
676 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
677 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
678 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
679 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
680 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
684 if (!UseSoftFloat && Subtarget->hasSSE1()) {
685 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
687 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
688 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
689 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
690 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
691 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
692 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
693 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
694 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
695 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
697 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
698 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
701 if (!UseSoftFloat && Subtarget->hasSSE2()) {
702 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
704 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
705 // registers cannot be used even for integer operations.
706 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
707 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
708 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
709 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
711 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
712 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
713 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
714 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
715 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
716 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
717 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
718 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
719 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
720 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
721 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
722 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
723 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
724 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
725 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
726 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
728 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
729 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
730 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
731 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
733 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
734 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
735 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
737 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
739 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
740 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
741 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
742 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
743 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
745 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
746 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
747 EVT VT = (MVT::SimpleValueType)i;
748 // Do not attempt to custom lower non-power-of-2 vectors
749 if (!isPowerOf2_32(VT.getVectorNumElements()))
751 // Do not attempt to custom lower non-128-bit vectors
752 if (!VT.is128BitVector())
754 setOperationAction(ISD::BUILD_VECTOR,
755 VT.getSimpleVT().SimpleTy, Custom);
756 setOperationAction(ISD::VECTOR_SHUFFLE,
757 VT.getSimpleVT().SimpleTy, Custom);
758 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
759 VT.getSimpleVT().SimpleTy, Custom);
762 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
763 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
764 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
765 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
766 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
767 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
769 if (Subtarget->is64Bit()) {
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
771 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
774 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
775 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
776 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
779 // Do not attempt to promote non-128-bit vectors
780 if (!VT.is128BitVector()) {
784 setOperationAction(ISD::AND, SVT, Promote);
785 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
786 setOperationAction(ISD::OR, SVT, Promote);
787 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
788 setOperationAction(ISD::XOR, SVT, Promote);
789 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
790 setOperationAction(ISD::LOAD, SVT, Promote);
791 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
792 setOperationAction(ISD::SELECT, SVT, Promote);
793 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
796 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
798 // Custom lower v2i64 and v2f64 selects.
799 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
800 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
801 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
802 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
804 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
805 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
806 if (!DisableMMX && Subtarget->hasMMX()) {
807 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
808 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
812 if (Subtarget->hasSSE41()) {
813 // FIXME: Do we need to handle scalar-to-vector here?
814 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
816 // i8 and i16 vectors are custom , because the source register and source
817 // source memory operand types are not the same width. f32 vectors are
818 // custom since the immediate controlling the insert encodes additional
820 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
821 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
822 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
823 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
826 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
827 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
828 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
830 if (Subtarget->is64Bit()) {
831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
836 if (Subtarget->hasSSE42()) {
837 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
840 if (!UseSoftFloat && Subtarget->hasAVX()) {
841 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
842 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
843 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
844 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
846 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
847 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
848 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
849 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
850 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
851 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
852 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
853 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
854 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
855 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
856 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
857 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
858 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
859 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
860 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
862 // Operations to consider commented out -v16i16 v32i8
863 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
864 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
865 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
866 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
867 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
868 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
869 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
870 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
871 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
872 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
873 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
874 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
875 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
876 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
878 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
879 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
880 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
881 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
883 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
884 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
885 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
889 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
890 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
891 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
892 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
893 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
894 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
897 // Not sure we want to do this since there are no 256-bit integer
900 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
901 // This includes 256-bit vectors
902 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
903 EVT VT = (MVT::SimpleValueType)i;
905 // Do not attempt to custom lower non-power-of-2 vectors
906 if (!isPowerOf2_32(VT.getVectorNumElements()))
909 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
911 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
914 if (Subtarget->is64Bit()) {
915 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
921 // Not sure we want to do this since there are no 256-bit integer
924 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
925 // Including 256-bit vectors
926 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
927 EVT VT = (MVT::SimpleValueType)i;
929 if (!VT.is256BitVector()) {
932 setOperationAction(ISD::AND, VT, Promote);
933 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
934 setOperationAction(ISD::OR, VT, Promote);
935 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
936 setOperationAction(ISD::XOR, VT, Promote);
937 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
938 setOperationAction(ISD::LOAD, VT, Promote);
939 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
940 setOperationAction(ISD::SELECT, VT, Promote);
941 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
944 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
948 // We want to custom lower some of our intrinsics.
949 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
951 // Add/Sub/Mul with overflow operations are custom lowered.
952 setOperationAction(ISD::SADDO, MVT::i32, Custom);
953 setOperationAction(ISD::SADDO, MVT::i64, Custom);
954 setOperationAction(ISD::UADDO, MVT::i32, Custom);
955 setOperationAction(ISD::UADDO, MVT::i64, Custom);
956 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
957 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
958 setOperationAction(ISD::USUBO, MVT::i32, Custom);
959 setOperationAction(ISD::USUBO, MVT::i64, Custom);
960 setOperationAction(ISD::SMULO, MVT::i32, Custom);
961 setOperationAction(ISD::SMULO, MVT::i64, Custom);
963 if (!Subtarget->is64Bit()) {
964 // These libcalls are not available in 32-bit.
965 setLibcallName(RTLIB::SHL_I128, 0);
966 setLibcallName(RTLIB::SRL_I128, 0);
967 setLibcallName(RTLIB::SRA_I128, 0);
970 // We have target-specific dag combine patterns for the following nodes:
971 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
972 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
973 setTargetDAGCombine(ISD::BUILD_VECTOR);
974 setTargetDAGCombine(ISD::SELECT);
975 setTargetDAGCombine(ISD::SHL);
976 setTargetDAGCombine(ISD::SRA);
977 setTargetDAGCombine(ISD::SRL);
978 setTargetDAGCombine(ISD::OR);
979 setTargetDAGCombine(ISD::STORE);
980 setTargetDAGCombine(ISD::MEMBARRIER);
981 setTargetDAGCombine(ISD::ZERO_EXTEND);
982 if (Subtarget->is64Bit())
983 setTargetDAGCombine(ISD::MUL);
985 computeRegisterProperties();
987 // FIXME: These should be based on subtarget info. Plus, the values should
988 // be smaller when we are in optimizing for size mode.
989 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
990 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
991 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
992 setPrefLoopAlignment(16);
993 benefitFromCodePlacementOpt = true;
997 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1002 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1003 /// the desired ByVal argument alignment.
1004 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1007 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1008 if (VTy->getBitWidth() == 128)
1010 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1011 unsigned EltAlign = 0;
1012 getMaxByValAlign(ATy->getElementType(), EltAlign);
1013 if (EltAlign > MaxAlign)
1014 MaxAlign = EltAlign;
1015 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1016 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1017 unsigned EltAlign = 0;
1018 getMaxByValAlign(STy->getElementType(i), EltAlign);
1019 if (EltAlign > MaxAlign)
1020 MaxAlign = EltAlign;
1028 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1029 /// function arguments in the caller parameter area. For X86, aggregates
1030 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1031 /// are at 4-byte boundaries.
1032 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1033 if (Subtarget->is64Bit()) {
1034 // Max of 8 and alignment of type.
1035 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1042 if (Subtarget->hasSSE1())
1043 getMaxByValAlign(Ty, Align);
1047 /// getOptimalMemOpType - Returns the target specific optimal type for load
1048 /// and store operations as a result of memset, memcpy, and memmove
1049 /// lowering. If DstAlign is zero that means it's safe to destination
1050 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1051 /// means there isn't a need to check it against alignment requirement,
1052 /// probably because the source does not need to be loaded. If
1053 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1054 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1055 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1056 /// constant so it does not need to be loaded.
1057 /// It returns EVT::Other if the type should be determined using generic
1058 /// target-independent logic.
1060 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1061 unsigned DstAlign, unsigned SrcAlign,
1062 bool NonScalarIntSafe,
1064 MachineFunction &MF) const {
1065 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1066 // linux. This is because the stack realignment code can't handle certain
1067 // cases like PR2962. This should be removed when PR2962 is fixed.
1068 const Function *F = MF.getFunction();
1069 if (NonScalarIntSafe &&
1070 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1072 (Subtarget->isUnalignedMemAccessFast() ||
1073 ((DstAlign == 0 || DstAlign >= 16) &&
1074 (SrcAlign == 0 || SrcAlign >= 16))) &&
1075 Subtarget->getStackAlignment() >= 16) {
1076 if (Subtarget->hasSSE2())
1078 if (Subtarget->hasSSE1())
1080 } else if (!MemcpyStrSrc && Size >= 8 &&
1081 !Subtarget->is64Bit() &&
1082 Subtarget->getStackAlignment() >= 8 &&
1083 Subtarget->hasSSE2()) {
1084 // Do not use f64 to lower memcpy if source is string constant. It's
1085 // better to use i32 to avoid the loads.
1089 if (Subtarget->is64Bit() && Size >= 8)
1094 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1095 /// current function. The returned value is a member of the
1096 /// MachineJumpTableInfo::JTEntryKind enum.
1097 unsigned X86TargetLowering::getJumpTableEncoding() const {
1098 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1100 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1101 Subtarget->isPICStyleGOT())
1102 return MachineJumpTableInfo::EK_Custom32;
1104 // Otherwise, use the normal jump table encoding heuristics.
1105 return TargetLowering::getJumpTableEncoding();
1108 /// getPICBaseSymbol - Return the X86-32 PIC base.
1110 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1111 MCContext &Ctx) const {
1112 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1113 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1114 Twine(MF->getFunctionNumber())+"$pb");
1119 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1120 const MachineBasicBlock *MBB,
1121 unsigned uid,MCContext &Ctx) const{
1122 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1123 Subtarget->isPICStyleGOT());
1124 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1126 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1127 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1130 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1132 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1133 SelectionDAG &DAG) const {
1134 if (!Subtarget->is64Bit())
1135 // This doesn't have DebugLoc associated with it, but is not really the
1136 // same as a Register.
1137 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1141 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1142 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1144 const MCExpr *X86TargetLowering::
1145 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1146 MCContext &Ctx) const {
1147 // X86-64 uses RIP relative addressing based on the jump table label.
1148 if (Subtarget->isPICStyleRIPRel())
1149 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1151 // Otherwise, the reference is relative to the PIC base.
1152 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1155 /// getFunctionAlignment - Return the Log2 alignment of this function.
1156 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1157 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1160 //===----------------------------------------------------------------------===//
1161 // Return Value Calling Convention Implementation
1162 //===----------------------------------------------------------------------===//
1164 #include "X86GenCallingConv.inc"
1167 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1168 const SmallVectorImpl<EVT> &OutTys,
1169 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1170 SelectionDAG &DAG) const {
1171 SmallVector<CCValAssign, 16> RVLocs;
1172 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1173 RVLocs, *DAG.getContext());
1174 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1178 X86TargetLowering::LowerReturn(SDValue Chain,
1179 CallingConv::ID CallConv, bool isVarArg,
1180 const SmallVectorImpl<ISD::OutputArg> &Outs,
1181 DebugLoc dl, SelectionDAG &DAG) const {
1182 MachineFunction &MF = DAG.getMachineFunction();
1183 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1185 SmallVector<CCValAssign, 16> RVLocs;
1186 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1187 RVLocs, *DAG.getContext());
1188 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1190 // Add the regs to the liveout set for the function.
1191 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1192 for (unsigned i = 0; i != RVLocs.size(); ++i)
1193 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1194 MRI.addLiveOut(RVLocs[i].getLocReg());
1198 SmallVector<SDValue, 6> RetOps;
1199 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1200 // Operand #1 = Bytes To Pop
1201 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1204 // Copy the result values into the output registers.
1205 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1206 CCValAssign &VA = RVLocs[i];
1207 assert(VA.isRegLoc() && "Can only return in registers!");
1208 SDValue ValToCopy = Outs[i].Val;
1210 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1211 // the RET instruction and handled by the FP Stackifier.
1212 if (VA.getLocReg() == X86::ST0 ||
1213 VA.getLocReg() == X86::ST1) {
1214 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1215 // change the value to the FP stack register class.
1216 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1217 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1218 RetOps.push_back(ValToCopy);
1219 // Don't emit a copytoreg.
1223 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1224 // which is returned in RAX / RDX.
1225 if (Subtarget->is64Bit()) {
1226 EVT ValVT = ValToCopy.getValueType();
1227 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1228 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1229 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1230 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1234 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1235 Flag = Chain.getValue(1);
1238 // The x86-64 ABI for returning structs by value requires that we copy
1239 // the sret argument into %rax for the return. We saved the argument into
1240 // a virtual register in the entry block, so now we copy the value out
1242 if (Subtarget->is64Bit() &&
1243 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1244 MachineFunction &MF = DAG.getMachineFunction();
1245 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246 unsigned Reg = FuncInfo->getSRetReturnReg();
1248 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1249 FuncInfo->setSRetReturnReg(Reg);
1251 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1253 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1254 Flag = Chain.getValue(1);
1256 // RAX now acts like a return value.
1257 MRI.addLiveOut(X86::RAX);
1260 RetOps[0] = Chain; // Update chain.
1262 // Add the flag if we have it.
1264 RetOps.push_back(Flag);
1266 return DAG.getNode(X86ISD::RET_FLAG, dl,
1267 MVT::Other, &RetOps[0], RetOps.size());
1270 /// LowerCallResult - Lower the result values of a call into the
1271 /// appropriate copies out of appropriate physical registers.
1274 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1275 CallingConv::ID CallConv, bool isVarArg,
1276 const SmallVectorImpl<ISD::InputArg> &Ins,
1277 DebugLoc dl, SelectionDAG &DAG,
1278 SmallVectorImpl<SDValue> &InVals) const {
1280 // Assign locations to each value returned by this call.
1281 SmallVector<CCValAssign, 16> RVLocs;
1282 bool Is64Bit = Subtarget->is64Bit();
1283 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1284 RVLocs, *DAG.getContext());
1285 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1287 // Copy all of the result registers out of their specified physreg.
1288 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1289 CCValAssign &VA = RVLocs[i];
1290 EVT CopyVT = VA.getValVT();
1292 // If this is x86-64, and we disabled SSE, we can't return FP values
1293 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1294 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1295 report_fatal_error("SSE register return with SSE disabled");
1298 // If this is a call to a function that returns an fp value on the floating
1299 // point stack, but where we prefer to use the value in xmm registers, copy
1300 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1301 if ((VA.getLocReg() == X86::ST0 ||
1302 VA.getLocReg() == X86::ST1) &&
1303 isScalarFPTypeInSSEReg(VA.getValVT())) {
1308 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1309 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1310 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1311 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1312 MVT::v2i64, InFlag).getValue(1);
1313 Val = Chain.getValue(0);
1314 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1315 Val, DAG.getConstant(0, MVT::i64));
1317 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1318 MVT::i64, InFlag).getValue(1);
1319 Val = Chain.getValue(0);
1321 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1323 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1324 CopyVT, InFlag).getValue(1);
1325 Val = Chain.getValue(0);
1327 InFlag = Chain.getValue(2);
1329 if (CopyVT != VA.getValVT()) {
1330 // Round the F80 the right size, which also moves to the appropriate xmm
1332 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1333 // This truncation won't change the value.
1334 DAG.getIntPtrConstant(1));
1337 InVals.push_back(Val);
1344 //===----------------------------------------------------------------------===//
1345 // C & StdCall & Fast Calling Convention implementation
1346 //===----------------------------------------------------------------------===//
1347 // StdCall calling convention seems to be standard for many Windows' API
1348 // routines and around. It differs from C calling convention just a little:
1349 // callee should clean up the stack, not caller. Symbols should be also
1350 // decorated in some fancy way :) It doesn't support any vector arguments.
1351 // For info on fast calling convention see Fast Calling Convention (tail call)
1352 // implementation LowerX86_32FastCCCallTo.
1354 /// CallIsStructReturn - Determines whether a call uses struct return
1356 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1360 return Outs[0].Flags.isSRet();
1363 /// ArgsAreStructReturn - Determines whether a function uses struct
1364 /// return semantics.
1366 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1370 return Ins[0].Flags.isSRet();
1373 /// IsCalleePop - Determines whether the callee is required to pop its
1374 /// own arguments. Callee pop is necessary to support tail calls.
1375 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1376 CallingConv::ID CallingConv) const {
1380 switch (CallingConv) {
1383 case CallingConv::X86_StdCall:
1384 return !Subtarget->is64Bit();
1385 case CallingConv::X86_FastCall:
1386 return !Subtarget->is64Bit();
1387 case CallingConv::Fast:
1388 return GuaranteedTailCallOpt;
1389 case CallingConv::GHC:
1390 return GuaranteedTailCallOpt;
1394 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1395 /// given CallingConvention value.
1396 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1397 if (Subtarget->is64Bit()) {
1398 if (CC == CallingConv::GHC)
1399 return CC_X86_64_GHC;
1400 else if (Subtarget->isTargetWin64())
1401 return CC_X86_Win64_C;
1406 if (CC == CallingConv::X86_FastCall)
1407 return CC_X86_32_FastCall;
1408 else if (CC == CallingConv::Fast)
1409 return CC_X86_32_FastCC;
1410 else if (CC == CallingConv::GHC)
1411 return CC_X86_32_GHC;
1416 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1417 /// by "Src" to address "Dst" with size and alignment information specified by
1418 /// the specific parameter attribute. The copy will be passed as a byval
1419 /// function parameter.
1421 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1422 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1424 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1425 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1426 /*isVolatile*/false, /*AlwaysInline=*/true,
1430 /// IsTailCallConvention - Return true if the calling convention is one that
1431 /// supports tail call optimization.
1432 static bool IsTailCallConvention(CallingConv::ID CC) {
1433 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1436 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1437 /// a tailcall target by changing its ABI.
1438 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1439 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1443 X86TargetLowering::LowerMemArgument(SDValue Chain,
1444 CallingConv::ID CallConv,
1445 const SmallVectorImpl<ISD::InputArg> &Ins,
1446 DebugLoc dl, SelectionDAG &DAG,
1447 const CCValAssign &VA,
1448 MachineFrameInfo *MFI,
1450 // Create the nodes corresponding to a load from this parameter slot.
1451 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1452 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1453 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1456 // If value is passed by pointer we have address passed instead of the value
1458 if (VA.getLocInfo() == CCValAssign::Indirect)
1459 ValVT = VA.getLocVT();
1461 ValVT = VA.getValVT();
1463 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1464 // changed with more analysis.
1465 // In case of tail call optimization mark all arguments mutable. Since they
1466 // could be overwritten by lowering of arguments in case of a tail call.
1467 if (Flags.isByVal()) {
1468 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1469 VA.getLocMemOffset(), isImmutable, false);
1470 return DAG.getFrameIndex(FI, getPointerTy());
1472 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1473 VA.getLocMemOffset(), isImmutable, false);
1474 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1475 return DAG.getLoad(ValVT, dl, Chain, FIN,
1476 PseudoSourceValue::getFixedStack(FI), 0,
1482 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1483 CallingConv::ID CallConv,
1485 const SmallVectorImpl<ISD::InputArg> &Ins,
1488 SmallVectorImpl<SDValue> &InVals)
1490 MachineFunction &MF = DAG.getMachineFunction();
1491 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1493 const Function* Fn = MF.getFunction();
1494 if (Fn->hasExternalLinkage() &&
1495 Subtarget->isTargetCygMing() &&
1496 Fn->getName() == "main")
1497 FuncInfo->setForceFramePointer(true);
1499 MachineFrameInfo *MFI = MF.getFrameInfo();
1500 bool Is64Bit = Subtarget->is64Bit();
1501 bool IsWin64 = Subtarget->isTargetWin64();
1503 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1504 "Var args not supported with calling convention fastcc or ghc");
1506 // Assign locations to all of the incoming arguments.
1507 SmallVector<CCValAssign, 16> ArgLocs;
1508 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1509 ArgLocs, *DAG.getContext());
1510 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1512 unsigned LastVal = ~0U;
1514 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1515 CCValAssign &VA = ArgLocs[i];
1516 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1518 assert(VA.getValNo() != LastVal &&
1519 "Don't support value assigned to multiple locs yet");
1520 LastVal = VA.getValNo();
1522 if (VA.isRegLoc()) {
1523 EVT RegVT = VA.getLocVT();
1524 TargetRegisterClass *RC = NULL;
1525 if (RegVT == MVT::i32)
1526 RC = X86::GR32RegisterClass;
1527 else if (Is64Bit && RegVT == MVT::i64)
1528 RC = X86::GR64RegisterClass;
1529 else if (RegVT == MVT::f32)
1530 RC = X86::FR32RegisterClass;
1531 else if (RegVT == MVT::f64)
1532 RC = X86::FR64RegisterClass;
1533 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1534 RC = X86::VR128RegisterClass;
1535 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1536 RC = X86::VR64RegisterClass;
1538 llvm_unreachable("Unknown argument type!");
1540 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1541 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1543 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1544 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1546 if (VA.getLocInfo() == CCValAssign::SExt)
1547 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1548 DAG.getValueType(VA.getValVT()));
1549 else if (VA.getLocInfo() == CCValAssign::ZExt)
1550 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1551 DAG.getValueType(VA.getValVT()));
1552 else if (VA.getLocInfo() == CCValAssign::BCvt)
1553 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1555 if (VA.isExtInLoc()) {
1556 // Handle MMX values passed in XMM regs.
1557 if (RegVT.isVector()) {
1558 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1559 ArgValue, DAG.getConstant(0, MVT::i64));
1560 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1562 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1565 assert(VA.isMemLoc());
1566 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1569 // If value is passed via pointer - do a load.
1570 if (VA.getLocInfo() == CCValAssign::Indirect)
1571 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1574 InVals.push_back(ArgValue);
1577 // The x86-64 ABI for returning structs by value requires that we copy
1578 // the sret argument into %rax for the return. Save the argument into
1579 // a virtual register so that we can access it from the return points.
1580 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1581 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1582 unsigned Reg = FuncInfo->getSRetReturnReg();
1584 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1585 FuncInfo->setSRetReturnReg(Reg);
1587 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1588 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1591 unsigned StackSize = CCInfo.getNextStackOffset();
1592 // Align stack specially for tail calls.
1593 if (FuncIsMadeTailCallSafe(CallConv))
1594 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1596 // If the function takes variable number of arguments, make a frame index for
1597 // the start of the first vararg value... for expansion of llvm.va_start.
1599 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1600 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1604 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1606 // FIXME: We should really autogenerate these arrays
1607 static const unsigned GPR64ArgRegsWin64[] = {
1608 X86::RCX, X86::RDX, X86::R8, X86::R9
1610 static const unsigned XMMArgRegsWin64[] = {
1611 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1613 static const unsigned GPR64ArgRegs64Bit[] = {
1614 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1616 static const unsigned XMMArgRegs64Bit[] = {
1617 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1618 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1620 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1623 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1624 GPR64ArgRegs = GPR64ArgRegsWin64;
1625 XMMArgRegs = XMMArgRegsWin64;
1627 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1628 GPR64ArgRegs = GPR64ArgRegs64Bit;
1629 XMMArgRegs = XMMArgRegs64Bit;
1631 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1633 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1636 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1637 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1638 "SSE register cannot be used when SSE is disabled!");
1639 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1640 "SSE register cannot be used when SSE is disabled!");
1641 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1642 // Kernel mode asks for SSE to be disabled, so don't push them
1644 TotalNumXMMRegs = 0;
1646 // For X86-64, if there are vararg parameters that are passed via
1647 // registers, then we must store them to their spots on the stack so they
1648 // may be loaded by deferencing the result of va_next.
1649 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1650 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1651 FuncInfo->setRegSaveFrameIndex(
1652 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1655 // Store the integer parameter registers.
1656 SmallVector<SDValue, 8> MemOps;
1657 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1659 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1660 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1661 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1662 DAG.getIntPtrConstant(Offset));
1663 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1664 X86::GR64RegisterClass);
1665 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1667 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1668 PseudoSourceValue::getFixedStack(
1669 FuncInfo->getRegSaveFrameIndex()),
1670 Offset, false, false, 0);
1671 MemOps.push_back(Store);
1675 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1676 // Now store the XMM (fp + vector) parameter registers.
1677 SmallVector<SDValue, 11> SaveXMMOps;
1678 SaveXMMOps.push_back(Chain);
1680 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1681 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1682 SaveXMMOps.push_back(ALVal);
1684 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1685 FuncInfo->getRegSaveFrameIndex()));
1686 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1687 FuncInfo->getVarArgsFPOffset()));
1689 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1690 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1691 X86::VR128RegisterClass);
1692 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1693 SaveXMMOps.push_back(Val);
1695 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1697 &SaveXMMOps[0], SaveXMMOps.size()));
1700 if (!MemOps.empty())
1701 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1702 &MemOps[0], MemOps.size());
1706 // Some CCs need callee pop.
1707 if (IsCalleePop(isVarArg, CallConv)) {
1708 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1710 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1711 // If this is an sret function, the return should pop the hidden pointer.
1712 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1713 FuncInfo->setBytesToPopOnReturn(4);
1717 // RegSaveFrameIndex is X86-64 only.
1718 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1719 if (CallConv == CallingConv::X86_FastCall)
1720 // fastcc functions can't have varargs.
1721 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1728 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1729 SDValue StackPtr, SDValue Arg,
1730 DebugLoc dl, SelectionDAG &DAG,
1731 const CCValAssign &VA,
1732 ISD::ArgFlagsTy Flags) const {
1733 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1734 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1735 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1736 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1737 if (Flags.isByVal()) {
1738 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1740 return DAG.getStore(Chain, dl, Arg, PtrOff,
1741 PseudoSourceValue::getStack(), LocMemOffset,
1745 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1746 /// optimization is performed and it is required.
1748 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1749 SDValue &OutRetAddr, SDValue Chain,
1750 bool IsTailCall, bool Is64Bit,
1751 int FPDiff, DebugLoc dl) const {
1752 // Adjust the Return address stack slot.
1753 EVT VT = getPointerTy();
1754 OutRetAddr = getReturnAddressFrameIndex(DAG);
1756 // Load the "old" Return address.
1757 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1758 return SDValue(OutRetAddr.getNode(), 1);
1761 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1762 /// optimization is performed and it is required (FPDiff!=0).
1764 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1765 SDValue Chain, SDValue RetAddrFrIdx,
1766 bool Is64Bit, int FPDiff, DebugLoc dl) {
1767 // Store the return address to the appropriate stack slot.
1768 if (!FPDiff) return Chain;
1769 // Calculate the new stack slot for the return address.
1770 int SlotSize = Is64Bit ? 8 : 4;
1771 int NewReturnAddrFI =
1772 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1773 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1774 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1775 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1776 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1782 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1783 CallingConv::ID CallConv, bool isVarArg,
1785 const SmallVectorImpl<ISD::OutputArg> &Outs,
1786 const SmallVectorImpl<ISD::InputArg> &Ins,
1787 DebugLoc dl, SelectionDAG &DAG,
1788 SmallVectorImpl<SDValue> &InVals) const {
1789 MachineFunction &MF = DAG.getMachineFunction();
1790 bool Is64Bit = Subtarget->is64Bit();
1791 bool IsStructRet = CallIsStructReturn(Outs);
1792 bool IsSibcall = false;
1795 // Check if it's really possible to do a tail call.
1796 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1797 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1800 // Sibcalls are automatically detected tailcalls which do not require
1802 if (!GuaranteedTailCallOpt && isTailCall)
1809 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1810 "Var args not supported with calling convention fastcc or ghc");
1812 // Analyze operands of the call, assigning locations to each operand.
1813 SmallVector<CCValAssign, 16> ArgLocs;
1814 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1815 ArgLocs, *DAG.getContext());
1816 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1818 // Get a count of how many bytes are to be pushed on the stack.
1819 unsigned NumBytes = CCInfo.getNextStackOffset();
1821 // This is a sibcall. The memory operands are available in caller's
1822 // own caller's stack.
1824 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1825 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1828 if (isTailCall && !IsSibcall) {
1829 // Lower arguments at fp - stackoffset + fpdiff.
1830 unsigned NumBytesCallerPushed =
1831 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1832 FPDiff = NumBytesCallerPushed - NumBytes;
1834 // Set the delta of movement of the returnaddr stackslot.
1835 // But only set if delta is greater than previous delta.
1836 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1837 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1841 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1843 SDValue RetAddrFrIdx;
1844 // Load return adress for tail calls.
1845 if (isTailCall && FPDiff)
1846 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1847 Is64Bit, FPDiff, dl);
1849 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1850 SmallVector<SDValue, 8> MemOpChains;
1853 // Walk the register/memloc assignments, inserting copies/loads. In the case
1854 // of tail call optimization arguments are handle later.
1855 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1856 CCValAssign &VA = ArgLocs[i];
1857 EVT RegVT = VA.getLocVT();
1858 SDValue Arg = Outs[i].Val;
1859 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1860 bool isByVal = Flags.isByVal();
1862 // Promote the value if needed.
1863 switch (VA.getLocInfo()) {
1864 default: llvm_unreachable("Unknown loc info!");
1865 case CCValAssign::Full: break;
1866 case CCValAssign::SExt:
1867 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1869 case CCValAssign::ZExt:
1870 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1872 case CCValAssign::AExt:
1873 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1874 // Special case: passing MMX values in XMM registers.
1875 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1876 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1877 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1879 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1881 case CCValAssign::BCvt:
1882 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1884 case CCValAssign::Indirect: {
1885 // Store the argument.
1886 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1887 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1888 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1889 PseudoSourceValue::getFixedStack(FI), 0,
1896 if (VA.isRegLoc()) {
1897 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1898 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1899 assert(VA.isMemLoc());
1900 if (StackPtr.getNode() == 0)
1901 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1902 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1903 dl, DAG, VA, Flags));
1907 if (!MemOpChains.empty())
1908 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1909 &MemOpChains[0], MemOpChains.size());
1911 // Build a sequence of copy-to-reg nodes chained together with token chain
1912 // and flag operands which copy the outgoing args into registers.
1914 // Tail call byval lowering might overwrite argument registers so in case of
1915 // tail call optimization the copies to registers are lowered later.
1917 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1918 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1919 RegsToPass[i].second, InFlag);
1920 InFlag = Chain.getValue(1);
1923 if (Subtarget->isPICStyleGOT()) {
1924 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1927 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1928 DAG.getNode(X86ISD::GlobalBaseReg,
1929 DebugLoc(), getPointerTy()),
1931 InFlag = Chain.getValue(1);
1933 // If we are tail calling and generating PIC/GOT style code load the
1934 // address of the callee into ECX. The value in ecx is used as target of
1935 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1936 // for tail calls on PIC/GOT architectures. Normally we would just put the
1937 // address of GOT into ebx and then call target@PLT. But for tail calls
1938 // ebx would be restored (since ebx is callee saved) before jumping to the
1941 // Note: The actual moving to ECX is done further down.
1942 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1943 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1944 !G->getGlobal()->hasProtectedVisibility())
1945 Callee = LowerGlobalAddress(Callee, DAG);
1946 else if (isa<ExternalSymbolSDNode>(Callee))
1947 Callee = LowerExternalSymbol(Callee, DAG);
1951 if (Is64Bit && isVarArg) {
1952 // From AMD64 ABI document:
1953 // For calls that may call functions that use varargs or stdargs
1954 // (prototype-less calls or calls to functions containing ellipsis (...) in
1955 // the declaration) %al is used as hidden argument to specify the number
1956 // of SSE registers used. The contents of %al do not need to match exactly
1957 // the number of registers, but must be an ubound on the number of SSE
1958 // registers used and is in the range 0 - 8 inclusive.
1960 // FIXME: Verify this on Win64
1961 // Count the number of XMM registers allocated.
1962 static const unsigned XMMArgRegs[] = {
1963 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1964 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1966 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1967 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1968 && "SSE registers cannot be used when SSE is disabled");
1970 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1971 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1972 InFlag = Chain.getValue(1);
1976 // For tail calls lower the arguments to the 'real' stack slot.
1978 // Force all the incoming stack arguments to be loaded from the stack
1979 // before any new outgoing arguments are stored to the stack, because the
1980 // outgoing stack slots may alias the incoming argument stack slots, and
1981 // the alias isn't otherwise explicit. This is slightly more conservative
1982 // than necessary, because it means that each store effectively depends
1983 // on every argument instead of just those arguments it would clobber.
1984 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1986 SmallVector<SDValue, 8> MemOpChains2;
1989 // Do not flag preceeding copytoreg stuff together with the following stuff.
1991 if (GuaranteedTailCallOpt) {
1992 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1993 CCValAssign &VA = ArgLocs[i];
1996 assert(VA.isMemLoc());
1997 SDValue Arg = Outs[i].Val;
1998 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1999 // Create frame index.
2000 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2001 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2002 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2003 FIN = DAG.getFrameIndex(FI, getPointerTy());
2005 if (Flags.isByVal()) {
2006 // Copy relative to framepointer.
2007 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2008 if (StackPtr.getNode() == 0)
2009 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2011 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2013 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2017 // Store relative to framepointer.
2018 MemOpChains2.push_back(
2019 DAG.getStore(ArgChain, dl, Arg, FIN,
2020 PseudoSourceValue::getFixedStack(FI), 0,
2026 if (!MemOpChains2.empty())
2027 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2028 &MemOpChains2[0], MemOpChains2.size());
2030 // Copy arguments to their registers.
2031 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2032 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2033 RegsToPass[i].second, InFlag);
2034 InFlag = Chain.getValue(1);
2038 // Store the return address to the appropriate stack slot.
2039 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2043 bool WasGlobalOrExternal = false;
2044 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2045 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2046 // In the 64-bit large code model, we have to make all calls
2047 // through a register, since the call instruction's 32-bit
2048 // pc-relative offset may not be large enough to hold the whole
2050 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2051 WasGlobalOrExternal = true;
2052 // If the callee is a GlobalAddress node (quite common, every direct call
2053 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2056 // We should use extra load for direct calls to dllimported functions in
2058 const GlobalValue *GV = G->getGlobal();
2059 if (!GV->hasDLLImportLinkage()) {
2060 unsigned char OpFlags = 0;
2062 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2063 // external symbols most go through the PLT in PIC mode. If the symbol
2064 // has hidden or protected visibility, or if it is static or local, then
2065 // we don't need to use the PLT - we can directly call it.
2066 if (Subtarget->isTargetELF() &&
2067 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2068 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2069 OpFlags = X86II::MO_PLT;
2070 } else if (Subtarget->isPICStyleStubAny() &&
2071 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2072 Subtarget->getDarwinVers() < 9) {
2073 // PC-relative references to external symbols should go through $stub,
2074 // unless we're building with the leopard linker or later, which
2075 // automatically synthesizes these stubs.
2076 OpFlags = X86II::MO_DARWIN_STUB;
2079 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2080 G->getOffset(), OpFlags);
2082 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2083 WasGlobalOrExternal = true;
2084 unsigned char OpFlags = 0;
2086 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2087 // symbols should go through the PLT.
2088 if (Subtarget->isTargetELF() &&
2089 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2090 OpFlags = X86II::MO_PLT;
2091 } else if (Subtarget->isPICStyleStubAny() &&
2092 Subtarget->getDarwinVers() < 9) {
2093 // PC-relative references to external symbols should go through $stub,
2094 // unless we're building with the leopard linker or later, which
2095 // automatically synthesizes these stubs.
2096 OpFlags = X86II::MO_DARWIN_STUB;
2099 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2103 // Returns a chain & a flag for retval copy to use.
2104 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2105 SmallVector<SDValue, 8> Ops;
2107 if (!IsSibcall && isTailCall) {
2108 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2109 DAG.getIntPtrConstant(0, true), InFlag);
2110 InFlag = Chain.getValue(1);
2113 Ops.push_back(Chain);
2114 Ops.push_back(Callee);
2117 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2119 // Add argument registers to the end of the list so that they are known live
2121 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2122 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2123 RegsToPass[i].second.getValueType()));
2125 // Add an implicit use GOT pointer in EBX.
2126 if (!isTailCall && Subtarget->isPICStyleGOT())
2127 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2129 // Add an implicit use of AL for x86 vararg functions.
2130 if (Is64Bit && isVarArg)
2131 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2133 if (InFlag.getNode())
2134 Ops.push_back(InFlag);
2137 // If this is the first return lowered for this function, add the regs
2138 // to the liveout set for the function.
2139 if (MF.getRegInfo().liveout_empty()) {
2140 SmallVector<CCValAssign, 16> RVLocs;
2141 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2143 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2144 for (unsigned i = 0; i != RVLocs.size(); ++i)
2145 if (RVLocs[i].isRegLoc())
2146 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2148 return DAG.getNode(X86ISD::TC_RETURN, dl,
2149 NodeTys, &Ops[0], Ops.size());
2152 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2153 InFlag = Chain.getValue(1);
2155 // Create the CALLSEQ_END node.
2156 unsigned NumBytesForCalleeToPush;
2157 if (IsCalleePop(isVarArg, CallConv))
2158 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2159 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2160 // If this is a call to a struct-return function, the callee
2161 // pops the hidden struct pointer, so we have to push it back.
2162 // This is common for Darwin/X86, Linux & Mingw32 targets.
2163 NumBytesForCalleeToPush = 4;
2165 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2167 // Returns a flag for retval copy to use.
2169 Chain = DAG.getCALLSEQ_END(Chain,
2170 DAG.getIntPtrConstant(NumBytes, true),
2171 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2174 InFlag = Chain.getValue(1);
2177 // Handle result values, copying them out of physregs into vregs that we
2179 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2180 Ins, dl, DAG, InVals);
2184 //===----------------------------------------------------------------------===//
2185 // Fast Calling Convention (tail call) implementation
2186 //===----------------------------------------------------------------------===//
2188 // Like std call, callee cleans arguments, convention except that ECX is
2189 // reserved for storing the tail called function address. Only 2 registers are
2190 // free for argument passing (inreg). Tail call optimization is performed
2192 // * tailcallopt is enabled
2193 // * caller/callee are fastcc
2194 // On X86_64 architecture with GOT-style position independent code only local
2195 // (within module) calls are supported at the moment.
2196 // To keep the stack aligned according to platform abi the function
2197 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2198 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2199 // If a tail called function callee has more arguments than the caller the
2200 // caller needs to make sure that there is room to move the RETADDR to. This is
2201 // achieved by reserving an area the size of the argument delta right after the
2202 // original REtADDR, but before the saved framepointer or the spilled registers
2203 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2215 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2216 /// for a 16 byte align requirement.
2218 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2219 SelectionDAG& DAG) const {
2220 MachineFunction &MF = DAG.getMachineFunction();
2221 const TargetMachine &TM = MF.getTarget();
2222 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2223 unsigned StackAlignment = TFI.getStackAlignment();
2224 uint64_t AlignMask = StackAlignment - 1;
2225 int64_t Offset = StackSize;
2226 uint64_t SlotSize = TD->getPointerSize();
2227 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2228 // Number smaller than 12 so just add the difference.
2229 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2231 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2232 Offset = ((~AlignMask) & Offset) + StackAlignment +
2233 (StackAlignment-SlotSize);
2238 /// MatchingStackOffset - Return true if the given stack call argument is
2239 /// already available in the same position (relatively) of the caller's
2240 /// incoming argument stack.
2242 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2243 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2244 const X86InstrInfo *TII) {
2245 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2247 if (Arg.getOpcode() == ISD::CopyFromReg) {
2248 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2249 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2251 MachineInstr *Def = MRI->getVRegDef(VR);
2254 if (!Flags.isByVal()) {
2255 if (!TII->isLoadFromStackSlot(Def, FI))
2258 unsigned Opcode = Def->getOpcode();
2259 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2260 Def->getOperand(1).isFI()) {
2261 FI = Def->getOperand(1).getIndex();
2262 Bytes = Flags.getByValSize();
2266 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2267 if (Flags.isByVal())
2268 // ByVal argument is passed in as a pointer but it's now being
2269 // dereferenced. e.g.
2270 // define @foo(%struct.X* %A) {
2271 // tail call @bar(%struct.X* byval %A)
2274 SDValue Ptr = Ld->getBasePtr();
2275 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2278 FI = FINode->getIndex();
2282 assert(FI != INT_MAX);
2283 if (!MFI->isFixedObjectIndex(FI))
2285 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2288 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2289 /// for tail call optimization. Targets which want to do tail call
2290 /// optimization should implement this function.
2292 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2293 CallingConv::ID CalleeCC,
2295 bool isCalleeStructRet,
2296 bool isCallerStructRet,
2297 const SmallVectorImpl<ISD::OutputArg> &Outs,
2298 const SmallVectorImpl<ISD::InputArg> &Ins,
2299 SelectionDAG& DAG) const {
2300 if (!IsTailCallConvention(CalleeCC) &&
2301 CalleeCC != CallingConv::C)
2304 // If -tailcallopt is specified, make fastcc functions tail-callable.
2305 const MachineFunction &MF = DAG.getMachineFunction();
2306 const Function *CallerF = DAG.getMachineFunction().getFunction();
2307 CallingConv::ID CallerCC = CallerF->getCallingConv();
2308 bool CCMatch = CallerCC == CalleeCC;
2310 if (GuaranteedTailCallOpt) {
2311 if (IsTailCallConvention(CalleeCC) && CCMatch)
2316 // Look for obvious safe cases to perform tail call optimization that does not
2317 // requite ABI changes. This is what gcc calls sibcall.
2319 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2320 // emit a special epilogue.
2321 if (RegInfo->needsStackRealignment(MF))
2324 // Do not sibcall optimize vararg calls unless the call site is not passing any
2326 if (isVarArg && !Outs.empty())
2329 // Also avoid sibcall optimization if either caller or callee uses struct
2330 // return semantics.
2331 if (isCalleeStructRet || isCallerStructRet)
2334 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2335 // Therefore if it's not used by the call it is not safe to optimize this into
2337 bool Unused = false;
2338 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2345 SmallVector<CCValAssign, 16> RVLocs;
2346 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2347 RVLocs, *DAG.getContext());
2348 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2349 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2350 CCValAssign &VA = RVLocs[i];
2351 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2356 // If the calling conventions do not match, then we'd better make sure the
2357 // results are returned in the same way as what the caller expects.
2359 SmallVector<CCValAssign, 16> RVLocs1;
2360 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2361 RVLocs1, *DAG.getContext());
2362 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2364 SmallVector<CCValAssign, 16> RVLocs2;
2365 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2366 RVLocs2, *DAG.getContext());
2367 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2369 if (RVLocs1.size() != RVLocs2.size())
2371 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2372 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2374 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2376 if (RVLocs1[i].isRegLoc()) {
2377 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2380 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2386 // If the callee takes no arguments then go on to check the results of the
2388 if (!Outs.empty()) {
2389 // Check if stack adjustment is needed. For now, do not do this if any
2390 // argument is passed on the stack.
2391 SmallVector<CCValAssign, 16> ArgLocs;
2392 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2393 ArgLocs, *DAG.getContext());
2394 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2395 if (CCInfo.getNextStackOffset()) {
2396 MachineFunction &MF = DAG.getMachineFunction();
2397 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2399 if (Subtarget->isTargetWin64())
2400 // Win64 ABI has additional complications.
2403 // Check if the arguments are already laid out in the right way as
2404 // the caller's fixed stack objects.
2405 MachineFrameInfo *MFI = MF.getFrameInfo();
2406 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2407 const X86InstrInfo *TII =
2408 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2409 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410 CCValAssign &VA = ArgLocs[i];
2411 EVT RegVT = VA.getLocVT();
2412 SDValue Arg = Outs[i].Val;
2413 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2414 if (VA.getLocInfo() == CCValAssign::Indirect)
2416 if (!VA.isRegLoc()) {
2417 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2429 X86TargetLowering::createFastISel(MachineFunction &mf,
2430 DenseMap<const Value *, unsigned> &vm,
2431 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2432 DenseMap<const AllocaInst *, int> &am,
2433 std::vector<std::pair<MachineInstr*, unsigned> > &pn
2435 , SmallSet<const Instruction *, 8> &cil
2438 return X86::createFastISel(mf, vm, bm, am, pn
2446 //===----------------------------------------------------------------------===//
2447 // Other Lowering Hooks
2448 //===----------------------------------------------------------------------===//
2451 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2452 MachineFunction &MF = DAG.getMachineFunction();
2453 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2454 int ReturnAddrIndex = FuncInfo->getRAIndex();
2456 if (ReturnAddrIndex == 0) {
2457 // Set up a frame object for the return address.
2458 uint64_t SlotSize = TD->getPointerSize();
2459 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2461 FuncInfo->setRAIndex(ReturnAddrIndex);
2464 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2468 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2469 bool hasSymbolicDisplacement) {
2470 // Offset should fit into 32 bit immediate field.
2471 if (!isInt<32>(Offset))
2474 // If we don't have a symbolic displacement - we don't have any extra
2476 if (!hasSymbolicDisplacement)
2479 // FIXME: Some tweaks might be needed for medium code model.
2480 if (M != CodeModel::Small && M != CodeModel::Kernel)
2483 // For small code model we assume that latest object is 16MB before end of 31
2484 // bits boundary. We may also accept pretty large negative constants knowing
2485 // that all objects are in the positive half of address space.
2486 if (M == CodeModel::Small && Offset < 16*1024*1024)
2489 // For kernel code model we know that all object resist in the negative half
2490 // of 32bits address space. We may not accept negative offsets, since they may
2491 // be just off and we may accept pretty large positive ones.
2492 if (M == CodeModel::Kernel && Offset > 0)
2498 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2499 /// specific condition code, returning the condition code and the LHS/RHS of the
2500 /// comparison to make.
2501 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2502 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2504 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2505 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2506 // X > -1 -> X == 0, jump !sign.
2507 RHS = DAG.getConstant(0, RHS.getValueType());
2508 return X86::COND_NS;
2509 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2510 // X < 0 -> X == 0, jump on sign.
2512 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2514 RHS = DAG.getConstant(0, RHS.getValueType());
2515 return X86::COND_LE;
2519 switch (SetCCOpcode) {
2520 default: llvm_unreachable("Invalid integer condition!");
2521 case ISD::SETEQ: return X86::COND_E;
2522 case ISD::SETGT: return X86::COND_G;
2523 case ISD::SETGE: return X86::COND_GE;
2524 case ISD::SETLT: return X86::COND_L;
2525 case ISD::SETLE: return X86::COND_LE;
2526 case ISD::SETNE: return X86::COND_NE;
2527 case ISD::SETULT: return X86::COND_B;
2528 case ISD::SETUGT: return X86::COND_A;
2529 case ISD::SETULE: return X86::COND_BE;
2530 case ISD::SETUGE: return X86::COND_AE;
2534 // First determine if it is required or is profitable to flip the operands.
2536 // If LHS is a foldable load, but RHS is not, flip the condition.
2537 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2538 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2539 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2540 std::swap(LHS, RHS);
2543 switch (SetCCOpcode) {
2549 std::swap(LHS, RHS);
2553 // On a floating point condition, the flags are set as follows:
2555 // 0 | 0 | 0 | X > Y
2556 // 0 | 0 | 1 | X < Y
2557 // 1 | 0 | 0 | X == Y
2558 // 1 | 1 | 1 | unordered
2559 switch (SetCCOpcode) {
2560 default: llvm_unreachable("Condcode should be pre-legalized away");
2562 case ISD::SETEQ: return X86::COND_E;
2563 case ISD::SETOLT: // flipped
2565 case ISD::SETGT: return X86::COND_A;
2566 case ISD::SETOLE: // flipped
2568 case ISD::SETGE: return X86::COND_AE;
2569 case ISD::SETUGT: // flipped
2571 case ISD::SETLT: return X86::COND_B;
2572 case ISD::SETUGE: // flipped
2574 case ISD::SETLE: return X86::COND_BE;
2576 case ISD::SETNE: return X86::COND_NE;
2577 case ISD::SETUO: return X86::COND_P;
2578 case ISD::SETO: return X86::COND_NP;
2580 case ISD::SETUNE: return X86::COND_INVALID;
2584 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2585 /// code. Current x86 isa includes the following FP cmov instructions:
2586 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2587 static bool hasFPCMov(unsigned X86CC) {
2603 /// isFPImmLegal - Returns true if the target can instruction select the
2604 /// specified FP immediate natively. If false, the legalizer will
2605 /// materialize the FP immediate as a load from a constant pool.
2606 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2607 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2608 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2614 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2615 /// the specified range (L, H].
2616 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2617 return (Val < 0) || (Val >= Low && Val < Hi);
2620 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2621 /// specified value.
2622 static bool isUndefOrEqual(int Val, int CmpVal) {
2623 if (Val < 0 || Val == CmpVal)
2628 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2629 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2630 /// the second operand.
2631 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2632 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2633 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2634 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2635 return (Mask[0] < 2 && Mask[1] < 2);
2639 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2640 SmallVector<int, 8> M;
2642 return ::isPSHUFDMask(M, N->getValueType(0));
2645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2646 /// is suitable for input to PSHUFHW.
2647 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2648 if (VT != MVT::v8i16)
2651 // Lower quadword copied in order or undef.
2652 for (int i = 0; i != 4; ++i)
2653 if (Mask[i] >= 0 && Mask[i] != i)
2656 // Upper quadword shuffled.
2657 for (int i = 4; i != 8; ++i)
2658 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2664 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2665 SmallVector<int, 8> M;
2667 return ::isPSHUFHWMask(M, N->getValueType(0));
2670 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2671 /// is suitable for input to PSHUFLW.
2672 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2673 if (VT != MVT::v8i16)
2676 // Upper quadword copied in order.
2677 for (int i = 4; i != 8; ++i)
2678 if (Mask[i] >= 0 && Mask[i] != i)
2681 // Lower quadword shuffled.
2682 for (int i = 0; i != 4; ++i)
2689 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2690 SmallVector<int, 8> M;
2692 return ::isPSHUFLWMask(M, N->getValueType(0));
2695 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2696 /// is suitable for input to PALIGNR.
2697 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2699 int i, e = VT.getVectorNumElements();
2701 // Do not handle v2i64 / v2f64 shuffles with palignr.
2702 if (e < 4 || !hasSSSE3)
2705 for (i = 0; i != e; ++i)
2709 // All undef, not a palignr.
2713 // Determine if it's ok to perform a palignr with only the LHS, since we
2714 // don't have access to the actual shuffle elements to see if RHS is undef.
2715 bool Unary = Mask[i] < (int)e;
2716 bool NeedsUnary = false;
2718 int s = Mask[i] - i;
2720 // Check the rest of the elements to see if they are consecutive.
2721 for (++i; i != e; ++i) {
2726 Unary = Unary && (m < (int)e);
2727 NeedsUnary = NeedsUnary || (m < s);
2729 if (NeedsUnary && !Unary)
2731 if (Unary && m != ((s+i) & (e-1)))
2733 if (!Unary && m != (s+i))
2739 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2740 SmallVector<int, 8> M;
2742 return ::isPALIGNRMask(M, N->getValueType(0), true);
2745 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2746 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2747 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2748 int NumElems = VT.getVectorNumElements();
2749 if (NumElems != 2 && NumElems != 4)
2752 int Half = NumElems / 2;
2753 for (int i = 0; i < Half; ++i)
2754 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2756 for (int i = Half; i < NumElems; ++i)
2757 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2763 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2764 SmallVector<int, 8> M;
2766 return ::isSHUFPMask(M, N->getValueType(0));
2769 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2770 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2771 /// half elements to come from vector 1 (which would equal the dest.) and
2772 /// the upper half to come from vector 2.
2773 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2774 int NumElems = VT.getVectorNumElements();
2776 if (NumElems != 2 && NumElems != 4)
2779 int Half = NumElems / 2;
2780 for (int i = 0; i < Half; ++i)
2781 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2783 for (int i = Half; i < NumElems; ++i)
2784 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2789 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2790 SmallVector<int, 8> M;
2792 return isCommutedSHUFPMask(M, N->getValueType(0));
2795 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2796 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2797 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2798 if (N->getValueType(0).getVectorNumElements() != 4)
2801 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2802 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2803 isUndefOrEqual(N->getMaskElt(1), 7) &&
2804 isUndefOrEqual(N->getMaskElt(2), 2) &&
2805 isUndefOrEqual(N->getMaskElt(3), 3);
2808 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2809 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2811 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2812 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2817 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2818 isUndefOrEqual(N->getMaskElt(1), 3) &&
2819 isUndefOrEqual(N->getMaskElt(2), 2) &&
2820 isUndefOrEqual(N->getMaskElt(3), 3);
2823 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2824 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2825 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2826 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2828 if (NumElems != 2 && NumElems != 4)
2831 for (unsigned i = 0; i < NumElems/2; ++i)
2832 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2835 for (unsigned i = NumElems/2; i < NumElems; ++i)
2836 if (!isUndefOrEqual(N->getMaskElt(i), i))
2842 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2843 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2844 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2845 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2847 if (NumElems != 2 && NumElems != 4)
2850 for (unsigned i = 0; i < NumElems/2; ++i)
2851 if (!isUndefOrEqual(N->getMaskElt(i), i))
2854 for (unsigned i = 0; i < NumElems/2; ++i)
2855 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2861 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2862 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2863 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2864 bool V2IsSplat = false) {
2865 int NumElts = VT.getVectorNumElements();
2866 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2869 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2871 int BitI1 = Mask[i+1];
2872 if (!isUndefOrEqual(BitI, j))
2875 if (!isUndefOrEqual(BitI1, NumElts))
2878 if (!isUndefOrEqual(BitI1, j + NumElts))
2885 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2886 SmallVector<int, 8> M;
2888 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2891 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2892 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2893 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2894 bool V2IsSplat = false) {
2895 int NumElts = VT.getVectorNumElements();
2896 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2899 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2901 int BitI1 = Mask[i+1];
2902 if (!isUndefOrEqual(BitI, j + NumElts/2))
2905 if (isUndefOrEqual(BitI1, NumElts))
2908 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2915 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2916 SmallVector<int, 8> M;
2918 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2921 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2922 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2924 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2925 int NumElems = VT.getVectorNumElements();
2926 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2929 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2931 int BitI1 = Mask[i+1];
2932 if (!isUndefOrEqual(BitI, j))
2934 if (!isUndefOrEqual(BitI1, j))
2940 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2941 SmallVector<int, 8> M;
2943 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2946 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2947 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2949 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2950 int NumElems = VT.getVectorNumElements();
2951 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2954 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2956 int BitI1 = Mask[i+1];
2957 if (!isUndefOrEqual(BitI, j))
2959 if (!isUndefOrEqual(BitI1, j))
2965 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2966 SmallVector<int, 8> M;
2968 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2971 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2972 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2973 /// MOVSD, and MOVD, i.e. setting the lowest element.
2974 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2975 if (VT.getVectorElementType().getSizeInBits() < 32)
2978 int NumElts = VT.getVectorNumElements();
2980 if (!isUndefOrEqual(Mask[0], NumElts))
2983 for (int i = 1; i < NumElts; ++i)
2984 if (!isUndefOrEqual(Mask[i], i))
2990 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2991 SmallVector<int, 8> M;
2993 return ::isMOVLMask(M, N->getValueType(0));
2996 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2997 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2998 /// element of vector 2 and the other elements to come from vector 1 in order.
2999 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3000 bool V2IsSplat = false, bool V2IsUndef = false) {
3001 int NumOps = VT.getVectorNumElements();
3002 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3005 if (!isUndefOrEqual(Mask[0], 0))
3008 for (int i = 1; i < NumOps; ++i)
3009 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3010 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3011 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3017 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3018 bool V2IsUndef = false) {
3019 SmallVector<int, 8> M;
3021 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3024 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3025 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3026 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3027 if (N->getValueType(0).getVectorNumElements() != 4)
3030 // Expect 1, 1, 3, 3
3031 for (unsigned i = 0; i < 2; ++i) {
3032 int Elt = N->getMaskElt(i);
3033 if (Elt >= 0 && Elt != 1)
3038 for (unsigned i = 2; i < 4; ++i) {
3039 int Elt = N->getMaskElt(i);
3040 if (Elt >= 0 && Elt != 3)
3045 // Don't use movshdup if it can be done with a shufps.
3046 // FIXME: verify that matching u, u, 3, 3 is what we want.
3050 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3051 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3052 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3053 if (N->getValueType(0).getVectorNumElements() != 4)
3056 // Expect 0, 0, 2, 2
3057 for (unsigned i = 0; i < 2; ++i)
3058 if (N->getMaskElt(i) > 0)
3062 for (unsigned i = 2; i < 4; ++i) {
3063 int Elt = N->getMaskElt(i);
3064 if (Elt >= 0 && Elt != 2)
3069 // Don't use movsldup if it can be done with a shufps.
3073 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3074 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3075 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3076 int e = N->getValueType(0).getVectorNumElements() / 2;
3078 for (int i = 0; i < e; ++i)
3079 if (!isUndefOrEqual(N->getMaskElt(i), i))
3081 for (int i = 0; i < e; ++i)
3082 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3087 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3088 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3089 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3090 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3091 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3093 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3095 for (int i = 0; i < NumOperands; ++i) {
3096 int Val = SVOp->getMaskElt(NumOperands-i-1);
3097 if (Val < 0) Val = 0;
3098 if (Val >= NumOperands) Val -= NumOperands;
3100 if (i != NumOperands - 1)
3106 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3107 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3108 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3111 // 8 nodes, but we only care about the last 4.
3112 for (unsigned i = 7; i >= 4; --i) {
3113 int Val = SVOp->getMaskElt(i);
3122 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3123 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3124 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3125 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3127 // 8 nodes, but we only care about the first 4.
3128 for (int i = 3; i >= 0; --i) {
3129 int Val = SVOp->getMaskElt(i);
3138 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3139 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3140 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3141 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3142 EVT VVT = N->getValueType(0);
3143 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3147 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3148 Val = SVOp->getMaskElt(i);
3152 return (Val - i) * EltSize;
3155 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3157 bool X86::isZeroNode(SDValue Elt) {
3158 return ((isa<ConstantSDNode>(Elt) &&
3159 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3160 (isa<ConstantFPSDNode>(Elt) &&
3161 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3164 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3165 /// their permute mask.
3166 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3167 SelectionDAG &DAG) {
3168 EVT VT = SVOp->getValueType(0);
3169 unsigned NumElems = VT.getVectorNumElements();
3170 SmallVector<int, 8> MaskVec;
3172 for (unsigned i = 0; i != NumElems; ++i) {
3173 int idx = SVOp->getMaskElt(i);
3175 MaskVec.push_back(idx);
3176 else if (idx < (int)NumElems)
3177 MaskVec.push_back(idx + NumElems);
3179 MaskVec.push_back(idx - NumElems);
3181 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3182 SVOp->getOperand(0), &MaskVec[0]);
3185 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3186 /// the two vector operands have swapped position.
3187 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3188 unsigned NumElems = VT.getVectorNumElements();
3189 for (unsigned i = 0; i != NumElems; ++i) {
3193 else if (idx < (int)NumElems)
3194 Mask[i] = idx + NumElems;
3196 Mask[i] = idx - NumElems;
3200 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3201 /// match movhlps. The lower half elements should come from upper half of
3202 /// V1 (and in order), and the upper half elements should come from the upper
3203 /// half of V2 (and in order).
3204 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3205 if (Op->getValueType(0).getVectorNumElements() != 4)
3207 for (unsigned i = 0, e = 2; i != e; ++i)
3208 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3210 for (unsigned i = 2; i != 4; ++i)
3211 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3216 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3217 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3219 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3220 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3222 N = N->getOperand(0).getNode();
3223 if (!ISD::isNON_EXTLoad(N))
3226 *LD = cast<LoadSDNode>(N);
3230 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3231 /// match movlp{s|d}. The lower half elements should come from lower half of
3232 /// V1 (and in order), and the upper half elements should come from the upper
3233 /// half of V2 (and in order). And since V1 will become the source of the
3234 /// MOVLP, it must be either a vector load or a scalar load to vector.
3235 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3236 ShuffleVectorSDNode *Op) {
3237 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3239 // Is V2 is a vector load, don't do this transformation. We will try to use
3240 // load folding shufps op.
3241 if (ISD::isNON_EXTLoad(V2))
3244 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3246 if (NumElems != 2 && NumElems != 4)
3248 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3249 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3251 for (unsigned i = NumElems/2; i != NumElems; ++i)
3252 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3257 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3259 static bool isSplatVector(SDNode *N) {
3260 if (N->getOpcode() != ISD::BUILD_VECTOR)
3263 SDValue SplatValue = N->getOperand(0);
3264 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3265 if (N->getOperand(i) != SplatValue)
3270 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3271 /// to an zero vector.
3272 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3273 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3274 SDValue V1 = N->getOperand(0);
3275 SDValue V2 = N->getOperand(1);
3276 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3277 for (unsigned i = 0; i != NumElems; ++i) {
3278 int Idx = N->getMaskElt(i);
3279 if (Idx >= (int)NumElems) {
3280 unsigned Opc = V2.getOpcode();
3281 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3283 if (Opc != ISD::BUILD_VECTOR ||
3284 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3286 } else if (Idx >= 0) {
3287 unsigned Opc = V1.getOpcode();
3288 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3290 if (Opc != ISD::BUILD_VECTOR ||
3291 !X86::isZeroNode(V1.getOperand(Idx)))
3298 /// getZeroVector - Returns a vector of specified type with all zero elements.
3300 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3302 assert(VT.isVector() && "Expected a vector type");
3304 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3305 // type. This ensures they get CSE'd.
3307 if (VT.getSizeInBits() == 64) { // MMX
3308 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3309 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3310 } else if (HasSSE2) { // SSE2
3311 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3312 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3314 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3315 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3317 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3320 /// getOnesVector - Returns a vector of specified type with all bits set.
3322 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3323 assert(VT.isVector() && "Expected a vector type");
3325 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3326 // type. This ensures they get CSE'd.
3327 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3329 if (VT.getSizeInBits() == 64) // MMX
3330 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3332 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3333 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3337 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3338 /// that point to V2 points to its first element.
3339 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3340 EVT VT = SVOp->getValueType(0);
3341 unsigned NumElems = VT.getVectorNumElements();
3343 bool Changed = false;
3344 SmallVector<int, 8> MaskVec;
3345 SVOp->getMask(MaskVec);
3347 for (unsigned i = 0; i != NumElems; ++i) {
3348 if (MaskVec[i] > (int)NumElems) {
3349 MaskVec[i] = NumElems;
3354 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3355 SVOp->getOperand(1), &MaskVec[0]);
3356 return SDValue(SVOp, 0);
3359 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3360 /// operation of specified width.
3361 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3363 unsigned NumElems = VT.getVectorNumElements();
3364 SmallVector<int, 8> Mask;
3365 Mask.push_back(NumElems);
3366 for (unsigned i = 1; i != NumElems; ++i)
3368 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3371 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3372 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3374 unsigned NumElems = VT.getVectorNumElements();
3375 SmallVector<int, 8> Mask;
3376 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3378 Mask.push_back(i + NumElems);
3380 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3383 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3384 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3386 unsigned NumElems = VT.getVectorNumElements();
3387 unsigned Half = NumElems/2;
3388 SmallVector<int, 8> Mask;
3389 for (unsigned i = 0; i != Half; ++i) {
3390 Mask.push_back(i + Half);
3391 Mask.push_back(i + NumElems + Half);
3393 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3396 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3397 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3399 if (SV->getValueType(0).getVectorNumElements() <= 4)
3400 return SDValue(SV, 0);
3402 EVT PVT = MVT::v4f32;
3403 EVT VT = SV->getValueType(0);
3404 DebugLoc dl = SV->getDebugLoc();
3405 SDValue V1 = SV->getOperand(0);
3406 int NumElems = VT.getVectorNumElements();
3407 int EltNo = SV->getSplatIndex();
3409 // unpack elements to the correct location
3410 while (NumElems > 4) {
3411 if (EltNo < NumElems/2) {
3412 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3414 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3415 EltNo -= NumElems/2;
3420 // Perform the splat.
3421 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3422 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3423 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3424 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3427 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3428 /// vector of zero or undef vector. This produces a shuffle where the low
3429 /// element of V2 is swizzled into the zero/undef vector, landing at element
3430 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3431 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3432 bool isZero, bool HasSSE2,
3433 SelectionDAG &DAG) {
3434 EVT VT = V2.getValueType();
3436 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3437 unsigned NumElems = VT.getVectorNumElements();
3438 SmallVector<int, 16> MaskVec;
3439 for (unsigned i = 0; i != NumElems; ++i)
3440 // If this is the insertion idx, put the low elt of V2 here.
3441 MaskVec.push_back(i == Idx ? NumElems : i);
3442 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3445 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3446 /// a shuffle that is zero.
3448 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3449 bool Low, SelectionDAG &DAG) {
3450 unsigned NumZeros = 0;
3451 for (int i = 0; i < NumElems; ++i) {
3452 unsigned Index = Low ? i : NumElems-i-1;
3453 int Idx = SVOp->getMaskElt(Index);
3458 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3459 if (Elt.getNode() && X86::isZeroNode(Elt))
3467 /// isVectorShift - Returns true if the shuffle can be implemented as a
3468 /// logical left or right shift of a vector.
3469 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3470 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3471 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3472 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3475 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3478 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3482 bool SeenV1 = false;
3483 bool SeenV2 = false;
3484 for (unsigned i = NumZeros; i < NumElems; ++i) {
3485 unsigned Val = isLeft ? (i - NumZeros) : i;
3486 int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3489 unsigned Idx = (unsigned) Idx_;
3499 if (SeenV1 && SeenV2)
3502 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3508 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3510 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3511 unsigned NumNonZero, unsigned NumZero,
3513 const TargetLowering &TLI) {
3517 DebugLoc dl = Op.getDebugLoc();
3520 for (unsigned i = 0; i < 16; ++i) {
3521 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3522 if (ThisIsNonZero && First) {
3524 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3526 V = DAG.getUNDEF(MVT::v8i16);
3531 SDValue ThisElt(0, 0), LastElt(0, 0);
3532 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3533 if (LastIsNonZero) {
3534 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3535 MVT::i16, Op.getOperand(i-1));
3537 if (ThisIsNonZero) {
3538 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3539 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3540 ThisElt, DAG.getConstant(8, MVT::i8));
3542 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3546 if (ThisElt.getNode())
3547 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3548 DAG.getIntPtrConstant(i/2));
3552 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3555 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3557 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3558 unsigned NumNonZero, unsigned NumZero,
3560 const TargetLowering &TLI) {
3564 DebugLoc dl = Op.getDebugLoc();
3567 for (unsigned i = 0; i < 8; ++i) {
3568 bool isNonZero = (NonZeros & (1 << i)) != 0;
3572 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3574 V = DAG.getUNDEF(MVT::v8i16);
3577 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3578 MVT::v8i16, V, Op.getOperand(i),
3579 DAG.getIntPtrConstant(i));
3586 /// getVShift - Return a vector logical shift node.
3588 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3589 unsigned NumBits, SelectionDAG &DAG,
3590 const TargetLowering &TLI, DebugLoc dl) {
3591 bool isMMX = VT.getSizeInBits() == 64;
3592 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3593 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3594 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3595 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3596 DAG.getNode(Opc, dl, ShVT, SrcOp,
3597 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3601 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3602 SelectionDAG &DAG) const {
3604 // Check if the scalar load can be widened into a vector load. And if
3605 // the address is "base + cst" see if the cst can be "absorbed" into
3606 // the shuffle mask.
3607 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3608 SDValue Ptr = LD->getBasePtr();
3609 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3611 EVT PVT = LD->getValueType(0);
3612 if (PVT != MVT::i32 && PVT != MVT::f32)
3617 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3618 FI = FINode->getIndex();
3620 } else if (Ptr.getOpcode() == ISD::ADD &&
3621 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3622 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3623 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3624 Offset = Ptr.getConstantOperandVal(1);
3625 Ptr = Ptr.getOperand(0);
3630 SDValue Chain = LD->getChain();
3631 // Make sure the stack object alignment is at least 16.
3632 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3633 if (DAG.InferPtrAlignment(Ptr) < 16) {
3634 if (MFI->isFixedObjectIndex(FI)) {
3635 // Can't change the alignment. FIXME: It's possible to compute
3636 // the exact stack offset and reference FI + adjust offset instead.
3637 // If someone *really* cares about this. That's the way to implement it.
3640 MFI->setObjectAlignment(FI, 16);
3644 // (Offset % 16) must be multiple of 4. Then address is then
3645 // Ptr + (Offset & ~15).
3648 if ((Offset % 16) & 3)
3650 int64_t StartOffset = Offset & ~15;
3652 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3653 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3655 int EltNo = (Offset - StartOffset) >> 2;
3656 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3657 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3658 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3660 // Canonicalize it to a v4i32 shuffle.
3661 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3662 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3663 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3664 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3670 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3671 /// vector of type 'VT', see if the elements can be replaced by a single large
3672 /// load which has the same value as a build_vector whose operands are 'elts'.
3674 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3676 /// FIXME: we'd also like to handle the case where the last elements are zero
3677 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3678 /// There's even a handy isZeroNode for that purpose.
3679 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3680 DebugLoc &dl, SelectionDAG &DAG) {
3681 EVT EltVT = VT.getVectorElementType();
3682 unsigned NumElems = Elts.size();
3684 LoadSDNode *LDBase = NULL;
3685 unsigned LastLoadedElt = -1U;
3687 // For each element in the initializer, see if we've found a load or an undef.
3688 // If we don't find an initial load element, or later load elements are
3689 // non-consecutive, bail out.
3690 for (unsigned i = 0; i < NumElems; ++i) {
3691 SDValue Elt = Elts[i];
3693 if (!Elt.getNode() ||
3694 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3697 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3699 LDBase = cast<LoadSDNode>(Elt.getNode());
3703 if (Elt.getOpcode() == ISD::UNDEF)
3706 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3707 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3712 // If we have found an entire vector of loads and undefs, then return a large
3713 // load of the entire vector width starting at the base pointer. If we found
3714 // consecutive loads for the low half, generate a vzext_load node.
3715 if (LastLoadedElt == NumElems - 1) {
3716 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3717 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3718 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3719 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3720 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3721 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3722 LDBase->isVolatile(), LDBase->isNonTemporal(),
3723 LDBase->getAlignment());
3724 } else if (NumElems == 4 && LastLoadedElt == 1) {
3725 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3726 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3727 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3728 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3734 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3735 DebugLoc dl = Op.getDebugLoc();
3736 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3737 if (ISD::isBuildVectorAllZeros(Op.getNode())
3738 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3739 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3740 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3741 // eliminated on x86-32 hosts.
3742 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3745 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3746 return getOnesVector(Op.getValueType(), DAG, dl);
3747 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3750 EVT VT = Op.getValueType();
3751 EVT ExtVT = VT.getVectorElementType();
3752 unsigned EVTBits = ExtVT.getSizeInBits();
3754 unsigned NumElems = Op.getNumOperands();
3755 unsigned NumZero = 0;
3756 unsigned NumNonZero = 0;
3757 unsigned NonZeros = 0;
3758 bool IsAllConstants = true;
3759 SmallSet<SDValue, 8> Values;
3760 for (unsigned i = 0; i < NumElems; ++i) {
3761 SDValue Elt = Op.getOperand(i);
3762 if (Elt.getOpcode() == ISD::UNDEF)
3765 if (Elt.getOpcode() != ISD::Constant &&
3766 Elt.getOpcode() != ISD::ConstantFP)
3767 IsAllConstants = false;
3768 if (X86::isZeroNode(Elt))
3771 NonZeros |= (1 << i);
3776 if (NumNonZero == 0) {
3777 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3778 return DAG.getUNDEF(VT);
3781 // Special case for single non-zero, non-undef, element.
3782 if (NumNonZero == 1) {
3783 unsigned Idx = CountTrailingZeros_32(NonZeros);
3784 SDValue Item = Op.getOperand(Idx);
3786 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3787 // the value are obviously zero, truncate the value to i32 and do the
3788 // insertion that way. Only do this if the value is non-constant or if the
3789 // value is a constant being inserted into element 0. It is cheaper to do
3790 // a constant pool load than it is to do a movd + shuffle.
3791 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3792 (!IsAllConstants || Idx == 0)) {
3793 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3794 // Handle MMX and SSE both.
3795 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3796 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3798 // Truncate the value (which may itself be a constant) to i32, and
3799 // convert it to a vector with movd (S2V+shuffle to zero extend).
3800 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3801 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3802 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3803 Subtarget->hasSSE2(), DAG);
3805 // Now we have our 32-bit value zero extended in the low element of
3806 // a vector. If Idx != 0, swizzle it into place.
3808 SmallVector<int, 4> Mask;
3809 Mask.push_back(Idx);
3810 for (unsigned i = 1; i != VecElts; ++i)
3812 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3813 DAG.getUNDEF(Item.getValueType()),
3816 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3820 // If we have a constant or non-constant insertion into the low element of
3821 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3822 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3823 // depending on what the source datatype is.
3826 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3827 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3828 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3829 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3830 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3831 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3833 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3834 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3835 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3836 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3837 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3838 Subtarget->hasSSE2(), DAG);
3839 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3843 // Is it a vector logical left shift?
3844 if (NumElems == 2 && Idx == 1 &&
3845 X86::isZeroNode(Op.getOperand(0)) &&
3846 !X86::isZeroNode(Op.getOperand(1))) {
3847 unsigned NumBits = VT.getSizeInBits();
3848 return getVShift(true, VT,
3849 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3850 VT, Op.getOperand(1)),
3851 NumBits/2, DAG, *this, dl);
3854 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3857 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3858 // is a non-constant being inserted into an element other than the low one,
3859 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3860 // movd/movss) to move this into the low element, then shuffle it into
3862 if (EVTBits == 32) {
3863 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3865 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3866 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3867 Subtarget->hasSSE2(), DAG);
3868 SmallVector<int, 8> MaskVec;
3869 for (unsigned i = 0; i < NumElems; i++)
3870 MaskVec.push_back(i == Idx ? 0 : 1);
3871 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3875 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3876 if (Values.size() == 1) {
3877 if (EVTBits == 32) {
3878 // Instead of a shuffle like this:
3879 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3880 // Check if it's possible to issue this instead.
3881 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3882 unsigned Idx = CountTrailingZeros_32(NonZeros);
3883 SDValue Item = Op.getOperand(Idx);
3884 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3885 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3890 // A vector full of immediates; various special cases are already
3891 // handled, so this is best done with a single constant-pool load.
3895 // Let legalizer expand 2-wide build_vectors.
3896 if (EVTBits == 64) {
3897 if (NumNonZero == 1) {
3898 // One half is zero or undef.
3899 unsigned Idx = CountTrailingZeros_32(NonZeros);
3900 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3901 Op.getOperand(Idx));
3902 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3903 Subtarget->hasSSE2(), DAG);
3908 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3909 if (EVTBits == 8 && NumElems == 16) {
3910 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3912 if (V.getNode()) return V;
3915 if (EVTBits == 16 && NumElems == 8) {
3916 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3918 if (V.getNode()) return V;
3921 // If element VT is == 32 bits, turn it into a number of shuffles.
3922 SmallVector<SDValue, 8> V;
3924 if (NumElems == 4 && NumZero > 0) {
3925 for (unsigned i = 0; i < 4; ++i) {
3926 bool isZero = !(NonZeros & (1 << i));
3928 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3930 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3933 for (unsigned i = 0; i < 2; ++i) {
3934 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3937 V[i] = V[i*2]; // Must be a zero vector.
3940 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3943 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3946 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3951 SmallVector<int, 8> MaskVec;
3952 bool Reverse = (NonZeros & 0x3) == 2;
3953 for (unsigned i = 0; i < 2; ++i)
3954 MaskVec.push_back(Reverse ? 1-i : i);
3955 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3956 for (unsigned i = 0; i < 2; ++i)
3957 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3958 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3961 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3962 // Check for a build vector of consecutive loads.
3963 for (unsigned i = 0; i < NumElems; ++i)
3964 V[i] = Op.getOperand(i);
3966 // Check for elements which are consecutive loads.
3967 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3971 // For SSE 4.1, use inserts into undef.
3972 if (getSubtarget()->hasSSE41()) {
3973 V[0] = DAG.getUNDEF(VT);
3974 for (unsigned i = 0; i < NumElems; ++i)
3975 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3976 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3977 Op.getOperand(i), DAG.getIntPtrConstant(i));
3981 // Otherwise, expand into a number of unpckl*
3983 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3984 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3985 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3986 for (unsigned i = 0; i < NumElems; ++i)
3987 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3989 while (NumElems != 0) {
3990 for (unsigned i = 0; i < NumElems; ++i)
3991 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4000 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4001 // We support concatenate two MMX registers and place them in a MMX
4002 // register. This is better than doing a stack convert.
4003 DebugLoc dl = Op.getDebugLoc();
4004 EVT ResVT = Op.getValueType();
4005 assert(Op.getNumOperands() == 2);
4006 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4007 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4009 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4010 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4011 InVec = Op.getOperand(1);
4012 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4013 unsigned NumElts = ResVT.getVectorNumElements();
4014 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4015 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4016 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4018 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4019 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4020 Mask[0] = 0; Mask[1] = 2;
4021 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4023 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4026 // v8i16 shuffles - Prefer shuffles in the following order:
4027 // 1. [all] pshuflw, pshufhw, optional move
4028 // 2. [ssse3] 1 x pshufb
4029 // 3. [ssse3] 2 x pshufb + 1 x por
4030 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4032 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4034 const X86TargetLowering &TLI) {
4035 SDValue V1 = SVOp->getOperand(0);
4036 SDValue V2 = SVOp->getOperand(1);
4037 DebugLoc dl = SVOp->getDebugLoc();
4038 SmallVector<int, 8> MaskVals;
4040 // Determine if more than 1 of the words in each of the low and high quadwords
4041 // of the result come from the same quadword of one of the two inputs. Undef
4042 // mask values count as coming from any quadword, for better codegen.
4043 SmallVector<unsigned, 4> LoQuad(4);
4044 SmallVector<unsigned, 4> HiQuad(4);
4045 BitVector InputQuads(4);
4046 for (unsigned i = 0; i < 8; ++i) {
4047 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4048 int EltIdx = SVOp->getMaskElt(i);
4049 MaskVals.push_back(EltIdx);
4058 InputQuads.set(EltIdx / 4);
4061 int BestLoQuad = -1;
4062 unsigned MaxQuad = 1;
4063 for (unsigned i = 0; i < 4; ++i) {
4064 if (LoQuad[i] > MaxQuad) {
4066 MaxQuad = LoQuad[i];
4070 int BestHiQuad = -1;
4072 for (unsigned i = 0; i < 4; ++i) {
4073 if (HiQuad[i] > MaxQuad) {
4075 MaxQuad = HiQuad[i];
4079 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4080 // of the two input vectors, shuffle them into one input vector so only a
4081 // single pshufb instruction is necessary. If There are more than 2 input
4082 // quads, disable the next transformation since it does not help SSSE3.
4083 bool V1Used = InputQuads[0] || InputQuads[1];
4084 bool V2Used = InputQuads[2] || InputQuads[3];
4085 if (TLI.getSubtarget()->hasSSSE3()) {
4086 if (InputQuads.count() == 2 && V1Used && V2Used) {
4087 BestLoQuad = InputQuads.find_first();
4088 BestHiQuad = InputQuads.find_next(BestLoQuad);
4090 if (InputQuads.count() > 2) {
4096 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4097 // the shuffle mask. If a quad is scored as -1, that means that it contains
4098 // words from all 4 input quadwords.
4100 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4101 SmallVector<int, 8> MaskV;
4102 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4103 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4104 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4105 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4106 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4107 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4109 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4110 // source words for the shuffle, to aid later transformations.
4111 bool AllWordsInNewV = true;
4112 bool InOrder[2] = { true, true };
4113 for (unsigned i = 0; i != 8; ++i) {
4114 int idx = MaskVals[i];
4116 InOrder[i/4] = false;
4117 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4119 AllWordsInNewV = false;
4123 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4124 if (AllWordsInNewV) {
4125 for (int i = 0; i != 8; ++i) {
4126 int idx = MaskVals[i];
4129 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4130 if ((idx != i) && idx < 4)
4132 if ((idx != i) && idx > 3)
4141 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4142 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4143 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4144 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4145 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4149 // If we have SSSE3, and all words of the result are from 1 input vector,
4150 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4151 // is present, fall back to case 4.
4152 if (TLI.getSubtarget()->hasSSSE3()) {
4153 SmallVector<SDValue,16> pshufbMask;
4155 // If we have elements from both input vectors, set the high bit of the
4156 // shuffle mask element to zero out elements that come from V2 in the V1
4157 // mask, and elements that come from V1 in the V2 mask, so that the two
4158 // results can be OR'd together.
4159 bool TwoInputs = V1Used && V2Used;
4160 for (unsigned i = 0; i != 8; ++i) {
4161 int EltIdx = MaskVals[i] * 2;
4162 if (TwoInputs && (EltIdx >= 16)) {
4163 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4164 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4167 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4168 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4170 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4171 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4172 DAG.getNode(ISD::BUILD_VECTOR, dl,
4173 MVT::v16i8, &pshufbMask[0], 16));
4175 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4177 // Calculate the shuffle mask for the second input, shuffle it, and
4178 // OR it with the first shuffled input.
4180 for (unsigned i = 0; i != 8; ++i) {
4181 int EltIdx = MaskVals[i] * 2;
4183 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4184 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4187 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4188 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4190 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4191 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4192 DAG.getNode(ISD::BUILD_VECTOR, dl,
4193 MVT::v16i8, &pshufbMask[0], 16));
4194 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4195 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4198 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4199 // and update MaskVals with new element order.
4200 BitVector InOrder(8);
4201 if (BestLoQuad >= 0) {
4202 SmallVector<int, 8> MaskV;
4203 for (int i = 0; i != 4; ++i) {
4204 int idx = MaskVals[i];
4206 MaskV.push_back(-1);
4208 } else if ((idx / 4) == BestLoQuad) {
4209 MaskV.push_back(idx & 3);
4212 MaskV.push_back(-1);
4215 for (unsigned i = 4; i != 8; ++i)
4217 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4221 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4222 // and update MaskVals with the new element order.
4223 if (BestHiQuad >= 0) {
4224 SmallVector<int, 8> MaskV;
4225 for (unsigned i = 0; i != 4; ++i)
4227 for (unsigned i = 4; i != 8; ++i) {
4228 int idx = MaskVals[i];
4230 MaskV.push_back(-1);
4232 } else if ((idx / 4) == BestHiQuad) {
4233 MaskV.push_back((idx & 3) + 4);
4236 MaskV.push_back(-1);
4239 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4243 // In case BestHi & BestLo were both -1, which means each quadword has a word
4244 // from each of the four input quadwords, calculate the InOrder bitvector now
4245 // before falling through to the insert/extract cleanup.
4246 if (BestLoQuad == -1 && BestHiQuad == -1) {
4248 for (int i = 0; i != 8; ++i)
4249 if (MaskVals[i] < 0 || MaskVals[i] == i)
4253 // The other elements are put in the right place using pextrw and pinsrw.
4254 for (unsigned i = 0; i != 8; ++i) {
4257 int EltIdx = MaskVals[i];
4260 SDValue ExtOp = (EltIdx < 8)
4261 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4262 DAG.getIntPtrConstant(EltIdx))
4263 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4264 DAG.getIntPtrConstant(EltIdx - 8));
4265 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4266 DAG.getIntPtrConstant(i));
4271 // v16i8 shuffles - Prefer shuffles in the following order:
4272 // 1. [ssse3] 1 x pshufb
4273 // 2. [ssse3] 2 x pshufb + 1 x por
4274 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4276 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4278 const X86TargetLowering &TLI) {
4279 SDValue V1 = SVOp->getOperand(0);
4280 SDValue V2 = SVOp->getOperand(1);
4281 DebugLoc dl = SVOp->getDebugLoc();
4282 SmallVector<int, 16> MaskVals;
4283 SVOp->getMask(MaskVals);
4285 // If we have SSSE3, case 1 is generated when all result bytes come from
4286 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4287 // present, fall back to case 3.
4288 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4291 for (unsigned i = 0; i < 16; ++i) {
4292 int EltIdx = MaskVals[i];
4301 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4302 if (TLI.getSubtarget()->hasSSSE3()) {
4303 SmallVector<SDValue,16> pshufbMask;
4305 // If all result elements are from one input vector, then only translate
4306 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4308 // Otherwise, we have elements from both input vectors, and must zero out
4309 // elements that come from V2 in the first mask, and V1 in the second mask
4310 // so that we can OR them together.
4311 bool TwoInputs = !(V1Only || V2Only);
4312 for (unsigned i = 0; i != 16; ++i) {
4313 int EltIdx = MaskVals[i];
4314 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4315 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4318 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4320 // If all the elements are from V2, assign it to V1 and return after
4321 // building the first pshufb.
4324 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4325 DAG.getNode(ISD::BUILD_VECTOR, dl,
4326 MVT::v16i8, &pshufbMask[0], 16));
4330 // Calculate the shuffle mask for the second input, shuffle it, and
4331 // OR it with the first shuffled input.
4333 for (unsigned i = 0; i != 16; ++i) {
4334 int EltIdx = MaskVals[i];
4336 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4339 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4341 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4342 DAG.getNode(ISD::BUILD_VECTOR, dl,
4343 MVT::v16i8, &pshufbMask[0], 16));
4344 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4347 // No SSSE3 - Calculate in place words and then fix all out of place words
4348 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4349 // the 16 different words that comprise the two doublequadword input vectors.
4350 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4351 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4352 SDValue NewV = V2Only ? V2 : V1;
4353 for (int i = 0; i != 8; ++i) {
4354 int Elt0 = MaskVals[i*2];
4355 int Elt1 = MaskVals[i*2+1];
4357 // This word of the result is all undef, skip it.
4358 if (Elt0 < 0 && Elt1 < 0)
4361 // This word of the result is already in the correct place, skip it.
4362 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4364 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4367 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4368 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4371 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4372 // using a single extract together, load it and store it.
4373 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4374 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4375 DAG.getIntPtrConstant(Elt1 / 2));
4376 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4377 DAG.getIntPtrConstant(i));
4381 // If Elt1 is defined, extract it from the appropriate source. If the
4382 // source byte is not also odd, shift the extracted word left 8 bits
4383 // otherwise clear the bottom 8 bits if we need to do an or.
4385 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4386 DAG.getIntPtrConstant(Elt1 / 2));
4387 if ((Elt1 & 1) == 0)
4388 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4389 DAG.getConstant(8, TLI.getShiftAmountTy()));
4391 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4392 DAG.getConstant(0xFF00, MVT::i16));
4394 // If Elt0 is defined, extract it from the appropriate source. If the
4395 // source byte is not also even, shift the extracted word right 8 bits. If
4396 // Elt1 was also defined, OR the extracted values together before
4397 // inserting them in the result.
4399 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4400 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4401 if ((Elt0 & 1) != 0)
4402 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4403 DAG.getConstant(8, TLI.getShiftAmountTy()));
4405 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4406 DAG.getConstant(0x00FF, MVT::i16));
4407 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4410 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4411 DAG.getIntPtrConstant(i));
4413 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4416 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4417 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4418 /// done when every pair / quad of shuffle mask elements point to elements in
4419 /// the right sequence. e.g.
4420 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4422 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4424 const TargetLowering &TLI, DebugLoc dl) {
4425 EVT VT = SVOp->getValueType(0);
4426 SDValue V1 = SVOp->getOperand(0);
4427 SDValue V2 = SVOp->getOperand(1);
4428 unsigned NumElems = VT.getVectorNumElements();
4429 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4430 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4431 EVT MaskEltVT = MaskVT.getVectorElementType();
4433 switch (VT.getSimpleVT().SimpleTy) {
4434 default: assert(false && "Unexpected!");
4435 case MVT::v4f32: NewVT = MVT::v2f64; break;
4436 case MVT::v4i32: NewVT = MVT::v2i64; break;
4437 case MVT::v8i16: NewVT = MVT::v4i32; break;
4438 case MVT::v16i8: NewVT = MVT::v4i32; break;
4441 if (NewWidth == 2) {
4447 int Scale = NumElems / NewWidth;
4448 SmallVector<int, 8> MaskVec;
4449 for (unsigned i = 0; i < NumElems; i += Scale) {
4451 for (int j = 0; j < Scale; ++j) {
4452 int EltIdx = SVOp->getMaskElt(i+j);
4456 StartIdx = EltIdx - (EltIdx % Scale);
4457 if (EltIdx != StartIdx + j)
4461 MaskVec.push_back(-1);
4463 MaskVec.push_back(StartIdx / Scale);
4466 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4467 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4468 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4471 /// getVZextMovL - Return a zero-extending vector move low node.
4473 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4474 SDValue SrcOp, SelectionDAG &DAG,
4475 const X86Subtarget *Subtarget, DebugLoc dl) {
4476 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4477 LoadSDNode *LD = NULL;
4478 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4479 LD = dyn_cast<LoadSDNode>(SrcOp);
4481 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4483 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4484 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4485 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4486 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4487 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4489 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4490 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4491 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4492 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4500 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4501 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4502 DAG.getNode(ISD::BIT_CONVERT, dl,
4506 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4509 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4510 SDValue V1 = SVOp->getOperand(0);
4511 SDValue V2 = SVOp->getOperand(1);
4512 DebugLoc dl = SVOp->getDebugLoc();
4513 EVT VT = SVOp->getValueType(0);
4515 SmallVector<std::pair<int, int>, 8> Locs;
4517 SmallVector<int, 8> Mask1(4U, -1);
4518 SmallVector<int, 8> PermMask;
4519 SVOp->getMask(PermMask);
4523 for (unsigned i = 0; i != 4; ++i) {
4524 int Idx = PermMask[i];
4526 Locs[i] = std::make_pair(-1, -1);
4528 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4530 Locs[i] = std::make_pair(0, NumLo);
4534 Locs[i] = std::make_pair(1, NumHi);
4536 Mask1[2+NumHi] = Idx;
4542 if (NumLo <= 2 && NumHi <= 2) {
4543 // If no more than two elements come from either vector. This can be
4544 // implemented with two shuffles. First shuffle gather the elements.
4545 // The second shuffle, which takes the first shuffle as both of its
4546 // vector operands, put the elements into the right order.
4547 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4549 SmallVector<int, 8> Mask2(4U, -1);
4551 for (unsigned i = 0; i != 4; ++i) {
4552 if (Locs[i].first == -1)
4555 unsigned Idx = (i < 2) ? 0 : 4;
4556 Idx += Locs[i].first * 2 + Locs[i].second;
4561 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4562 } else if (NumLo == 3 || NumHi == 3) {
4563 // Otherwise, we must have three elements from one vector, call it X, and
4564 // one element from the other, call it Y. First, use a shufps to build an
4565 // intermediate vector with the one element from Y and the element from X
4566 // that will be in the same half in the final destination (the indexes don't
4567 // matter). Then, use a shufps to build the final vector, taking the half
4568 // containing the element from Y from the intermediate, and the other half
4571 // Normalize it so the 3 elements come from V1.
4572 CommuteVectorShuffleMask(PermMask, VT);
4576 // Find the element from V2.
4578 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4579 int Val = PermMask[HiIndex];
4586 Mask1[0] = PermMask[HiIndex];
4588 Mask1[2] = PermMask[HiIndex^1];
4590 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4593 Mask1[0] = PermMask[0];
4594 Mask1[1] = PermMask[1];
4595 Mask1[2] = HiIndex & 1 ? 6 : 4;
4596 Mask1[3] = HiIndex & 1 ? 4 : 6;
4597 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4599 Mask1[0] = HiIndex & 1 ? 2 : 0;
4600 Mask1[1] = HiIndex & 1 ? 0 : 2;
4601 Mask1[2] = PermMask[2];
4602 Mask1[3] = PermMask[3];
4607 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4611 // Break it into (shuffle shuffle_hi, shuffle_lo).
4613 SmallVector<int,8> LoMask(4U, -1);
4614 SmallVector<int,8> HiMask(4U, -1);
4616 SmallVector<int,8> *MaskPtr = &LoMask;
4617 unsigned MaskIdx = 0;
4620 for (unsigned i = 0; i != 4; ++i) {
4627 int Idx = PermMask[i];
4629 Locs[i] = std::make_pair(-1, -1);
4630 } else if (Idx < 4) {
4631 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4632 (*MaskPtr)[LoIdx] = Idx;
4635 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4636 (*MaskPtr)[HiIdx] = Idx;
4641 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4642 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4643 SmallVector<int, 8> MaskOps;
4644 for (unsigned i = 0; i != 4; ++i) {
4645 if (Locs[i].first == -1) {
4646 MaskOps.push_back(-1);
4648 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4649 MaskOps.push_back(Idx);
4652 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4656 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4657 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4658 SDValue V1 = Op.getOperand(0);
4659 SDValue V2 = Op.getOperand(1);
4660 EVT VT = Op.getValueType();
4661 DebugLoc dl = Op.getDebugLoc();
4662 unsigned NumElems = VT.getVectorNumElements();
4663 bool isMMX = VT.getSizeInBits() == 64;
4664 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4665 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4666 bool V1IsSplat = false;
4667 bool V2IsSplat = false;
4669 if (isZeroShuffle(SVOp))
4670 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4672 // Promote splats to v4f32.
4673 if (SVOp->isSplat()) {
4674 if (isMMX || NumElems < 4)
4676 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4679 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4681 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4682 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4683 if (NewOp.getNode())
4684 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4685 LowerVECTOR_SHUFFLE(NewOp, DAG));
4686 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4687 // FIXME: Figure out a cleaner way to do this.
4688 // Try to make use of movq to zero out the top part.
4689 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4690 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4691 if (NewOp.getNode()) {
4692 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4693 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4694 DAG, Subtarget, dl);
4696 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4697 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4698 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4699 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4700 DAG, Subtarget, dl);
4704 if (X86::isPSHUFDMask(SVOp))
4707 // Check if this can be converted into a logical shift.
4708 bool isLeft = false;
4711 bool isShift = getSubtarget()->hasSSE2() &&
4712 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4713 if (isShift && ShVal.hasOneUse()) {
4714 // If the shifted value has multiple uses, it may be cheaper to use
4715 // v_set0 + movlhps or movhlps, etc.
4716 EVT EltVT = VT.getVectorElementType();
4717 ShAmt *= EltVT.getSizeInBits();
4718 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4721 if (X86::isMOVLMask(SVOp)) {
4724 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4725 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4730 // FIXME: fold these into legal mask.
4731 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4732 X86::isMOVSLDUPMask(SVOp) ||
4733 X86::isMOVHLPSMask(SVOp) ||
4734 X86::isMOVLHPSMask(SVOp) ||
4735 X86::isMOVLPMask(SVOp)))
4738 if (ShouldXformToMOVHLPS(SVOp) ||
4739 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4740 return CommuteVectorShuffle(SVOp, DAG);
4743 // No better options. Use a vshl / vsrl.
4744 EVT EltVT = VT.getVectorElementType();
4745 ShAmt *= EltVT.getSizeInBits();
4746 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4749 bool Commuted = false;
4750 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4751 // 1,1,1,1 -> v8i16 though.
4752 V1IsSplat = isSplatVector(V1.getNode());
4753 V2IsSplat = isSplatVector(V2.getNode());
4755 // Canonicalize the splat or undef, if present, to be on the RHS.
4756 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4757 Op = CommuteVectorShuffle(SVOp, DAG);
4758 SVOp = cast<ShuffleVectorSDNode>(Op);
4759 V1 = SVOp->getOperand(0);
4760 V2 = SVOp->getOperand(1);
4761 std::swap(V1IsSplat, V2IsSplat);
4762 std::swap(V1IsUndef, V2IsUndef);
4766 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4767 // Shuffling low element of v1 into undef, just return v1.
4770 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4771 // the instruction selector will not match, so get a canonical MOVL with
4772 // swapped operands to undo the commute.
4773 return getMOVL(DAG, dl, VT, V2, V1);
4776 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4777 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4778 X86::isUNPCKLMask(SVOp) ||
4779 X86::isUNPCKHMask(SVOp))
4783 // Normalize mask so all entries that point to V2 points to its first
4784 // element then try to match unpck{h|l} again. If match, return a
4785 // new vector_shuffle with the corrected mask.
4786 SDValue NewMask = NormalizeMask(SVOp, DAG);
4787 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4788 if (NSVOp != SVOp) {
4789 if (X86::isUNPCKLMask(NSVOp, true)) {
4791 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4798 // Commute is back and try unpck* again.
4799 // FIXME: this seems wrong.
4800 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4801 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4802 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4803 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4804 X86::isUNPCKLMask(NewSVOp) ||
4805 X86::isUNPCKHMask(NewSVOp))
4809 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4811 // Normalize the node to match x86 shuffle ops if needed
4812 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4813 return CommuteVectorShuffle(SVOp, DAG);
4815 // Check for legal shuffle and return?
4816 SmallVector<int, 16> PermMask;
4817 SVOp->getMask(PermMask);
4818 if (isShuffleMaskLegal(PermMask, VT))
4821 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4822 if (VT == MVT::v8i16) {
4823 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4824 if (NewOp.getNode())
4828 if (VT == MVT::v16i8) {
4829 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4830 if (NewOp.getNode())
4834 // Handle all 4 wide cases with a number of shuffles except for MMX.
4835 if (NumElems == 4 && !isMMX)
4836 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4842 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4843 SelectionDAG &DAG) const {
4844 EVT VT = Op.getValueType();
4845 DebugLoc dl = Op.getDebugLoc();
4846 if (VT.getSizeInBits() == 8) {
4847 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4848 Op.getOperand(0), Op.getOperand(1));
4849 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4850 DAG.getValueType(VT));
4851 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4852 } else if (VT.getSizeInBits() == 16) {
4853 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4854 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4856 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4857 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4858 DAG.getNode(ISD::BIT_CONVERT, dl,
4862 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4863 Op.getOperand(0), Op.getOperand(1));
4864 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4865 DAG.getValueType(VT));
4866 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4867 } else if (VT == MVT::f32) {
4868 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4869 // the result back to FR32 register. It's only worth matching if the
4870 // result has a single use which is a store or a bitcast to i32. And in
4871 // the case of a store, it's not worth it if the index is a constant 0,
4872 // because a MOVSSmr can be used instead, which is smaller and faster.
4873 if (!Op.hasOneUse())
4875 SDNode *User = *Op.getNode()->use_begin();
4876 if ((User->getOpcode() != ISD::STORE ||
4877 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4878 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4879 (User->getOpcode() != ISD::BIT_CONVERT ||
4880 User->getValueType(0) != MVT::i32))
4882 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4883 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4886 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4887 } else if (VT == MVT::i32) {
4888 // ExtractPS works with constant index.
4889 if (isa<ConstantSDNode>(Op.getOperand(1)))
4897 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4898 SelectionDAG &DAG) const {
4899 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4902 if (Subtarget->hasSSE41()) {
4903 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4908 EVT VT = Op.getValueType();
4909 DebugLoc dl = Op.getDebugLoc();
4910 // TODO: handle v16i8.
4911 if (VT.getSizeInBits() == 16) {
4912 SDValue Vec = Op.getOperand(0);
4913 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4915 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4916 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4917 DAG.getNode(ISD::BIT_CONVERT, dl,
4920 // Transform it so it match pextrw which produces a 32-bit result.
4921 EVT EltVT = MVT::i32;
4922 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4923 Op.getOperand(0), Op.getOperand(1));
4924 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4925 DAG.getValueType(VT));
4926 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4927 } else if (VT.getSizeInBits() == 32) {
4928 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4932 // SHUFPS the element to the lowest double word, then movss.
4933 int Mask[4] = { Idx, -1, -1, -1 };
4934 EVT VVT = Op.getOperand(0).getValueType();
4935 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4936 DAG.getUNDEF(VVT), Mask);
4937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4938 DAG.getIntPtrConstant(0));
4939 } else if (VT.getSizeInBits() == 64) {
4940 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4941 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4942 // to match extract_elt for f64.
4943 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4947 // UNPCKHPD the element to the lowest double word, then movsd.
4948 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4949 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4950 int Mask[2] = { 1, -1 };
4951 EVT VVT = Op.getOperand(0).getValueType();
4952 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4953 DAG.getUNDEF(VVT), Mask);
4954 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4955 DAG.getIntPtrConstant(0));
4962 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4963 SelectionDAG &DAG) const {
4964 EVT VT = Op.getValueType();
4965 EVT EltVT = VT.getVectorElementType();
4966 DebugLoc dl = Op.getDebugLoc();
4968 SDValue N0 = Op.getOperand(0);
4969 SDValue N1 = Op.getOperand(1);
4970 SDValue N2 = Op.getOperand(2);
4972 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4973 isa<ConstantSDNode>(N2)) {
4975 if (VT == MVT::v8i16)
4976 Opc = X86ISD::PINSRW;
4977 else if (VT == MVT::v4i16)
4978 Opc = X86ISD::MMX_PINSRW;
4979 else if (VT == MVT::v16i8)
4980 Opc = X86ISD::PINSRB;
4982 Opc = X86ISD::PINSRB;
4984 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4986 if (N1.getValueType() != MVT::i32)
4987 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4988 if (N2.getValueType() != MVT::i32)
4989 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4990 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4991 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4992 // Bits [7:6] of the constant are the source select. This will always be
4993 // zero here. The DAG Combiner may combine an extract_elt index into these
4994 // bits. For example (insert (extract, 3), 2) could be matched by putting
4995 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4996 // Bits [5:4] of the constant are the destination select. This is the
4997 // value of the incoming immediate.
4998 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4999 // combine either bitwise AND or insert of float 0.0 to set these bits.
5000 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5001 // Create this as a scalar to vector..
5002 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5003 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5004 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5005 // PINSR* works with constant index.
5012 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5013 EVT VT = Op.getValueType();
5014 EVT EltVT = VT.getVectorElementType();
5016 if (Subtarget->hasSSE41())
5017 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5019 if (EltVT == MVT::i8)
5022 DebugLoc dl = Op.getDebugLoc();
5023 SDValue N0 = Op.getOperand(0);
5024 SDValue N1 = Op.getOperand(1);
5025 SDValue N2 = Op.getOperand(2);
5027 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5028 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5029 // as its second argument.
5030 if (N1.getValueType() != MVT::i32)
5031 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5032 if (N2.getValueType() != MVT::i32)
5033 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5034 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5035 dl, VT, N0, N1, N2);
5041 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5042 DebugLoc dl = Op.getDebugLoc();
5043 if (Op.getValueType() == MVT::v2f32)
5044 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5045 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5046 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5047 Op.getOperand(0))));
5049 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5050 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5052 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5053 EVT VT = MVT::v2i32;
5054 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5061 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5062 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5065 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5066 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5067 // one of the above mentioned nodes. It has to be wrapped because otherwise
5068 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5069 // be used to form addressing mode. These wrapped nodes will be selected
5072 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5073 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5075 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5077 unsigned char OpFlag = 0;
5078 unsigned WrapperKind = X86ISD::Wrapper;
5079 CodeModel::Model M = getTargetMachine().getCodeModel();
5081 if (Subtarget->isPICStyleRIPRel() &&
5082 (M == CodeModel::Small || M == CodeModel::Kernel))
5083 WrapperKind = X86ISD::WrapperRIP;
5084 else if (Subtarget->isPICStyleGOT())
5085 OpFlag = X86II::MO_GOTOFF;
5086 else if (Subtarget->isPICStyleStubPIC())
5087 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5089 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5091 CP->getOffset(), OpFlag);
5092 DebugLoc DL = CP->getDebugLoc();
5093 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5094 // With PIC, the address is actually $g + Offset.
5096 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5097 DAG.getNode(X86ISD::GlobalBaseReg,
5098 DebugLoc(), getPointerTy()),
5105 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5106 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5108 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5110 unsigned char OpFlag = 0;
5111 unsigned WrapperKind = X86ISD::Wrapper;
5112 CodeModel::Model M = getTargetMachine().getCodeModel();
5114 if (Subtarget->isPICStyleRIPRel() &&
5115 (M == CodeModel::Small || M == CodeModel::Kernel))
5116 WrapperKind = X86ISD::WrapperRIP;
5117 else if (Subtarget->isPICStyleGOT())
5118 OpFlag = X86II::MO_GOTOFF;
5119 else if (Subtarget->isPICStyleStubPIC())
5120 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5122 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5124 DebugLoc DL = JT->getDebugLoc();
5125 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5127 // With PIC, the address is actually $g + Offset.
5129 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5130 DAG.getNode(X86ISD::GlobalBaseReg,
5131 DebugLoc(), getPointerTy()),
5139 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5140 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5142 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5144 unsigned char OpFlag = 0;
5145 unsigned WrapperKind = X86ISD::Wrapper;
5146 CodeModel::Model M = getTargetMachine().getCodeModel();
5148 if (Subtarget->isPICStyleRIPRel() &&
5149 (M == CodeModel::Small || M == CodeModel::Kernel))
5150 WrapperKind = X86ISD::WrapperRIP;
5151 else if (Subtarget->isPICStyleGOT())
5152 OpFlag = X86II::MO_GOTOFF;
5153 else if (Subtarget->isPICStyleStubPIC())
5154 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5156 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5158 DebugLoc DL = Op.getDebugLoc();
5159 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5162 // With PIC, the address is actually $g + Offset.
5163 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5164 !Subtarget->is64Bit()) {
5165 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5166 DAG.getNode(X86ISD::GlobalBaseReg,
5167 DebugLoc(), getPointerTy()),
5175 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5176 // Create the TargetBlockAddressAddress node.
5177 unsigned char OpFlags =
5178 Subtarget->ClassifyBlockAddressReference();
5179 CodeModel::Model M = getTargetMachine().getCodeModel();
5180 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5181 DebugLoc dl = Op.getDebugLoc();
5182 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5183 /*isTarget=*/true, OpFlags);
5185 if (Subtarget->isPICStyleRIPRel() &&
5186 (M == CodeModel::Small || M == CodeModel::Kernel))
5187 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5189 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5191 // With PIC, the address is actually $g + Offset.
5192 if (isGlobalRelativeToPICBase(OpFlags)) {
5193 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5194 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5202 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5204 SelectionDAG &DAG) const {
5205 // Create the TargetGlobalAddress node, folding in the constant
5206 // offset if it is legal.
5207 unsigned char OpFlags =
5208 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5209 CodeModel::Model M = getTargetMachine().getCodeModel();
5211 if (OpFlags == X86II::MO_NO_FLAG &&
5212 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5213 // A direct static reference to a global.
5214 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5217 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5220 if (Subtarget->isPICStyleRIPRel() &&
5221 (M == CodeModel::Small || M == CodeModel::Kernel))
5222 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5224 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5226 // With PIC, the address is actually $g + Offset.
5227 if (isGlobalRelativeToPICBase(OpFlags)) {
5228 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5229 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5233 // For globals that require a load from a stub to get the address, emit the
5235 if (isGlobalStubReference(OpFlags))
5236 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5237 PseudoSourceValue::getGOT(), 0, false, false, 0);
5239 // If there was a non-zero offset that we didn't fold, create an explicit
5242 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5243 DAG.getConstant(Offset, getPointerTy()));
5249 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5250 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5251 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5252 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5256 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5257 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5258 unsigned char OperandFlags) {
5259 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5260 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5261 DebugLoc dl = GA->getDebugLoc();
5262 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5263 GA->getValueType(0),
5267 SDValue Ops[] = { Chain, TGA, *InFlag };
5268 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5270 SDValue Ops[] = { Chain, TGA };
5271 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5274 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5275 MFI->setHasCalls(true);
5277 SDValue Flag = Chain.getValue(1);
5278 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5281 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5283 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5286 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5287 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5288 DAG.getNode(X86ISD::GlobalBaseReg,
5289 DebugLoc(), PtrVT), InFlag);
5290 InFlag = Chain.getValue(1);
5292 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5295 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5297 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5299 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5300 X86::RAX, X86II::MO_TLSGD);
5303 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5304 // "local exec" model.
5305 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5306 const EVT PtrVT, TLSModel::Model model,
5308 DebugLoc dl = GA->getDebugLoc();
5309 // Get the Thread Pointer
5310 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5312 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5315 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5316 NULL, 0, false, false, 0);
5318 unsigned char OperandFlags = 0;
5319 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5321 unsigned WrapperKind = X86ISD::Wrapper;
5322 if (model == TLSModel::LocalExec) {
5323 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5324 } else if (is64Bit) {
5325 assert(model == TLSModel::InitialExec);
5326 OperandFlags = X86II::MO_GOTTPOFF;
5327 WrapperKind = X86ISD::WrapperRIP;
5329 assert(model == TLSModel::InitialExec);
5330 OperandFlags = X86II::MO_INDNTPOFF;
5333 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5335 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5336 GA->getOffset(), OperandFlags);
5337 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5339 if (model == TLSModel::InitialExec)
5340 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5341 PseudoSourceValue::getGOT(), 0, false, false, 0);
5343 // The address of the thread local variable is the add of the thread
5344 // pointer with the offset of the variable.
5345 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5349 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5350 // TODO: implement the "local dynamic" model
5351 // TODO: implement the "initial exec"model for pic executables
5352 assert(Subtarget->isTargetELF() &&
5353 "TLS not implemented for non-ELF targets");
5354 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5355 const GlobalValue *GV = GA->getGlobal();
5357 // If GV is an alias then use the aliasee for determining
5358 // thread-localness.
5359 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5360 GV = GA->resolveAliasedGlobal(false);
5362 TLSModel::Model model = getTLSModel(GV,
5363 getTargetMachine().getRelocationModel());
5366 case TLSModel::GeneralDynamic:
5367 case TLSModel::LocalDynamic: // not implemented
5368 if (Subtarget->is64Bit())
5369 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5370 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5372 case TLSModel::InitialExec:
5373 case TLSModel::LocalExec:
5374 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5375 Subtarget->is64Bit());
5378 llvm_unreachable("Unreachable");
5383 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5384 /// take a 2 x i32 value to shift plus a shift amount.
5385 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5386 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5387 EVT VT = Op.getValueType();
5388 unsigned VTBits = VT.getSizeInBits();
5389 DebugLoc dl = Op.getDebugLoc();
5390 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5391 SDValue ShOpLo = Op.getOperand(0);
5392 SDValue ShOpHi = Op.getOperand(1);
5393 SDValue ShAmt = Op.getOperand(2);
5394 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5395 DAG.getConstant(VTBits - 1, MVT::i8))
5396 : DAG.getConstant(0, VT);
5399 if (Op.getOpcode() == ISD::SHL_PARTS) {
5400 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5401 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5403 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5404 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5407 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5408 DAG.getConstant(VTBits, MVT::i8));
5409 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5410 AndNode, DAG.getConstant(0, MVT::i8));
5413 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5414 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5415 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5417 if (Op.getOpcode() == ISD::SHL_PARTS) {
5418 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5419 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5421 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5422 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5425 SDValue Ops[2] = { Lo, Hi };
5426 return DAG.getMergeValues(Ops, 2, dl);
5429 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5430 SelectionDAG &DAG) const {
5431 EVT SrcVT = Op.getOperand(0).getValueType();
5433 if (SrcVT.isVector()) {
5434 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5440 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5441 "Unknown SINT_TO_FP to lower!");
5443 // These are really Legal; return the operand so the caller accepts it as
5445 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5447 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5448 Subtarget->is64Bit()) {
5452 DebugLoc dl = Op.getDebugLoc();
5453 unsigned Size = SrcVT.getSizeInBits()/8;
5454 MachineFunction &MF = DAG.getMachineFunction();
5455 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5456 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5457 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5459 PseudoSourceValue::getFixedStack(SSFI), 0,
5461 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5464 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5466 SelectionDAG &DAG) const {
5468 DebugLoc dl = Op.getDebugLoc();
5470 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5472 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5474 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5475 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5476 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5477 Tys, Ops, array_lengthof(Ops));
5480 Chain = Result.getValue(1);
5481 SDValue InFlag = Result.getValue(2);
5483 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5484 // shouldn't be necessary except that RFP cannot be live across
5485 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5486 MachineFunction &MF = DAG.getMachineFunction();
5487 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5488 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5489 Tys = DAG.getVTList(MVT::Other);
5491 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5493 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5494 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5495 PseudoSourceValue::getFixedStack(SSFI), 0,
5502 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5503 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5504 SelectionDAG &DAG) const {
5505 // This algorithm is not obvious. Here it is in C code, more or less:
5507 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5508 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5509 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5511 // Copy ints to xmm registers.
5512 __m128i xh = _mm_cvtsi32_si128( hi );
5513 __m128i xl = _mm_cvtsi32_si128( lo );
5515 // Combine into low half of a single xmm register.
5516 __m128i x = _mm_unpacklo_epi32( xh, xl );
5520 // Merge in appropriate exponents to give the integer bits the right
5522 x = _mm_unpacklo_epi32( x, exp );
5524 // Subtract away the biases to deal with the IEEE-754 double precision
5526 d = _mm_sub_pd( (__m128d) x, bias );
5528 // All conversions up to here are exact. The correctly rounded result is
5529 // calculated using the current rounding mode using the following
5531 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5532 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5533 // store doesn't really need to be here (except
5534 // maybe to zero the other double)
5539 DebugLoc dl = Op.getDebugLoc();
5540 LLVMContext *Context = DAG.getContext();
5542 // Build some magic constants.
5543 std::vector<Constant*> CV0;
5544 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5545 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5546 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5547 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5548 Constant *C0 = ConstantVector::get(CV0);
5549 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5551 std::vector<Constant*> CV1;
5553 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5555 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5556 Constant *C1 = ConstantVector::get(CV1);
5557 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5559 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5560 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5562 DAG.getIntPtrConstant(1)));
5563 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5564 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5566 DAG.getIntPtrConstant(0)));
5567 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5568 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5569 PseudoSourceValue::getConstantPool(), 0,
5571 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5572 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5573 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5574 PseudoSourceValue::getConstantPool(), 0,
5576 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5578 // Add the halves; easiest way is to swap them into another reg first.
5579 int ShufMask[2] = { 1, -1 };
5580 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5581 DAG.getUNDEF(MVT::v2f64), ShufMask);
5582 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5583 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5584 DAG.getIntPtrConstant(0));
5587 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5588 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5589 SelectionDAG &DAG) const {
5590 DebugLoc dl = Op.getDebugLoc();
5591 // FP constant to bias correct the final result.
5592 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5595 // Load the 32-bit value into an XMM register.
5596 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5597 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5599 DAG.getIntPtrConstant(0)));
5601 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5602 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5603 DAG.getIntPtrConstant(0));
5605 // Or the load with the bias.
5606 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5607 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5608 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5610 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5611 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5612 MVT::v2f64, Bias)));
5613 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5614 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5615 DAG.getIntPtrConstant(0));
5617 // Subtract the bias.
5618 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5620 // Handle final rounding.
5621 EVT DestVT = Op.getValueType();
5623 if (DestVT.bitsLT(MVT::f64)) {
5624 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5625 DAG.getIntPtrConstant(0));
5626 } else if (DestVT.bitsGT(MVT::f64)) {
5627 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5630 // Handle final rounding.
5634 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5635 SelectionDAG &DAG) const {
5636 SDValue N0 = Op.getOperand(0);
5637 DebugLoc dl = Op.getDebugLoc();
5639 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5640 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5641 // the optimization here.
5642 if (DAG.SignBitIsZero(N0))
5643 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5645 EVT SrcVT = N0.getValueType();
5646 if (SrcVT == MVT::i64) {
5647 // We only handle SSE2 f64 target here; caller can expand the rest.
5648 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5651 return LowerUINT_TO_FP_i64(Op, DAG);
5652 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5653 return LowerUINT_TO_FP_i32(Op, DAG);
5656 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5658 // Make a 64-bit buffer, and use it to build an FILD.
5659 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
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 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5670 std::pair<SDValue,SDValue> X86TargetLowering::
5671 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5672 DebugLoc dl = Op.getDebugLoc();
5674 EVT DstTy = Op.getValueType();
5677 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5681 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5682 DstTy.getSimpleVT() >= MVT::i16 &&
5683 "Unknown FP_TO_SINT to lower!");
5685 // These are really Legal.
5686 if (DstTy == MVT::i32 &&
5687 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5688 return std::make_pair(SDValue(), SDValue());
5689 if (Subtarget->is64Bit() &&
5690 DstTy == MVT::i64 &&
5691 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5692 return std::make_pair(SDValue(), SDValue());
5694 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5696 MachineFunction &MF = DAG.getMachineFunction();
5697 unsigned MemSize = DstTy.getSizeInBits()/8;
5698 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5699 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5702 switch (DstTy.getSimpleVT().SimpleTy) {
5703 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5704 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5705 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5706 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5709 SDValue Chain = DAG.getEntryNode();
5710 SDValue Value = Op.getOperand(0);
5711 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5712 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5713 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5714 PseudoSourceValue::getFixedStack(SSFI), 0,
5716 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5718 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5720 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5721 Chain = Value.getValue(1);
5722 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5723 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5726 // Build the FP_TO_INT*_IN_MEM
5727 SDValue Ops[] = { Chain, Value, StackSlot };
5728 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5730 return std::make_pair(FIST, StackSlot);
5733 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5734 SelectionDAG &DAG) const {
5735 if (Op.getValueType().isVector()) {
5736 if (Op.getValueType() == MVT::v2i32 &&
5737 Op.getOperand(0).getValueType() == MVT::v2f64) {
5743 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5744 SDValue FIST = Vals.first, StackSlot = Vals.second;
5745 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5746 if (FIST.getNode() == 0) return Op;
5749 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5750 FIST, StackSlot, NULL, 0, false, false, 0);
5753 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5754 SelectionDAG &DAG) const {
5755 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5756 SDValue FIST = Vals.first, StackSlot = Vals.second;
5757 assert(FIST.getNode() && "Unexpected failure");
5760 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5761 FIST, StackSlot, NULL, 0, false, false, 0);
5764 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5765 SelectionDAG &DAG) const {
5766 LLVMContext *Context = DAG.getContext();
5767 DebugLoc dl = Op.getDebugLoc();
5768 EVT VT = Op.getValueType();
5771 EltVT = VT.getVectorElementType();
5772 std::vector<Constant*> CV;
5773 if (EltVT == MVT::f64) {
5774 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5778 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5784 Constant *C = ConstantVector::get(CV);
5785 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5786 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5787 PseudoSourceValue::getConstantPool(), 0,
5789 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5792 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5793 LLVMContext *Context = DAG.getContext();
5794 DebugLoc dl = Op.getDebugLoc();
5795 EVT VT = Op.getValueType();
5798 EltVT = VT.getVectorElementType();
5799 std::vector<Constant*> CV;
5800 if (EltVT == MVT::f64) {
5801 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5805 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5811 Constant *C = ConstantVector::get(CV);
5812 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5813 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5814 PseudoSourceValue::getConstantPool(), 0,
5816 if (VT.isVector()) {
5817 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5818 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5819 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5821 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5823 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5827 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5828 LLVMContext *Context = DAG.getContext();
5829 SDValue Op0 = Op.getOperand(0);
5830 SDValue Op1 = Op.getOperand(1);
5831 DebugLoc dl = Op.getDebugLoc();
5832 EVT VT = Op.getValueType();
5833 EVT SrcVT = Op1.getValueType();
5835 // If second operand is smaller, extend it first.
5836 if (SrcVT.bitsLT(VT)) {
5837 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5840 // And if it is bigger, shrink it first.
5841 if (SrcVT.bitsGT(VT)) {
5842 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5846 // At this point the operands and the result should have the same
5847 // type, and that won't be f80 since that is not custom lowered.
5849 // First get the sign bit of second operand.
5850 std::vector<Constant*> CV;
5851 if (SrcVT == MVT::f64) {
5852 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5853 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5855 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5856 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5857 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5858 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5860 Constant *C = ConstantVector::get(CV);
5861 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5862 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5863 PseudoSourceValue::getConstantPool(), 0,
5865 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5867 // Shift sign bit right or left if the two operands have different types.
5868 if (SrcVT.bitsGT(VT)) {
5869 // Op0 is MVT::f32, Op1 is MVT::f64.
5870 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5871 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5872 DAG.getConstant(32, MVT::i32));
5873 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5874 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5875 DAG.getIntPtrConstant(0));
5878 // Clear first operand sign bit.
5880 if (VT == MVT::f64) {
5881 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5882 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5884 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5885 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5886 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5887 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5889 C = ConstantVector::get(CV);
5890 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5891 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5892 PseudoSourceValue::getConstantPool(), 0,
5894 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5896 // Or the value with the sign bit.
5897 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5900 /// Emit nodes that will be selected as "test Op0,Op0", or something
5902 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5903 SelectionDAG &DAG) const {
5904 DebugLoc dl = Op.getDebugLoc();
5906 // CF and OF aren't always set the way we want. Determine which
5907 // of these we need.
5908 bool NeedCF = false;
5909 bool NeedOF = false;
5911 case X86::COND_A: case X86::COND_AE:
5912 case X86::COND_B: case X86::COND_BE:
5915 case X86::COND_G: case X86::COND_GE:
5916 case X86::COND_L: case X86::COND_LE:
5917 case X86::COND_O: case X86::COND_NO:
5923 // See if we can use the EFLAGS value from the operand instead of
5924 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5925 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5926 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5927 unsigned Opcode = 0;
5928 unsigned NumOperands = 0;
5929 switch (Op.getNode()->getOpcode()) {
5931 // Due to an isel shortcoming, be conservative if this add is
5932 // likely to be selected as part of a load-modify-store
5933 // instruction. When the root node in a match is a store, isel
5934 // doesn't know how to remap non-chain non-flag uses of other
5935 // nodes in the match, such as the ADD in this case. This leads
5936 // to the ADD being left around and reselected, with the result
5937 // being two adds in the output. Alas, even if none our users
5938 // are stores, that doesn't prove we're O.K. Ergo, if we have
5939 // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5940 // A better fix seems to require climbing the DAG back to the
5941 // root, and it doesn't seem to be worth the effort.
5942 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5943 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5944 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5946 if (ConstantSDNode *C =
5947 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5948 // An add of one will be selected as an INC.
5949 if (C->getAPIntValue() == 1) {
5950 Opcode = X86ISD::INC;
5954 // An add of negative one (subtract of one) will be selected as a DEC.
5955 if (C->getAPIntValue().isAllOnesValue()) {
5956 Opcode = X86ISD::DEC;
5961 // Otherwise use a regular EFLAGS-setting add.
5962 Opcode = X86ISD::ADD;
5966 // If the primary and result isn't used, don't bother using X86ISD::AND,
5967 // because a TEST instruction will be better.
5968 bool NonFlagUse = false;
5969 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5970 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5972 unsigned UOpNo = UI.getOperandNo();
5973 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5974 // Look pass truncate.
5975 UOpNo = User->use_begin().getOperandNo();
5976 User = *User->use_begin();
5978 if (User->getOpcode() != ISD::BRCOND &&
5979 User->getOpcode() != ISD::SETCC &&
5980 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5992 // Due to the ISEL shortcoming noted above, be conservative if this op is
5993 // likely to be selected as part of a load-modify-store instruction.
5994 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5995 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5996 if (UI->getOpcode() == ISD::STORE)
5998 // Otherwise use a regular EFLAGS-setting instruction.
5999 switch (Op.getNode()->getOpcode()) {
6000 case ISD::SUB: Opcode = X86ISD::SUB; break;
6001 case ISD::OR: Opcode = X86ISD::OR; break;
6002 case ISD::XOR: Opcode = X86ISD::XOR; break;
6003 case ISD::AND: Opcode = X86ISD::AND; break;
6004 default: llvm_unreachable("unexpected operator!");
6015 return SDValue(Op.getNode(), 1);
6021 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6022 SmallVector<SDValue, 4> Ops;
6023 for (unsigned i = 0; i != NumOperands; ++i)
6024 Ops.push_back(Op.getOperand(i));
6025 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6026 DAG.ReplaceAllUsesWith(Op, New);
6027 return SDValue(New.getNode(), 1);
6031 // Otherwise just emit a CMP with 0, which is the TEST pattern.
6032 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6033 DAG.getConstant(0, Op.getValueType()));
6036 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6038 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6039 SelectionDAG &DAG) const {
6040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6041 if (C->getAPIntValue() == 0)
6042 return EmitTest(Op0, X86CC, DAG);
6044 DebugLoc dl = Op0.getDebugLoc();
6045 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6048 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6049 /// if it's possible.
6050 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6051 DebugLoc dl, SelectionDAG &DAG) const {
6052 SDValue Op0 = And.getOperand(0);
6053 SDValue Op1 = And.getOperand(1);
6054 if (Op0.getOpcode() == ISD::TRUNCATE)
6055 Op0 = Op0.getOperand(0);
6056 if (Op1.getOpcode() == ISD::TRUNCATE)
6057 Op1 = Op1.getOperand(0);
6060 if (Op1.getOpcode() == ISD::SHL) {
6061 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6062 if (And10C->getZExtValue() == 1) {
6064 RHS = Op1.getOperand(1);
6066 } else if (Op0.getOpcode() == ISD::SHL) {
6067 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6068 if (And00C->getZExtValue() == 1) {
6070 RHS = Op0.getOperand(1);
6072 } else if (Op1.getOpcode() == ISD::Constant) {
6073 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6074 SDValue AndLHS = Op0;
6075 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6076 LHS = AndLHS.getOperand(0);
6077 RHS = AndLHS.getOperand(1);
6081 if (LHS.getNode()) {
6082 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6083 // instruction. Since the shift amount is in-range-or-undefined, we know
6084 // that doing a bittest on the i32 value is ok. We extend to i32 because
6085 // the encoding for the i16 version is larger than the i32 version.
6086 // Also promote i16 to i32 for performance / code size reason.
6087 if (LHS.getValueType() == MVT::i8 ||
6088 LHS.getValueType() == MVT::i16)
6089 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6091 // If the operand types disagree, extend the shift amount to match. Since
6092 // BT ignores high bits (like shifts) we can use anyextend.
6093 if (LHS.getValueType() != RHS.getValueType())
6094 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6096 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6097 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6098 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6099 DAG.getConstant(Cond, MVT::i8), BT);
6105 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6106 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6107 SDValue Op0 = Op.getOperand(0);
6108 SDValue Op1 = Op.getOperand(1);
6109 DebugLoc dl = Op.getDebugLoc();
6110 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6112 // Optimize to BT if possible.
6113 // Lower (X & (1 << N)) == 0 to BT(X, N).
6114 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6115 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6116 if (Op0.getOpcode() == ISD::AND &&
6118 Op1.getOpcode() == ISD::Constant &&
6119 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6120 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6121 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6122 if (NewSetCC.getNode())
6126 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6127 if (Op0.getOpcode() == X86ISD::SETCC &&
6128 Op1.getOpcode() == ISD::Constant &&
6129 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6130 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6131 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6132 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6133 bool Invert = (CC == ISD::SETNE) ^
6134 cast<ConstantSDNode>(Op1)->isNullValue();
6136 CCode = X86::GetOppositeBranchCondition(CCode);
6137 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6138 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6141 bool isFP = Op1.getValueType().isFloatingPoint();
6142 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6143 if (X86CC == X86::COND_INVALID)
6146 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6148 // Use sbb x, x to materialize carry bit into a GPR.
6149 if (X86CC == X86::COND_B)
6150 return DAG.getNode(ISD::AND, dl, MVT::i8,
6151 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6152 DAG.getConstant(X86CC, MVT::i8), Cond),
6153 DAG.getConstant(1, MVT::i8));
6155 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6156 DAG.getConstant(X86CC, MVT::i8), Cond);
6159 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6161 SDValue Op0 = Op.getOperand(0);
6162 SDValue Op1 = Op.getOperand(1);
6163 SDValue CC = Op.getOperand(2);
6164 EVT VT = Op.getValueType();
6165 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6166 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6167 DebugLoc dl = Op.getDebugLoc();
6171 EVT VT0 = Op0.getValueType();
6172 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6173 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6176 switch (SetCCOpcode) {
6179 case ISD::SETEQ: SSECC = 0; break;
6181 case ISD::SETGT: Swap = true; // Fallthrough
6183 case ISD::SETOLT: SSECC = 1; break;
6185 case ISD::SETGE: Swap = true; // Fallthrough
6187 case ISD::SETOLE: SSECC = 2; break;
6188 case ISD::SETUO: SSECC = 3; break;
6190 case ISD::SETNE: SSECC = 4; break;
6191 case ISD::SETULE: Swap = true;
6192 case ISD::SETUGE: SSECC = 5; break;
6193 case ISD::SETULT: Swap = true;
6194 case ISD::SETUGT: SSECC = 6; break;
6195 case ISD::SETO: SSECC = 7; break;
6198 std::swap(Op0, Op1);
6200 // In the two special cases we can't handle, emit two comparisons.
6202 if (SetCCOpcode == ISD::SETUEQ) {
6204 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6205 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6206 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6208 else if (SetCCOpcode == ISD::SETONE) {
6210 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6211 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6212 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6214 llvm_unreachable("Illegal FP comparison");
6216 // Handle all other FP comparisons here.
6217 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6220 // We are handling one of the integer comparisons here. Since SSE only has
6221 // GT and EQ comparisons for integer, swapping operands and multiple
6222 // operations may be required for some comparisons.
6223 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6224 bool Swap = false, Invert = false, FlipSigns = false;
6226 switch (VT.getSimpleVT().SimpleTy) {
6229 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6231 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6233 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6234 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6237 switch (SetCCOpcode) {
6239 case ISD::SETNE: Invert = true;
6240 case ISD::SETEQ: Opc = EQOpc; break;
6241 case ISD::SETLT: Swap = true;
6242 case ISD::SETGT: Opc = GTOpc; break;
6243 case ISD::SETGE: Swap = true;
6244 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6245 case ISD::SETULT: Swap = true;
6246 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6247 case ISD::SETUGE: Swap = true;
6248 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6251 std::swap(Op0, Op1);
6253 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6254 // bits of the inputs before performing those operations.
6256 EVT EltVT = VT.getVectorElementType();
6257 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6259 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6260 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6262 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6263 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6266 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6268 // If the logical-not of the result is required, perform that now.
6270 Result = DAG.getNOT(dl, Result, VT);
6275 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6276 static bool isX86LogicalCmp(SDValue Op) {
6277 unsigned Opc = Op.getNode()->getOpcode();
6278 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6280 if (Op.getResNo() == 1 &&
6281 (Opc == X86ISD::ADD ||
6282 Opc == X86ISD::SUB ||
6283 Opc == X86ISD::SMUL ||
6284 Opc == X86ISD::UMUL ||
6285 Opc == X86ISD::INC ||
6286 Opc == X86ISD::DEC ||
6287 Opc == X86ISD::OR ||
6288 Opc == X86ISD::XOR ||
6289 Opc == X86ISD::AND))
6295 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6296 bool addTest = true;
6297 SDValue Cond = Op.getOperand(0);
6298 DebugLoc dl = Op.getDebugLoc();
6301 if (Cond.getOpcode() == ISD::SETCC) {
6302 SDValue NewCond = LowerSETCC(Cond, DAG);
6303 if (NewCond.getNode())
6307 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6308 SDValue Op1 = Op.getOperand(1);
6309 SDValue Op2 = Op.getOperand(2);
6310 if (Cond.getOpcode() == X86ISD::SETCC &&
6311 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6312 SDValue Cmp = Cond.getOperand(1);
6313 if (Cmp.getOpcode() == X86ISD::CMP) {
6314 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6315 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6316 ConstantSDNode *RHSC =
6317 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6318 if (N1C && N1C->isAllOnesValue() &&
6319 N2C && N2C->isNullValue() &&
6320 RHSC && RHSC->isNullValue()) {
6321 SDValue CmpOp0 = Cmp.getOperand(0);
6322 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6323 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6324 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6325 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6330 // Look pass (and (setcc_carry (cmp ...)), 1).
6331 if (Cond.getOpcode() == ISD::AND &&
6332 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6333 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6334 if (C && C->getAPIntValue() == 1)
6335 Cond = Cond.getOperand(0);
6338 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6339 // setting operand in place of the X86ISD::SETCC.
6340 if (Cond.getOpcode() == X86ISD::SETCC ||
6341 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6342 CC = Cond.getOperand(0);
6344 SDValue Cmp = Cond.getOperand(1);
6345 unsigned Opc = Cmp.getOpcode();
6346 EVT VT = Op.getValueType();
6348 bool IllegalFPCMov = false;
6349 if (VT.isFloatingPoint() && !VT.isVector() &&
6350 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6351 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6353 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6354 Opc == X86ISD::BT) { // FIXME
6361 // Look pass the truncate.
6362 if (Cond.getOpcode() == ISD::TRUNCATE)
6363 Cond = Cond.getOperand(0);
6365 // We know the result of AND is compared against zero. Try to match
6367 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6368 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6369 if (NewSetCC.getNode()) {
6370 CC = NewSetCC.getOperand(0);
6371 Cond = NewSetCC.getOperand(1);
6378 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6379 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6382 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6383 // condition is true.
6384 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6385 SDValue Ops[] = { Op2, Op1, CC, Cond };
6386 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6389 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6390 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6391 // from the AND / OR.
6392 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6393 Opc = Op.getOpcode();
6394 if (Opc != ISD::OR && Opc != ISD::AND)
6396 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6397 Op.getOperand(0).hasOneUse() &&
6398 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6399 Op.getOperand(1).hasOneUse());
6402 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6403 // 1 and that the SETCC node has a single use.
6404 static bool isXor1OfSetCC(SDValue Op) {
6405 if (Op.getOpcode() != ISD::XOR)
6407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6408 if (N1C && N1C->getAPIntValue() == 1) {
6409 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6410 Op.getOperand(0).hasOneUse();
6415 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6416 bool addTest = true;
6417 SDValue Chain = Op.getOperand(0);
6418 SDValue Cond = Op.getOperand(1);
6419 SDValue Dest = Op.getOperand(2);
6420 DebugLoc dl = Op.getDebugLoc();
6423 if (Cond.getOpcode() == ISD::SETCC) {
6424 SDValue NewCond = LowerSETCC(Cond, DAG);
6425 if (NewCond.getNode())
6429 // FIXME: LowerXALUO doesn't handle these!!
6430 else if (Cond.getOpcode() == X86ISD::ADD ||
6431 Cond.getOpcode() == X86ISD::SUB ||
6432 Cond.getOpcode() == X86ISD::SMUL ||
6433 Cond.getOpcode() == X86ISD::UMUL)
6434 Cond = LowerXALUO(Cond, DAG);
6437 // Look pass (and (setcc_carry (cmp ...)), 1).
6438 if (Cond.getOpcode() == ISD::AND &&
6439 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6440 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6441 if (C && C->getAPIntValue() == 1)
6442 Cond = Cond.getOperand(0);
6445 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6446 // setting operand in place of the X86ISD::SETCC.
6447 if (Cond.getOpcode() == X86ISD::SETCC ||
6448 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6449 CC = Cond.getOperand(0);
6451 SDValue Cmp = Cond.getOperand(1);
6452 unsigned Opc = Cmp.getOpcode();
6453 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6454 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6458 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6462 // These can only come from an arithmetic instruction with overflow,
6463 // e.g. SADDO, UADDO.
6464 Cond = Cond.getNode()->getOperand(1);
6471 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6472 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6473 if (CondOpc == ISD::OR) {
6474 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6475 // two branches instead of an explicit OR instruction with a
6477 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6478 isX86LogicalCmp(Cmp)) {
6479 CC = Cond.getOperand(0).getOperand(0);
6480 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6481 Chain, Dest, CC, Cmp);
6482 CC = Cond.getOperand(1).getOperand(0);
6486 } else { // ISD::AND
6487 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6488 // two branches instead of an explicit AND instruction with a
6489 // separate test. However, we only do this if this block doesn't
6490 // have a fall-through edge, because this requires an explicit
6491 // jmp when the condition is false.
6492 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6493 isX86LogicalCmp(Cmp) &&
6494 Op.getNode()->hasOneUse()) {
6495 X86::CondCode CCode =
6496 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6497 CCode = X86::GetOppositeBranchCondition(CCode);
6498 CC = DAG.getConstant(CCode, MVT::i8);
6499 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6500 // Look for an unconditional branch following this conditional branch.
6501 // We need this because we need to reverse the successors in order
6502 // to implement FCMP_OEQ.
6503 if (User.getOpcode() == ISD::BR) {
6504 SDValue FalseBB = User.getOperand(1);
6506 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6507 assert(NewBR == User);
6510 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6511 Chain, Dest, CC, Cmp);
6512 X86::CondCode CCode =
6513 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6514 CCode = X86::GetOppositeBranchCondition(CCode);
6515 CC = DAG.getConstant(CCode, MVT::i8);
6521 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6522 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6523 // It should be transformed during dag combiner except when the condition
6524 // is set by a arithmetics with overflow node.
6525 X86::CondCode CCode =
6526 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6527 CCode = X86::GetOppositeBranchCondition(CCode);
6528 CC = DAG.getConstant(CCode, MVT::i8);
6529 Cond = Cond.getOperand(0).getOperand(1);
6535 // Look pass the truncate.
6536 if (Cond.getOpcode() == ISD::TRUNCATE)
6537 Cond = Cond.getOperand(0);
6539 // We know the result of AND is compared against zero. Try to match
6541 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6542 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6543 if (NewSetCC.getNode()) {
6544 CC = NewSetCC.getOperand(0);
6545 Cond = NewSetCC.getOperand(1);
6552 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6553 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6555 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6556 Chain, Dest, CC, Cond);
6560 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6561 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6562 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6563 // that the guard pages used by the OS virtual memory manager are allocated in
6564 // correct sequence.
6566 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6567 SelectionDAG &DAG) const {
6568 assert(Subtarget->isTargetCygMing() &&
6569 "This should be used only on Cygwin/Mingw targets");
6570 DebugLoc dl = Op.getDebugLoc();
6573 SDValue Chain = Op.getOperand(0);
6574 SDValue Size = Op.getOperand(1);
6575 // FIXME: Ensure alignment here
6579 EVT IntPtr = getPointerTy();
6580 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6582 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6583 Flag = Chain.getValue(1);
6585 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6587 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6588 Flag = Chain.getValue(1);
6590 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6592 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6593 return DAG.getMergeValues(Ops1, 2, dl);
6597 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6599 SDValue Dst, SDValue Src,
6600 SDValue Size, unsigned Align,
6603 uint64_t DstSVOff) const {
6604 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6606 // If not DWORD aligned or size is more than the threshold, call the library.
6607 // The libc version is likely to be faster for these cases. It can use the
6608 // address value and run time information about the CPU.
6609 if ((Align & 3) != 0 ||
6611 ConstantSize->getZExtValue() >
6612 getSubtarget()->getMaxInlineSizeThreshold()) {
6613 SDValue InFlag(0, 0);
6615 // Check to see if there is a specialized entry-point for memory zeroing.
6616 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6618 if (const char *bzeroEntry = V &&
6619 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6620 EVT IntPtr = getPointerTy();
6621 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6622 TargetLowering::ArgListTy Args;
6623 TargetLowering::ArgListEntry Entry;
6625 Entry.Ty = IntPtrTy;
6626 Args.push_back(Entry);
6628 Args.push_back(Entry);
6629 std::pair<SDValue,SDValue> CallResult =
6630 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6631 false, false, false, false,
6632 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6633 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6634 return CallResult.second;
6637 // Otherwise have the target-independent code call memset.
6641 uint64_t SizeVal = ConstantSize->getZExtValue();
6642 SDValue InFlag(0, 0);
6645 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6646 unsigned BytesLeft = 0;
6647 bool TwoRepStos = false;
6650 uint64_t Val = ValC->getZExtValue() & 255;
6652 // If the value is a constant, then we can potentially use larger sets.
6653 switch (Align & 3) {
6654 case 2: // WORD aligned
6657 Val = (Val << 8) | Val;
6659 case 0: // DWORD aligned
6662 Val = (Val << 8) | Val;
6663 Val = (Val << 16) | Val;
6664 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6667 Val = (Val << 32) | Val;
6670 default: // Byte aligned
6673 Count = DAG.getIntPtrConstant(SizeVal);
6677 if (AVT.bitsGT(MVT::i8)) {
6678 unsigned UBytes = AVT.getSizeInBits() / 8;
6679 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6680 BytesLeft = SizeVal % UBytes;
6683 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6685 InFlag = Chain.getValue(1);
6688 Count = DAG.getIntPtrConstant(SizeVal);
6689 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6690 InFlag = Chain.getValue(1);
6693 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6696 InFlag = Chain.getValue(1);
6697 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6700 InFlag = Chain.getValue(1);
6702 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6703 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6704 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6707 InFlag = Chain.getValue(1);
6709 EVT CVT = Count.getValueType();
6710 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6711 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6712 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6715 InFlag = Chain.getValue(1);
6716 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6717 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6718 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6719 } else if (BytesLeft) {
6720 // Handle the last 1 - 7 bytes.
6721 unsigned Offset = SizeVal - BytesLeft;
6722 EVT AddrVT = Dst.getValueType();
6723 EVT SizeVT = Size.getValueType();
6725 Chain = DAG.getMemset(Chain, dl,
6726 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6727 DAG.getConstant(Offset, AddrVT)),
6729 DAG.getConstant(BytesLeft, SizeVT),
6730 Align, isVolatile, DstSV, DstSVOff + Offset);
6733 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6738 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6739 SDValue Chain, SDValue Dst, SDValue Src,
6740 SDValue Size, unsigned Align,
6741 bool isVolatile, bool AlwaysInline,
6745 uint64_t SrcSVOff) const {
6746 // This requires the copy size to be a constant, preferrably
6747 // within a subtarget-specific limit.
6748 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6751 uint64_t SizeVal = ConstantSize->getZExtValue();
6752 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6755 /// If not DWORD aligned, call the library.
6756 if ((Align & 3) != 0)
6761 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6764 unsigned UBytes = AVT.getSizeInBits() / 8;
6765 unsigned CountVal = SizeVal / UBytes;
6766 SDValue Count = DAG.getIntPtrConstant(CountVal);
6767 unsigned BytesLeft = SizeVal % UBytes;
6769 SDValue InFlag(0, 0);
6770 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6773 InFlag = Chain.getValue(1);
6774 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6777 InFlag = Chain.getValue(1);
6778 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6781 InFlag = Chain.getValue(1);
6783 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6784 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6785 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6786 array_lengthof(Ops));
6788 SmallVector<SDValue, 4> Results;
6789 Results.push_back(RepMovs);
6791 // Handle the last 1 - 7 bytes.
6792 unsigned Offset = SizeVal - BytesLeft;
6793 EVT DstVT = Dst.getValueType();
6794 EVT SrcVT = Src.getValueType();
6795 EVT SizeVT = Size.getValueType();
6796 Results.push_back(DAG.getMemcpy(Chain, dl,
6797 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6798 DAG.getConstant(Offset, DstVT)),
6799 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6800 DAG.getConstant(Offset, SrcVT)),
6801 DAG.getConstant(BytesLeft, SizeVT),
6802 Align, isVolatile, AlwaysInline,
6803 DstSV, DstSVOff + Offset,
6804 SrcSV, SrcSVOff + Offset));
6807 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6808 &Results[0], Results.size());
6811 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6812 MachineFunction &MF = DAG.getMachineFunction();
6813 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6815 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6816 DebugLoc dl = Op.getDebugLoc();
6818 if (!Subtarget->is64Bit()) {
6819 // vastart just stores the address of the VarArgsFrameIndex slot into the
6820 // memory location argument.
6821 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6823 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6828 // gp_offset (0 - 6 * 8)
6829 // fp_offset (48 - 48 + 8 * 16)
6830 // overflow_arg_area (point to parameters coming in memory).
6832 SmallVector<SDValue, 8> MemOps;
6833 SDValue FIN = Op.getOperand(1);
6835 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6836 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6838 FIN, SV, 0, false, false, 0);
6839 MemOps.push_back(Store);
6842 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6843 FIN, DAG.getIntPtrConstant(4));
6844 Store = DAG.getStore(Op.getOperand(0), dl,
6845 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6847 FIN, SV, 0, false, false, 0);
6848 MemOps.push_back(Store);
6850 // Store ptr to overflow_arg_area
6851 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6852 FIN, DAG.getIntPtrConstant(4));
6853 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6855 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6857 MemOps.push_back(Store);
6859 // Store ptr to reg_save_area.
6860 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6861 FIN, DAG.getIntPtrConstant(8));
6862 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6864 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6866 MemOps.push_back(Store);
6867 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6868 &MemOps[0], MemOps.size());
6871 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6872 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6873 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6874 SDValue Chain = Op.getOperand(0);
6875 SDValue SrcPtr = Op.getOperand(1);
6876 SDValue SrcSV = Op.getOperand(2);
6878 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6882 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6883 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6884 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6885 SDValue Chain = Op.getOperand(0);
6886 SDValue DstPtr = Op.getOperand(1);
6887 SDValue SrcPtr = Op.getOperand(2);
6888 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6889 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6890 DebugLoc dl = Op.getDebugLoc();
6892 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6893 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6894 false, DstSV, 0, SrcSV, 0);
6898 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6899 DebugLoc dl = Op.getDebugLoc();
6900 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6902 default: return SDValue(); // Don't custom lower most intrinsics.
6903 // Comparison intrinsics.
6904 case Intrinsic::x86_sse_comieq_ss:
6905 case Intrinsic::x86_sse_comilt_ss:
6906 case Intrinsic::x86_sse_comile_ss:
6907 case Intrinsic::x86_sse_comigt_ss:
6908 case Intrinsic::x86_sse_comige_ss:
6909 case Intrinsic::x86_sse_comineq_ss:
6910 case Intrinsic::x86_sse_ucomieq_ss:
6911 case Intrinsic::x86_sse_ucomilt_ss:
6912 case Intrinsic::x86_sse_ucomile_ss:
6913 case Intrinsic::x86_sse_ucomigt_ss:
6914 case Intrinsic::x86_sse_ucomige_ss:
6915 case Intrinsic::x86_sse_ucomineq_ss:
6916 case Intrinsic::x86_sse2_comieq_sd:
6917 case Intrinsic::x86_sse2_comilt_sd:
6918 case Intrinsic::x86_sse2_comile_sd:
6919 case Intrinsic::x86_sse2_comigt_sd:
6920 case Intrinsic::x86_sse2_comige_sd:
6921 case Intrinsic::x86_sse2_comineq_sd:
6922 case Intrinsic::x86_sse2_ucomieq_sd:
6923 case Intrinsic::x86_sse2_ucomilt_sd:
6924 case Intrinsic::x86_sse2_ucomile_sd:
6925 case Intrinsic::x86_sse2_ucomigt_sd:
6926 case Intrinsic::x86_sse2_ucomige_sd:
6927 case Intrinsic::x86_sse2_ucomineq_sd: {
6929 ISD::CondCode CC = ISD::SETCC_INVALID;
6932 case Intrinsic::x86_sse_comieq_ss:
6933 case Intrinsic::x86_sse2_comieq_sd:
6937 case Intrinsic::x86_sse_comilt_ss:
6938 case Intrinsic::x86_sse2_comilt_sd:
6942 case Intrinsic::x86_sse_comile_ss:
6943 case Intrinsic::x86_sse2_comile_sd:
6947 case Intrinsic::x86_sse_comigt_ss:
6948 case Intrinsic::x86_sse2_comigt_sd:
6952 case Intrinsic::x86_sse_comige_ss:
6953 case Intrinsic::x86_sse2_comige_sd:
6957 case Intrinsic::x86_sse_comineq_ss:
6958 case Intrinsic::x86_sse2_comineq_sd:
6962 case Intrinsic::x86_sse_ucomieq_ss:
6963 case Intrinsic::x86_sse2_ucomieq_sd:
6964 Opc = X86ISD::UCOMI;
6967 case Intrinsic::x86_sse_ucomilt_ss:
6968 case Intrinsic::x86_sse2_ucomilt_sd:
6969 Opc = X86ISD::UCOMI;
6972 case Intrinsic::x86_sse_ucomile_ss:
6973 case Intrinsic::x86_sse2_ucomile_sd:
6974 Opc = X86ISD::UCOMI;
6977 case Intrinsic::x86_sse_ucomigt_ss:
6978 case Intrinsic::x86_sse2_ucomigt_sd:
6979 Opc = X86ISD::UCOMI;
6982 case Intrinsic::x86_sse_ucomige_ss:
6983 case Intrinsic::x86_sse2_ucomige_sd:
6984 Opc = X86ISD::UCOMI;
6987 case Intrinsic::x86_sse_ucomineq_ss:
6988 case Intrinsic::x86_sse2_ucomineq_sd:
6989 Opc = X86ISD::UCOMI;
6994 SDValue LHS = Op.getOperand(1);
6995 SDValue RHS = Op.getOperand(2);
6996 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6997 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6998 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6999 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7000 DAG.getConstant(X86CC, MVT::i8), Cond);
7001 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7003 // ptest intrinsics. The intrinsic these come from are designed to return
7004 // an integer value, not just an instruction so lower it to the ptest
7005 // pattern and a setcc for the result.
7006 case Intrinsic::x86_sse41_ptestz:
7007 case Intrinsic::x86_sse41_ptestc:
7008 case Intrinsic::x86_sse41_ptestnzc:{
7011 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7012 case Intrinsic::x86_sse41_ptestz:
7014 X86CC = X86::COND_E;
7016 case Intrinsic::x86_sse41_ptestc:
7018 X86CC = X86::COND_B;
7020 case Intrinsic::x86_sse41_ptestnzc:
7022 X86CC = X86::COND_A;
7026 SDValue LHS = Op.getOperand(1);
7027 SDValue RHS = Op.getOperand(2);
7028 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
7029 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7030 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7031 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7034 // Fix vector shift instructions where the last operand is a non-immediate
7036 case Intrinsic::x86_sse2_pslli_w:
7037 case Intrinsic::x86_sse2_pslli_d:
7038 case Intrinsic::x86_sse2_pslli_q:
7039 case Intrinsic::x86_sse2_psrli_w:
7040 case Intrinsic::x86_sse2_psrli_d:
7041 case Intrinsic::x86_sse2_psrli_q:
7042 case Intrinsic::x86_sse2_psrai_w:
7043 case Intrinsic::x86_sse2_psrai_d:
7044 case Intrinsic::x86_mmx_pslli_w:
7045 case Intrinsic::x86_mmx_pslli_d:
7046 case Intrinsic::x86_mmx_pslli_q:
7047 case Intrinsic::x86_mmx_psrli_w:
7048 case Intrinsic::x86_mmx_psrli_d:
7049 case Intrinsic::x86_mmx_psrli_q:
7050 case Intrinsic::x86_mmx_psrai_w:
7051 case Intrinsic::x86_mmx_psrai_d: {
7052 SDValue ShAmt = Op.getOperand(2);
7053 if (isa<ConstantSDNode>(ShAmt))
7056 unsigned NewIntNo = 0;
7057 EVT ShAmtVT = MVT::v4i32;
7059 case Intrinsic::x86_sse2_pslli_w:
7060 NewIntNo = Intrinsic::x86_sse2_psll_w;
7062 case Intrinsic::x86_sse2_pslli_d:
7063 NewIntNo = Intrinsic::x86_sse2_psll_d;
7065 case Intrinsic::x86_sse2_pslli_q:
7066 NewIntNo = Intrinsic::x86_sse2_psll_q;
7068 case Intrinsic::x86_sse2_psrli_w:
7069 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7071 case Intrinsic::x86_sse2_psrli_d:
7072 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7074 case Intrinsic::x86_sse2_psrli_q:
7075 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7077 case Intrinsic::x86_sse2_psrai_w:
7078 NewIntNo = Intrinsic::x86_sse2_psra_w;
7080 case Intrinsic::x86_sse2_psrai_d:
7081 NewIntNo = Intrinsic::x86_sse2_psra_d;
7084 ShAmtVT = MVT::v2i32;
7086 case Intrinsic::x86_mmx_pslli_w:
7087 NewIntNo = Intrinsic::x86_mmx_psll_w;
7089 case Intrinsic::x86_mmx_pslli_d:
7090 NewIntNo = Intrinsic::x86_mmx_psll_d;
7092 case Intrinsic::x86_mmx_pslli_q:
7093 NewIntNo = Intrinsic::x86_mmx_psll_q;
7095 case Intrinsic::x86_mmx_psrli_w:
7096 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7098 case Intrinsic::x86_mmx_psrli_d:
7099 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7101 case Intrinsic::x86_mmx_psrli_q:
7102 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7104 case Intrinsic::x86_mmx_psrai_w:
7105 NewIntNo = Intrinsic::x86_mmx_psra_w;
7107 case Intrinsic::x86_mmx_psrai_d:
7108 NewIntNo = Intrinsic::x86_mmx_psra_d;
7110 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7116 // The vector shift intrinsics with scalars uses 32b shift amounts but
7117 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7121 ShOps[1] = DAG.getConstant(0, MVT::i32);
7122 if (ShAmtVT == MVT::v4i32) {
7123 ShOps[2] = DAG.getUNDEF(MVT::i32);
7124 ShOps[3] = DAG.getUNDEF(MVT::i32);
7125 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7127 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7130 EVT VT = Op.getValueType();
7131 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7132 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7133 DAG.getConstant(NewIntNo, MVT::i32),
7134 Op.getOperand(1), ShAmt);
7139 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7140 SelectionDAG &DAG) const {
7141 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7142 DebugLoc dl = Op.getDebugLoc();
7145 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7147 DAG.getConstant(TD->getPointerSize(),
7148 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7149 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7150 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7152 NULL, 0, false, false, 0);
7155 // Just load the return address.
7156 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7157 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7158 RetAddrFI, NULL, 0, false, false, 0);
7161 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7162 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7163 MFI->setFrameAddressIsTaken(true);
7164 EVT VT = Op.getValueType();
7165 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7166 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7167 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7168 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7170 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7175 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7176 SelectionDAG &DAG) const {
7177 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7180 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7181 MachineFunction &MF = DAG.getMachineFunction();
7182 SDValue Chain = Op.getOperand(0);
7183 SDValue Offset = Op.getOperand(1);
7184 SDValue Handler = Op.getOperand(2);
7185 DebugLoc dl = Op.getDebugLoc();
7187 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7189 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7191 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7192 DAG.getIntPtrConstant(-TD->getPointerSize()));
7193 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7194 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7195 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7196 MF.getRegInfo().addLiveOut(StoreAddrReg);
7198 return DAG.getNode(X86ISD::EH_RETURN, dl,
7200 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7203 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7204 SelectionDAG &DAG) const {
7205 SDValue Root = Op.getOperand(0);
7206 SDValue Trmp = Op.getOperand(1); // trampoline
7207 SDValue FPtr = Op.getOperand(2); // nested function
7208 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7209 DebugLoc dl = Op.getDebugLoc();
7211 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7213 if (Subtarget->is64Bit()) {
7214 SDValue OutChains[6];
7216 // Large code-model.
7217 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7218 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7220 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7221 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7223 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7225 // Load the pointer to the nested function into R11.
7226 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7227 SDValue Addr = Trmp;
7228 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7229 Addr, TrmpAddr, 0, false, false, 0);
7231 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7232 DAG.getConstant(2, MVT::i64));
7233 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7236 // Load the 'nest' parameter value into R10.
7237 // R10 is specified in X86CallingConv.td
7238 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7239 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7240 DAG.getConstant(10, MVT::i64));
7241 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7242 Addr, TrmpAddr, 10, false, false, 0);
7244 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7245 DAG.getConstant(12, MVT::i64));
7246 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7249 // Jump to the nested function.
7250 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7251 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7252 DAG.getConstant(20, MVT::i64));
7253 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7254 Addr, TrmpAddr, 20, false, false, 0);
7256 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7257 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7258 DAG.getConstant(22, MVT::i64));
7259 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7260 TrmpAddr, 22, false, false, 0);
7263 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7264 return DAG.getMergeValues(Ops, 2, dl);
7266 const Function *Func =
7267 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7268 CallingConv::ID CC = Func->getCallingConv();
7273 llvm_unreachable("Unsupported calling convention");
7274 case CallingConv::C:
7275 case CallingConv::X86_StdCall: {
7276 // Pass 'nest' parameter in ECX.
7277 // Must be kept in sync with X86CallingConv.td
7280 // Check that ECX wasn't needed by an 'inreg' parameter.
7281 const FunctionType *FTy = Func->getFunctionType();
7282 const AttrListPtr &Attrs = Func->getAttributes();
7284 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7285 unsigned InRegCount = 0;
7288 for (FunctionType::param_iterator I = FTy->param_begin(),
7289 E = FTy->param_end(); I != E; ++I, ++Idx)
7290 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7291 // FIXME: should only count parameters that are lowered to integers.
7292 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7294 if (InRegCount > 2) {
7295 report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7300 case CallingConv::X86_FastCall:
7301 case CallingConv::Fast:
7302 // Pass 'nest' parameter in EAX.
7303 // Must be kept in sync with X86CallingConv.td
7308 SDValue OutChains[4];
7311 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7312 DAG.getConstant(10, MVT::i32));
7313 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7315 // This is storing the opcode for MOV32ri.
7316 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7317 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7318 OutChains[0] = DAG.getStore(Root, dl,
7319 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7320 Trmp, TrmpAddr, 0, false, false, 0);
7322 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7323 DAG.getConstant(1, MVT::i32));
7324 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7327 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7328 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7329 DAG.getConstant(5, MVT::i32));
7330 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7331 TrmpAddr, 5, false, false, 1);
7333 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7334 DAG.getConstant(6, MVT::i32));
7335 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7339 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7340 return DAG.getMergeValues(Ops, 2, dl);
7344 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7345 SelectionDAG &DAG) const {
7347 The rounding mode is in bits 11:10 of FPSR, and has the following
7354 FLT_ROUNDS, on the other hand, expects the following:
7361 To perform the conversion, we do:
7362 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7365 MachineFunction &MF = DAG.getMachineFunction();
7366 const TargetMachine &TM = MF.getTarget();
7367 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7368 unsigned StackAlignment = TFI.getStackAlignment();
7369 EVT VT = Op.getValueType();
7370 DebugLoc dl = Op.getDebugLoc();
7372 // Save FP Control Word to stack slot
7373 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7374 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7376 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7377 DAG.getEntryNode(), StackSlot);
7379 // Load FP Control Word from stack slot
7380 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7383 // Transform as necessary
7385 DAG.getNode(ISD::SRL, dl, MVT::i16,
7386 DAG.getNode(ISD::AND, dl, MVT::i16,
7387 CWD, DAG.getConstant(0x800, MVT::i16)),
7388 DAG.getConstant(11, MVT::i8));
7390 DAG.getNode(ISD::SRL, dl, MVT::i16,
7391 DAG.getNode(ISD::AND, dl, MVT::i16,
7392 CWD, DAG.getConstant(0x400, MVT::i16)),
7393 DAG.getConstant(9, MVT::i8));
7396 DAG.getNode(ISD::AND, dl, MVT::i16,
7397 DAG.getNode(ISD::ADD, dl, MVT::i16,
7398 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7399 DAG.getConstant(1, MVT::i16)),
7400 DAG.getConstant(3, MVT::i16));
7403 return DAG.getNode((VT.getSizeInBits() < 16 ?
7404 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7407 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7408 EVT VT = Op.getValueType();
7410 unsigned NumBits = VT.getSizeInBits();
7411 DebugLoc dl = Op.getDebugLoc();
7413 Op = Op.getOperand(0);
7414 if (VT == MVT::i8) {
7415 // Zero extend to i32 since there is not an i8 bsr.
7417 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7420 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7421 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7422 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7424 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7427 DAG.getConstant(NumBits+NumBits-1, OpVT),
7428 DAG.getConstant(X86::COND_E, MVT::i8),
7431 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7433 // Finally xor with NumBits-1.
7434 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7437 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7441 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7442 EVT VT = Op.getValueType();
7444 unsigned NumBits = VT.getSizeInBits();
7445 DebugLoc dl = Op.getDebugLoc();
7447 Op = Op.getOperand(0);
7448 if (VT == MVT::i8) {
7450 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7453 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7454 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7455 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7457 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7460 DAG.getConstant(NumBits, OpVT),
7461 DAG.getConstant(X86::COND_E, MVT::i8),
7464 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7467 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7471 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7472 EVT VT = Op.getValueType();
7473 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7474 DebugLoc dl = Op.getDebugLoc();
7476 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7477 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7478 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7479 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7480 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7482 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7483 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7484 // return AloBlo + AloBhi + AhiBlo;
7486 SDValue A = Op.getOperand(0);
7487 SDValue B = Op.getOperand(1);
7489 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7490 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7491 A, DAG.getConstant(32, MVT::i32));
7492 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7493 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7494 B, DAG.getConstant(32, MVT::i32));
7495 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7496 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7498 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7499 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7501 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7502 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7504 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7505 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7506 AloBhi, DAG.getConstant(32, MVT::i32));
7507 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7508 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7509 AhiBlo, DAG.getConstant(32, MVT::i32));
7510 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7511 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7516 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7517 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7518 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7519 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7520 // has only one use.
7521 SDNode *N = Op.getNode();
7522 SDValue LHS = N->getOperand(0);
7523 SDValue RHS = N->getOperand(1);
7524 unsigned BaseOp = 0;
7526 DebugLoc dl = Op.getDebugLoc();
7528 switch (Op.getOpcode()) {
7529 default: llvm_unreachable("Unknown ovf instruction!");
7531 // A subtract of one will be selected as a INC. Note that INC doesn't
7532 // set CF, so we can't do this for UADDO.
7533 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7534 if (C->getAPIntValue() == 1) {
7535 BaseOp = X86ISD::INC;
7539 BaseOp = X86ISD::ADD;
7543 BaseOp = X86ISD::ADD;
7547 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7548 // set CF, so we can't do this for USUBO.
7549 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7550 if (C->getAPIntValue() == 1) {
7551 BaseOp = X86ISD::DEC;
7555 BaseOp = X86ISD::SUB;
7559 BaseOp = X86ISD::SUB;
7563 BaseOp = X86ISD::SMUL;
7567 BaseOp = X86ISD::UMUL;
7572 // Also sets EFLAGS.
7573 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7574 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7577 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7578 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7580 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7584 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7585 EVT T = Op.getValueType();
7586 DebugLoc dl = Op.getDebugLoc();
7589 switch(T.getSimpleVT().SimpleTy) {
7591 assert(false && "Invalid value type!");
7592 case MVT::i8: Reg = X86::AL; size = 1; break;
7593 case MVT::i16: Reg = X86::AX; size = 2; break;
7594 case MVT::i32: Reg = X86::EAX; size = 4; break;
7596 assert(Subtarget->is64Bit() && "Node not type legal!");
7597 Reg = X86::RAX; size = 8;
7600 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7601 Op.getOperand(2), SDValue());
7602 SDValue Ops[] = { cpIn.getValue(0),
7605 DAG.getTargetConstant(size, MVT::i8),
7607 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7608 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7610 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7614 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7615 SelectionDAG &DAG) const {
7616 assert(Subtarget->is64Bit() && "Result not type legalized?");
7617 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7618 SDValue TheChain = Op.getOperand(0);
7619 DebugLoc dl = Op.getDebugLoc();
7620 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7621 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7622 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7624 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7625 DAG.getConstant(32, MVT::i8));
7627 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7630 return DAG.getMergeValues(Ops, 2, dl);
7633 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7634 SDNode *Node = Op.getNode();
7635 DebugLoc dl = Node->getDebugLoc();
7636 EVT T = Node->getValueType(0);
7637 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7638 DAG.getConstant(0, T), Node->getOperand(2));
7639 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7640 cast<AtomicSDNode>(Node)->getMemoryVT(),
7641 Node->getOperand(0),
7642 Node->getOperand(1), negOp,
7643 cast<AtomicSDNode>(Node)->getSrcValue(),
7644 cast<AtomicSDNode>(Node)->getAlignment());
7647 /// LowerOperation - Provide custom lowering hooks for some operations.
7649 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7650 switch (Op.getOpcode()) {
7651 default: llvm_unreachable("Should not custom lower this!");
7652 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7653 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7654 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7655 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7656 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7657 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7658 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7659 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7660 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7661 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7662 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7663 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7664 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7665 case ISD::SHL_PARTS:
7666 case ISD::SRA_PARTS:
7667 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7668 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7669 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7670 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7671 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7672 case ISD::FABS: return LowerFABS(Op, DAG);
7673 case ISD::FNEG: return LowerFNEG(Op, DAG);
7674 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7675 case ISD::SETCC: return LowerSETCC(Op, DAG);
7676 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7677 case ISD::SELECT: return LowerSELECT(Op, DAG);
7678 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7679 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7680 case ISD::VASTART: return LowerVASTART(Op, DAG);
7681 case ISD::VAARG: return LowerVAARG(Op, DAG);
7682 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7683 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7684 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7685 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7686 case ISD::FRAME_TO_ARGS_OFFSET:
7687 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7688 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7689 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7690 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7691 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7692 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7693 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7694 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7700 case ISD::UMULO: return LowerXALUO(Op, DAG);
7701 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7705 void X86TargetLowering::
7706 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7707 SelectionDAG &DAG, unsigned NewOp) const {
7708 EVT T = Node->getValueType(0);
7709 DebugLoc dl = Node->getDebugLoc();
7710 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7712 SDValue Chain = Node->getOperand(0);
7713 SDValue In1 = Node->getOperand(1);
7714 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7715 Node->getOperand(2), DAG.getIntPtrConstant(0));
7716 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7717 Node->getOperand(2), DAG.getIntPtrConstant(1));
7718 SDValue Ops[] = { Chain, In1, In2L, In2H };
7719 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7721 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7722 cast<MemSDNode>(Node)->getMemOperand());
7723 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7724 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7725 Results.push_back(Result.getValue(2));
7728 /// ReplaceNodeResults - Replace a node with an illegal result type
7729 /// with a new node built out of custom code.
7730 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7731 SmallVectorImpl<SDValue>&Results,
7732 SelectionDAG &DAG) const {
7733 DebugLoc dl = N->getDebugLoc();
7734 switch (N->getOpcode()) {
7736 assert(false && "Do not know how to custom type legalize this operation!");
7738 case ISD::FP_TO_SINT: {
7739 std::pair<SDValue,SDValue> Vals =
7740 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7741 SDValue FIST = Vals.first, StackSlot = Vals.second;
7742 if (FIST.getNode() != 0) {
7743 EVT VT = N->getValueType(0);
7744 // Return a load from the stack slot.
7745 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7750 case ISD::READCYCLECOUNTER: {
7751 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7752 SDValue TheChain = N->getOperand(0);
7753 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7754 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7756 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7758 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7759 SDValue Ops[] = { eax, edx };
7760 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7761 Results.push_back(edx.getValue(1));
7764 case ISD::ATOMIC_CMP_SWAP: {
7765 EVT T = N->getValueType(0);
7766 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7767 SDValue cpInL, cpInH;
7768 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7769 DAG.getConstant(0, MVT::i32));
7770 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7771 DAG.getConstant(1, MVT::i32));
7772 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7773 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7775 SDValue swapInL, swapInH;
7776 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7777 DAG.getConstant(0, MVT::i32));
7778 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7779 DAG.getConstant(1, MVT::i32));
7780 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7782 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7783 swapInL.getValue(1));
7784 SDValue Ops[] = { swapInH.getValue(0),
7786 swapInH.getValue(1) };
7787 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7788 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7789 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7790 MVT::i32, Result.getValue(1));
7791 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7792 MVT::i32, cpOutL.getValue(2));
7793 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7794 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7795 Results.push_back(cpOutH.getValue(1));
7798 case ISD::ATOMIC_LOAD_ADD:
7799 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7801 case ISD::ATOMIC_LOAD_AND:
7802 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7804 case ISD::ATOMIC_LOAD_NAND:
7805 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7807 case ISD::ATOMIC_LOAD_OR:
7808 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7810 case ISD::ATOMIC_LOAD_SUB:
7811 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7813 case ISD::ATOMIC_LOAD_XOR:
7814 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7816 case ISD::ATOMIC_SWAP:
7817 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7822 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7824 default: return NULL;
7825 case X86ISD::BSF: return "X86ISD::BSF";
7826 case X86ISD::BSR: return "X86ISD::BSR";
7827 case X86ISD::SHLD: return "X86ISD::SHLD";
7828 case X86ISD::SHRD: return "X86ISD::SHRD";
7829 case X86ISD::FAND: return "X86ISD::FAND";
7830 case X86ISD::FOR: return "X86ISD::FOR";
7831 case X86ISD::FXOR: return "X86ISD::FXOR";
7832 case X86ISD::FSRL: return "X86ISD::FSRL";
7833 case X86ISD::FILD: return "X86ISD::FILD";
7834 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7835 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7836 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7837 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7838 case X86ISD::FLD: return "X86ISD::FLD";
7839 case X86ISD::FST: return "X86ISD::FST";
7840 case X86ISD::CALL: return "X86ISD::CALL";
7841 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7842 case X86ISD::BT: return "X86ISD::BT";
7843 case X86ISD::CMP: return "X86ISD::CMP";
7844 case X86ISD::COMI: return "X86ISD::COMI";
7845 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7846 case X86ISD::SETCC: return "X86ISD::SETCC";
7847 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7848 case X86ISD::CMOV: return "X86ISD::CMOV";
7849 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7850 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7851 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7852 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7853 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7854 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7855 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7856 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7857 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7858 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7859 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7860 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7861 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7862 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7863 case X86ISD::FMAX: return "X86ISD::FMAX";
7864 case X86ISD::FMIN: return "X86ISD::FMIN";
7865 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7866 case X86ISD::FRCP: return "X86ISD::FRCP";
7867 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7868 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7869 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7870 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7871 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7872 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7873 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7874 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7875 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7876 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7877 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7878 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7879 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7880 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7881 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7882 case X86ISD::VSHL: return "X86ISD::VSHL";
7883 case X86ISD::VSRL: return "X86ISD::VSRL";
7884 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7885 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7886 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7887 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7888 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7889 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7890 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7891 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7892 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7893 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7894 case X86ISD::ADD: return "X86ISD::ADD";
7895 case X86ISD::SUB: return "X86ISD::SUB";
7896 case X86ISD::SMUL: return "X86ISD::SMUL";
7897 case X86ISD::UMUL: return "X86ISD::UMUL";
7898 case X86ISD::INC: return "X86ISD::INC";
7899 case X86ISD::DEC: return "X86ISD::DEC";
7900 case X86ISD::OR: return "X86ISD::OR";
7901 case X86ISD::XOR: return "X86ISD::XOR";
7902 case X86ISD::AND: return "X86ISD::AND";
7903 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7904 case X86ISD::PTEST: return "X86ISD::PTEST";
7905 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7906 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7910 // isLegalAddressingMode - Return true if the addressing mode represented
7911 // by AM is legal for this target, for a load/store of the specified type.
7912 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7913 const Type *Ty) const {
7914 // X86 supports extremely general addressing modes.
7915 CodeModel::Model M = getTargetMachine().getCodeModel();
7917 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7918 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7923 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7925 // If a reference to this global requires an extra load, we can't fold it.
7926 if (isGlobalStubReference(GVFlags))
7929 // If BaseGV requires a register for the PIC base, we cannot also have a
7930 // BaseReg specified.
7931 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7934 // If lower 4G is not available, then we must use rip-relative addressing.
7935 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7945 // These scales always work.
7950 // These scales are formed with basereg+scalereg. Only accept if there is
7955 default: // Other stuff never works.
7963 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7964 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7966 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7967 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7968 if (NumBits1 <= NumBits2)
7973 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7974 if (!VT1.isInteger() || !VT2.isInteger())
7976 unsigned NumBits1 = VT1.getSizeInBits();
7977 unsigned NumBits2 = VT2.getSizeInBits();
7978 if (NumBits1 <= NumBits2)
7983 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7984 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7985 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7988 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7989 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7990 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7993 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7994 // i16 instructions are longer (0x66 prefix) and potentially slower.
7995 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7998 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7999 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8000 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8001 /// are assumed to be legal.
8003 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8005 // Very little shuffling can be done for 64-bit vectors right now.
8006 if (VT.getSizeInBits() == 64)
8007 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8009 // FIXME: pshufb, blends, shifts.
8010 return (VT.getVectorNumElements() == 2 ||
8011 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8012 isMOVLMask(M, VT) ||
8013 isSHUFPMask(M, VT) ||
8014 isPSHUFDMask(M, VT) ||
8015 isPSHUFHWMask(M, VT) ||
8016 isPSHUFLWMask(M, VT) ||
8017 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8018 isUNPCKLMask(M, VT) ||
8019 isUNPCKHMask(M, VT) ||
8020 isUNPCKL_v_undef_Mask(M, VT) ||
8021 isUNPCKH_v_undef_Mask(M, VT));
8025 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8027 unsigned NumElts = VT.getVectorNumElements();
8028 // FIXME: This collection of masks seems suspect.
8031 if (NumElts == 4 && VT.getSizeInBits() == 128) {
8032 return (isMOVLMask(Mask, VT) ||
8033 isCommutedMOVLMask(Mask, VT, true) ||
8034 isSHUFPMask(Mask, VT) ||
8035 isCommutedSHUFPMask(Mask, VT));
8040 //===----------------------------------------------------------------------===//
8041 // X86 Scheduler Hooks
8042 //===----------------------------------------------------------------------===//
8044 // private utility function
8046 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8047 MachineBasicBlock *MBB,
8055 TargetRegisterClass *RC,
8056 bool invSrc) const {
8057 // For the atomic bitwise operator, we generate
8060 // ld t1 = [bitinstr.addr]
8061 // op t2 = t1, [bitinstr.val]
8063 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8065 // fallthrough -->nextMBB
8066 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8067 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8068 MachineFunction::iterator MBBIter = MBB;
8071 /// First build the CFG
8072 MachineFunction *F = MBB->getParent();
8073 MachineBasicBlock *thisMBB = MBB;
8074 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8075 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8076 F->insert(MBBIter, newMBB);
8077 F->insert(MBBIter, nextMBB);
8079 // Move all successors to thisMBB to nextMBB
8080 nextMBB->transferSuccessors(thisMBB);
8082 // Update thisMBB to fall through to newMBB
8083 thisMBB->addSuccessor(newMBB);
8085 // newMBB jumps to itself and fall through to nextMBB
8086 newMBB->addSuccessor(nextMBB);
8087 newMBB->addSuccessor(newMBB);
8089 // Insert instructions into newMBB based on incoming instruction
8090 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8091 "unexpected number of operands");
8092 DebugLoc dl = bInstr->getDebugLoc();
8093 MachineOperand& destOper = bInstr->getOperand(0);
8094 MachineOperand* argOpers[2 + X86AddrNumOperands];
8095 int numArgs = bInstr->getNumOperands() - 1;
8096 for (int i=0; i < numArgs; ++i)
8097 argOpers[i] = &bInstr->getOperand(i+1);
8099 // x86 address has 4 operands: base, index, scale, and displacement
8100 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8101 int valArgIndx = lastAddrIndx + 1;
8103 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8104 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8105 for (int i=0; i <= lastAddrIndx; ++i)
8106 (*MIB).addOperand(*argOpers[i]);
8108 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8110 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8115 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8116 assert((argOpers[valArgIndx]->isReg() ||
8117 argOpers[valArgIndx]->isImm()) &&
8119 if (argOpers[valArgIndx]->isReg())
8120 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8122 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8124 (*MIB).addOperand(*argOpers[valArgIndx]);
8126 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8129 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8130 for (int i=0; i <= lastAddrIndx; ++i)
8131 (*MIB).addOperand(*argOpers[i]);
8133 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8134 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8135 bInstr->memoperands_end());
8137 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8141 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8143 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8147 // private utility function: 64 bit atomics on 32 bit host.
8149 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8150 MachineBasicBlock *MBB,
8155 bool invSrc) const {
8156 // For the atomic bitwise operator, we generate
8157 // thisMBB (instructions are in pairs, except cmpxchg8b)
8158 // ld t1,t2 = [bitinstr.addr]
8160 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8161 // op t5, t6 <- out1, out2, [bitinstr.val]
8162 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
8163 // mov ECX, EBX <- t5, t6
8164 // mov EAX, EDX <- t1, t2
8165 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
8166 // mov t3, t4 <- EAX, EDX
8168 // result in out1, out2
8169 // fallthrough -->nextMBB
8171 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8172 const unsigned LoadOpc = X86::MOV32rm;
8173 const unsigned copyOpc = X86::MOV32rr;
8174 const unsigned NotOpc = X86::NOT32r;
8175 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8176 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8177 MachineFunction::iterator MBBIter = MBB;
8180 /// First build the CFG
8181 MachineFunction *F = MBB->getParent();
8182 MachineBasicBlock *thisMBB = MBB;
8183 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8184 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8185 F->insert(MBBIter, newMBB);
8186 F->insert(MBBIter, nextMBB);
8188 // Move all successors to thisMBB to nextMBB
8189 nextMBB->transferSuccessors(thisMBB);
8191 // Update thisMBB to fall through to newMBB
8192 thisMBB->addSuccessor(newMBB);
8194 // newMBB jumps to itself and fall through to nextMBB
8195 newMBB->addSuccessor(nextMBB);
8196 newMBB->addSuccessor(newMBB);
8198 DebugLoc dl = bInstr->getDebugLoc();
8199 // Insert instructions into newMBB based on incoming instruction
8200 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8201 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8202 "unexpected number of operands");
8203 MachineOperand& dest1Oper = bInstr->getOperand(0);
8204 MachineOperand& dest2Oper = bInstr->getOperand(1);
8205 MachineOperand* argOpers[2 + X86AddrNumOperands];
8206 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8207 argOpers[i] = &bInstr->getOperand(i+2);
8209 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8210 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8212 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8213 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8214 for (int i=0; i <= lastAddrIndx; ++i)
8215 (*MIB).addOperand(*argOpers[i]);
8216 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8217 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8218 // add 4 to displacement.
8219 for (int i=0; i <= lastAddrIndx-2; ++i)
8220 (*MIB).addOperand(*argOpers[i]);
8221 MachineOperand newOp3 = *(argOpers[3]);
8223 newOp3.setImm(newOp3.getImm()+4);
8225 newOp3.setOffset(newOp3.getOffset()+4);
8226 (*MIB).addOperand(newOp3);
8227 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8229 // t3/4 are defined later, at the bottom of the loop
8230 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8231 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8232 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8233 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8234 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8235 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8237 // The subsequent operations should be using the destination registers of
8238 //the PHI instructions.
8240 t1 = F->getRegInfo().createVirtualRegister(RC);
8241 t2 = F->getRegInfo().createVirtualRegister(RC);
8242 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8243 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8245 t1 = dest1Oper.getReg();
8246 t2 = dest2Oper.getReg();
8249 int valArgIndx = lastAddrIndx + 1;
8250 assert((argOpers[valArgIndx]->isReg() ||
8251 argOpers[valArgIndx]->isImm()) &&
8253 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8254 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8255 if (argOpers[valArgIndx]->isReg())
8256 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8258 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8259 if (regOpcL != X86::MOV32rr)
8261 (*MIB).addOperand(*argOpers[valArgIndx]);
8262 assert(argOpers[valArgIndx + 1]->isReg() ==
8263 argOpers[valArgIndx]->isReg());
8264 assert(argOpers[valArgIndx + 1]->isImm() ==
8265 argOpers[valArgIndx]->isImm());
8266 if (argOpers[valArgIndx + 1]->isReg())
8267 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8269 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8270 if (regOpcH != X86::MOV32rr)
8272 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8274 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8276 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8279 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8281 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8284 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8285 for (int i=0; i <= lastAddrIndx; ++i)
8286 (*MIB).addOperand(*argOpers[i]);
8288 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8289 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8290 bInstr->memoperands_end());
8292 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8293 MIB.addReg(X86::EAX);
8294 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8295 MIB.addReg(X86::EDX);
8298 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8300 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8304 // private utility function
8306 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8307 MachineBasicBlock *MBB,
8308 unsigned cmovOpc) const {
8309 // For the atomic min/max operator, we generate
8312 // ld t1 = [min/max.addr]
8313 // mov t2 = [min/max.val]
8315 // cmov[cond] t2 = t1
8317 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8319 // fallthrough -->nextMBB
8321 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8322 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8323 MachineFunction::iterator MBBIter = MBB;
8326 /// First build the CFG
8327 MachineFunction *F = MBB->getParent();
8328 MachineBasicBlock *thisMBB = MBB;
8329 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8330 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8331 F->insert(MBBIter, newMBB);
8332 F->insert(MBBIter, nextMBB);
8334 // Move all successors of thisMBB to nextMBB
8335 nextMBB->transferSuccessors(thisMBB);
8337 // Update thisMBB to fall through to newMBB
8338 thisMBB->addSuccessor(newMBB);
8340 // newMBB jumps to newMBB and fall through to nextMBB
8341 newMBB->addSuccessor(nextMBB);
8342 newMBB->addSuccessor(newMBB);
8344 DebugLoc dl = mInstr->getDebugLoc();
8345 // Insert instructions into newMBB based on incoming instruction
8346 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8347 "unexpected number of operands");
8348 MachineOperand& destOper = mInstr->getOperand(0);
8349 MachineOperand* argOpers[2 + X86AddrNumOperands];
8350 int numArgs = mInstr->getNumOperands() - 1;
8351 for (int i=0; i < numArgs; ++i)
8352 argOpers[i] = &mInstr->getOperand(i+1);
8354 // x86 address has 4 operands: base, index, scale, and displacement
8355 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8356 int valArgIndx = lastAddrIndx + 1;
8358 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8359 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8360 for (int i=0; i <= lastAddrIndx; ++i)
8361 (*MIB).addOperand(*argOpers[i]);
8363 // We only support register and immediate values
8364 assert((argOpers[valArgIndx]->isReg() ||
8365 argOpers[valArgIndx]->isImm()) &&
8368 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8369 if (argOpers[valArgIndx]->isReg())
8370 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8372 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8373 (*MIB).addOperand(*argOpers[valArgIndx]);
8375 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8378 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8383 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8384 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8388 // Cmp and exchange if none has modified the memory location
8389 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8390 for (int i=0; i <= lastAddrIndx; ++i)
8391 (*MIB).addOperand(*argOpers[i]);
8393 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8394 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8395 mInstr->memoperands_end());
8397 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8398 MIB.addReg(X86::EAX);
8401 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8403 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8407 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8408 // all of this code can be replaced with that in the .td file.
8410 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8411 unsigned numArgs, bool memArg) const {
8413 MachineFunction *F = BB->getParent();
8414 DebugLoc dl = MI->getDebugLoc();
8415 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8419 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8421 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8423 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8425 for (unsigned i = 0; i < numArgs; ++i) {
8426 MachineOperand &Op = MI->getOperand(i+1);
8428 if (!(Op.isReg() && Op.isImplicit()))
8432 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8435 F->DeleteMachineInstr(MI);
8441 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8443 MachineBasicBlock *MBB) const {
8444 // Emit code to save XMM registers to the stack. The ABI says that the
8445 // number of registers to save is given in %al, so it's theoretically
8446 // possible to do an indirect jump trick to avoid saving all of them,
8447 // however this code takes a simpler approach and just executes all
8448 // of the stores if %al is non-zero. It's less code, and it's probably
8449 // easier on the hardware branch predictor, and stores aren't all that
8450 // expensive anyway.
8452 // Create the new basic blocks. One block contains all the XMM stores,
8453 // and one block is the final destination regardless of whether any
8454 // stores were performed.
8455 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8456 MachineFunction *F = MBB->getParent();
8457 MachineFunction::iterator MBBIter = MBB;
8459 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8460 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8461 F->insert(MBBIter, XMMSaveMBB);
8462 F->insert(MBBIter, EndMBB);
8465 // Move any original successors of MBB to the end block.
8466 EndMBB->transferSuccessors(MBB);
8467 // The original block will now fall through to the XMM save block.
8468 MBB->addSuccessor(XMMSaveMBB);
8469 // The XMMSaveMBB will fall through to the end block.
8470 XMMSaveMBB->addSuccessor(EndMBB);
8472 // Now add the instructions.
8473 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8474 DebugLoc DL = MI->getDebugLoc();
8476 unsigned CountReg = MI->getOperand(0).getReg();
8477 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8478 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8480 if (!Subtarget->isTargetWin64()) {
8481 // If %al is 0, branch around the XMM save block.
8482 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8483 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8484 MBB->addSuccessor(EndMBB);
8487 // In the XMM save block, save all the XMM argument registers.
8488 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8489 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8490 MachineMemOperand *MMO =
8491 F->getMachineMemOperand(
8492 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8493 MachineMemOperand::MOStore, Offset,
8494 /*Size=*/16, /*Align=*/16);
8495 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8496 .addFrameIndex(RegSaveFrameIndex)
8497 .addImm(/*Scale=*/1)
8498 .addReg(/*IndexReg=*/0)
8499 .addImm(/*Disp=*/Offset)
8500 .addReg(/*Segment=*/0)
8501 .addReg(MI->getOperand(i).getReg())
8502 .addMemOperand(MMO);
8505 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8511 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8512 MachineBasicBlock *BB) const {
8513 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8514 DebugLoc DL = MI->getDebugLoc();
8516 // To "insert" a SELECT_CC instruction, we actually have to insert the
8517 // diamond control-flow pattern. The incoming instruction knows the
8518 // destination vreg to set, the condition code register to branch on, the
8519 // true/false values to select between, and a branch opcode to use.
8520 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8521 MachineFunction::iterator It = BB;
8527 // cmpTY ccX, r1, r2
8529 // fallthrough --> copy0MBB
8530 MachineBasicBlock *thisMBB = BB;
8531 MachineFunction *F = BB->getParent();
8532 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8533 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8535 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8536 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8537 F->insert(It, copy0MBB);
8538 F->insert(It, sinkMBB);
8539 // Update machine-CFG edges by first adding all successors of the current
8540 // block to the new block which will contain the Phi node for the select.
8541 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8542 E = BB->succ_end(); I != E; ++I)
8543 sinkMBB->addSuccessor(*I);
8544 // Next, remove all successors of the current block, and add the true
8545 // and fallthrough blocks as its successors.
8546 while (!BB->succ_empty())
8547 BB->removeSuccessor(BB->succ_begin());
8548 // Add the true and fallthrough blocks as its successors.
8549 BB->addSuccessor(copy0MBB);
8550 BB->addSuccessor(sinkMBB);
8553 // %FalseValue = ...
8554 // # fallthrough to sinkMBB
8555 copy0MBB->addSuccessor(sinkMBB);
8558 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8560 BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8561 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8562 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8564 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8569 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8570 MachineBasicBlock *BB) const {
8571 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8572 DebugLoc DL = MI->getDebugLoc();
8573 MachineFunction *F = BB->getParent();
8575 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8576 // non-trivial part is impdef of ESP.
8577 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8580 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8581 .addExternalSymbol("_alloca")
8582 .addReg(X86::EAX, RegState::Implicit)
8583 .addReg(X86::ESP, RegState::Implicit)
8584 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8585 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8587 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8592 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8593 MachineBasicBlock *BB) const {
8594 switch (MI->getOpcode()) {
8595 default: assert(false && "Unexpected instr type to insert");
8596 case X86::MINGW_ALLOCA:
8597 return EmitLoweredMingwAlloca(MI, BB);
8599 case X86::CMOV_V1I64:
8600 case X86::CMOV_FR32:
8601 case X86::CMOV_FR64:
8602 case X86::CMOV_V4F32:
8603 case X86::CMOV_V2F64:
8604 case X86::CMOV_V2I64:
8605 case X86::CMOV_GR16:
8606 case X86::CMOV_GR32:
8607 case X86::CMOV_RFP32:
8608 case X86::CMOV_RFP64:
8609 case X86::CMOV_RFP80:
8610 return EmitLoweredSelect(MI, BB);
8612 case X86::FP32_TO_INT16_IN_MEM:
8613 case X86::FP32_TO_INT32_IN_MEM:
8614 case X86::FP32_TO_INT64_IN_MEM:
8615 case X86::FP64_TO_INT16_IN_MEM:
8616 case X86::FP64_TO_INT32_IN_MEM:
8617 case X86::FP64_TO_INT64_IN_MEM:
8618 case X86::FP80_TO_INT16_IN_MEM:
8619 case X86::FP80_TO_INT32_IN_MEM:
8620 case X86::FP80_TO_INT64_IN_MEM: {
8621 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8622 DebugLoc DL = MI->getDebugLoc();
8624 // Change the floating point control register to use "round towards zero"
8625 // mode when truncating to an integer value.
8626 MachineFunction *F = BB->getParent();
8627 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8628 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8630 // Load the old value of the high byte of the control word...
8632 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8633 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8636 // Set the high part to be round to zero...
8637 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8640 // Reload the modified control word now...
8641 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8643 // Restore the memory image of control word to original value
8644 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8647 // Get the X86 opcode to use.
8649 switch (MI->getOpcode()) {
8650 default: llvm_unreachable("illegal opcode!");
8651 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8652 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8653 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8654 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8655 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8656 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8657 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8658 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8659 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8663 MachineOperand &Op = MI->getOperand(0);
8665 AM.BaseType = X86AddressMode::RegBase;
8666 AM.Base.Reg = Op.getReg();
8668 AM.BaseType = X86AddressMode::FrameIndexBase;
8669 AM.Base.FrameIndex = Op.getIndex();
8671 Op = MI->getOperand(1);
8673 AM.Scale = Op.getImm();
8674 Op = MI->getOperand(2);
8676 AM.IndexReg = Op.getImm();
8677 Op = MI->getOperand(3);
8678 if (Op.isGlobal()) {
8679 AM.GV = Op.getGlobal();
8681 AM.Disp = Op.getImm();
8683 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8684 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8686 // Reload the original control word now.
8687 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8689 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8692 // String/text processing lowering.
8693 case X86::PCMPISTRM128REG:
8694 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8695 case X86::PCMPISTRM128MEM:
8696 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8697 case X86::PCMPESTRM128REG:
8698 return EmitPCMP(MI, BB, 5, false /* in mem */);
8699 case X86::PCMPESTRM128MEM:
8700 return EmitPCMP(MI, BB, 5, true /* in mem */);
8703 case X86::ATOMAND32:
8704 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8705 X86::AND32ri, X86::MOV32rm,
8706 X86::LCMPXCHG32, X86::MOV32rr,
8707 X86::NOT32r, X86::EAX,
8708 X86::GR32RegisterClass);
8710 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8711 X86::OR32ri, X86::MOV32rm,
8712 X86::LCMPXCHG32, X86::MOV32rr,
8713 X86::NOT32r, X86::EAX,
8714 X86::GR32RegisterClass);
8715 case X86::ATOMXOR32:
8716 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8717 X86::XOR32ri, X86::MOV32rm,
8718 X86::LCMPXCHG32, X86::MOV32rr,
8719 X86::NOT32r, X86::EAX,
8720 X86::GR32RegisterClass);
8721 case X86::ATOMNAND32:
8722 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8723 X86::AND32ri, X86::MOV32rm,
8724 X86::LCMPXCHG32, X86::MOV32rr,
8725 X86::NOT32r, X86::EAX,
8726 X86::GR32RegisterClass, true);
8727 case X86::ATOMMIN32:
8728 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8729 case X86::ATOMMAX32:
8730 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8731 case X86::ATOMUMIN32:
8732 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8733 case X86::ATOMUMAX32:
8734 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8736 case X86::ATOMAND16:
8737 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8738 X86::AND16ri, X86::MOV16rm,
8739 X86::LCMPXCHG16, X86::MOV16rr,
8740 X86::NOT16r, X86::AX,
8741 X86::GR16RegisterClass);
8743 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8744 X86::OR16ri, X86::MOV16rm,
8745 X86::LCMPXCHG16, X86::MOV16rr,
8746 X86::NOT16r, X86::AX,
8747 X86::GR16RegisterClass);
8748 case X86::ATOMXOR16:
8749 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8750 X86::XOR16ri, X86::MOV16rm,
8751 X86::LCMPXCHG16, X86::MOV16rr,
8752 X86::NOT16r, X86::AX,
8753 X86::GR16RegisterClass);
8754 case X86::ATOMNAND16:
8755 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8756 X86::AND16ri, X86::MOV16rm,
8757 X86::LCMPXCHG16, X86::MOV16rr,
8758 X86::NOT16r, X86::AX,
8759 X86::GR16RegisterClass, true);
8760 case X86::ATOMMIN16:
8761 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8762 case X86::ATOMMAX16:
8763 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8764 case X86::ATOMUMIN16:
8765 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8766 case X86::ATOMUMAX16:
8767 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8770 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8771 X86::AND8ri, X86::MOV8rm,
8772 X86::LCMPXCHG8, X86::MOV8rr,
8773 X86::NOT8r, X86::AL,
8774 X86::GR8RegisterClass);
8776 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8777 X86::OR8ri, X86::MOV8rm,
8778 X86::LCMPXCHG8, X86::MOV8rr,
8779 X86::NOT8r, X86::AL,
8780 X86::GR8RegisterClass);
8782 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8783 X86::XOR8ri, X86::MOV8rm,
8784 X86::LCMPXCHG8, X86::MOV8rr,
8785 X86::NOT8r, X86::AL,
8786 X86::GR8RegisterClass);
8787 case X86::ATOMNAND8:
8788 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8789 X86::AND8ri, X86::MOV8rm,
8790 X86::LCMPXCHG8, X86::MOV8rr,
8791 X86::NOT8r, X86::AL,
8792 X86::GR8RegisterClass, true);
8793 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8794 // This group is for 64-bit host.
8795 case X86::ATOMAND64:
8796 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8797 X86::AND64ri32, X86::MOV64rm,
8798 X86::LCMPXCHG64, X86::MOV64rr,
8799 X86::NOT64r, X86::RAX,
8800 X86::GR64RegisterClass);
8802 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8803 X86::OR64ri32, X86::MOV64rm,
8804 X86::LCMPXCHG64, X86::MOV64rr,
8805 X86::NOT64r, X86::RAX,
8806 X86::GR64RegisterClass);
8807 case X86::ATOMXOR64:
8808 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8809 X86::XOR64ri32, X86::MOV64rm,
8810 X86::LCMPXCHG64, X86::MOV64rr,
8811 X86::NOT64r, X86::RAX,
8812 X86::GR64RegisterClass);
8813 case X86::ATOMNAND64:
8814 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8815 X86::AND64ri32, X86::MOV64rm,
8816 X86::LCMPXCHG64, X86::MOV64rr,
8817 X86::NOT64r, X86::RAX,
8818 X86::GR64RegisterClass, true);
8819 case X86::ATOMMIN64:
8820 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8821 case X86::ATOMMAX64:
8822 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8823 case X86::ATOMUMIN64:
8824 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8825 case X86::ATOMUMAX64:
8826 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8828 // This group does 64-bit operations on a 32-bit host.
8829 case X86::ATOMAND6432:
8830 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8831 X86::AND32rr, X86::AND32rr,
8832 X86::AND32ri, X86::AND32ri,
8834 case X86::ATOMOR6432:
8835 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8836 X86::OR32rr, X86::OR32rr,
8837 X86::OR32ri, X86::OR32ri,
8839 case X86::ATOMXOR6432:
8840 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8841 X86::XOR32rr, X86::XOR32rr,
8842 X86::XOR32ri, X86::XOR32ri,
8844 case X86::ATOMNAND6432:
8845 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8846 X86::AND32rr, X86::AND32rr,
8847 X86::AND32ri, X86::AND32ri,
8849 case X86::ATOMADD6432:
8850 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8851 X86::ADD32rr, X86::ADC32rr,
8852 X86::ADD32ri, X86::ADC32ri,
8854 case X86::ATOMSUB6432:
8855 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8856 X86::SUB32rr, X86::SBB32rr,
8857 X86::SUB32ri, X86::SBB32ri,
8859 case X86::ATOMSWAP6432:
8860 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8861 X86::MOV32rr, X86::MOV32rr,
8862 X86::MOV32ri, X86::MOV32ri,
8864 case X86::VASTART_SAVE_XMM_REGS:
8865 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8869 //===----------------------------------------------------------------------===//
8870 // X86 Optimization Hooks
8871 //===----------------------------------------------------------------------===//
8873 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8877 const SelectionDAG &DAG,
8878 unsigned Depth) const {
8879 unsigned Opc = Op.getOpcode();
8880 assert((Opc >= ISD::BUILTIN_OP_END ||
8881 Opc == ISD::INTRINSIC_WO_CHAIN ||
8882 Opc == ISD::INTRINSIC_W_CHAIN ||
8883 Opc == ISD::INTRINSIC_VOID) &&
8884 "Should use MaskedValueIsZero if you don't know whether Op"
8885 " is a target node!");
8887 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8899 // These nodes' second result is a boolean.
8900 if (Op.getResNo() == 0)
8904 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8905 Mask.getBitWidth() - 1);
8910 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8911 /// node is a GlobalAddress + offset.
8912 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8913 const GlobalValue* &GA,
8914 int64_t &Offset) const {
8915 if (N->getOpcode() == X86ISD::Wrapper) {
8916 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8917 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8918 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8922 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8925 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8926 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8927 /// if the load addresses are consecutive, non-overlapping, and in the right
8929 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8930 const TargetLowering &TLI) {
8931 DebugLoc dl = N->getDebugLoc();
8932 EVT VT = N->getValueType(0);
8933 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8935 if (VT.getSizeInBits() != 128)
8938 SmallVector<SDValue, 16> Elts;
8939 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8940 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8942 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8945 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8946 /// and convert it from being a bunch of shuffles and extracts to a simple
8947 /// store and scalar loads to extract the elements.
8948 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8949 const TargetLowering &TLI) {
8950 SDValue InputVector = N->getOperand(0);
8952 // Only operate on vectors of 4 elements, where the alternative shuffling
8953 // gets to be more expensive.
8954 if (InputVector.getValueType() != MVT::v4i32)
8957 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8958 // single use which is a sign-extend or zero-extend, and all elements are
8960 SmallVector<SDNode *, 4> Uses;
8961 unsigned ExtractedElements = 0;
8962 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8963 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8964 if (UI.getUse().getResNo() != InputVector.getResNo())
8967 SDNode *Extract = *UI;
8968 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8971 if (Extract->getValueType(0) != MVT::i32)
8973 if (!Extract->hasOneUse())
8975 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8976 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8978 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8981 // Record which element was extracted.
8982 ExtractedElements |=
8983 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8985 Uses.push_back(Extract);
8988 // If not all the elements were used, this may not be worthwhile.
8989 if (ExtractedElements != 15)
8992 // Ok, we've now decided to do the transformation.
8993 DebugLoc dl = InputVector.getDebugLoc();
8995 // Store the value to a temporary stack slot.
8996 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8997 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
9000 // Replace each use (extract) with a load of the appropriate element.
9001 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9002 UE = Uses.end(); UI != UE; ++UI) {
9003 SDNode *Extract = *UI;
9005 // Compute the element's address.
9006 SDValue Idx = Extract->getOperand(1);
9008 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9009 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9010 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9012 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
9015 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
9016 NULL, 0, false, false, 0);
9018 // Replace the exact with the load.
9019 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9022 // The replacement was made in place; don't return anything.
9026 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9027 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9028 const X86Subtarget *Subtarget) {
9029 DebugLoc DL = N->getDebugLoc();
9030 SDValue Cond = N->getOperand(0);
9031 // Get the LHS/RHS of the select.
9032 SDValue LHS = N->getOperand(1);
9033 SDValue RHS = N->getOperand(2);
9035 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9036 // instructions match the semantics of the common C idiom x<y?x:y but not
9037 // x<=y?x:y, because of how they handle negative zero (which can be
9038 // ignored in unsafe-math mode).
9039 if (Subtarget->hasSSE2() &&
9040 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9041 Cond.getOpcode() == ISD::SETCC) {
9042 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9044 unsigned Opcode = 0;
9045 // Check for x CC y ? x : y.
9046 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9047 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9051 // Converting this to a min would handle NaNs incorrectly, and swapping
9052 // the operands would cause it to handle comparisons between positive
9053 // and negative zero incorrectly.
9054 if (!FiniteOnlyFPMath() &&
9055 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9056 if (!UnsafeFPMath &&
9057 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9059 std::swap(LHS, RHS);
9061 Opcode = X86ISD::FMIN;
9064 // Converting this to a min would handle comparisons between positive
9065 // and negative zero incorrectly.
9066 if (!UnsafeFPMath &&
9067 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9069 Opcode = X86ISD::FMIN;
9072 // Converting this to a min would handle both negative zeros and NaNs
9073 // incorrectly, but we can swap the operands to fix both.
9074 std::swap(LHS, RHS);
9078 Opcode = X86ISD::FMIN;
9082 // Converting this to a max would handle comparisons between positive
9083 // and negative zero incorrectly.
9084 if (!UnsafeFPMath &&
9085 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9087 Opcode = X86ISD::FMAX;
9090 // Converting this to a max would handle NaNs incorrectly, and swapping
9091 // the operands would cause it to handle comparisons between positive
9092 // and negative zero incorrectly.
9093 if (!FiniteOnlyFPMath() &&
9094 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9095 if (!UnsafeFPMath &&
9096 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9098 std::swap(LHS, RHS);
9100 Opcode = X86ISD::FMAX;
9103 // Converting this to a max would handle both negative zeros and NaNs
9104 // incorrectly, but we can swap the operands to fix both.
9105 std::swap(LHS, RHS);
9109 Opcode = X86ISD::FMAX;
9112 // Check for x CC y ? y : x -- a min/max with reversed arms.
9113 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9114 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9118 // Converting this to a min would handle comparisons between positive
9119 // and negative zero incorrectly, and swapping the operands would
9120 // cause it to handle NaNs incorrectly.
9121 if (!UnsafeFPMath &&
9122 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9123 if (!FiniteOnlyFPMath() &&
9124 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9126 std::swap(LHS, RHS);
9128 Opcode = X86ISD::FMIN;
9131 // Converting this to a min would handle NaNs incorrectly.
9132 if (!UnsafeFPMath &&
9133 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9135 Opcode = X86ISD::FMIN;
9138 // Converting this to a min would handle both negative zeros and NaNs
9139 // incorrectly, but we can swap the operands to fix both.
9140 std::swap(LHS, RHS);
9144 Opcode = X86ISD::FMIN;
9148 // Converting this to a max would handle NaNs incorrectly.
9149 if (!FiniteOnlyFPMath() &&
9150 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9152 Opcode = X86ISD::FMAX;
9155 // Converting this to a max would handle comparisons between positive
9156 // and negative zero incorrectly, and swapping the operands would
9157 // cause it to handle NaNs incorrectly.
9158 if (!UnsafeFPMath &&
9159 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9160 if (!FiniteOnlyFPMath() &&
9161 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9163 std::swap(LHS, RHS);
9165 Opcode = X86ISD::FMAX;
9168 // Converting this to a max would handle both negative zeros and NaNs
9169 // incorrectly, but we can swap the operands to fix both.
9170 std::swap(LHS, RHS);
9174 Opcode = X86ISD::FMAX;
9180 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9183 // If this is a select between two integer constants, try to do some
9185 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9186 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9187 // Don't do this for crazy integer types.
9188 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9189 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9190 // so that TrueC (the true value) is larger than FalseC.
9191 bool NeedsCondInvert = false;
9193 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9194 // Efficiently invertible.
9195 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9196 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9197 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9198 NeedsCondInvert = true;
9199 std::swap(TrueC, FalseC);
9202 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9203 if (FalseC->getAPIntValue() == 0 &&
9204 TrueC->getAPIntValue().isPowerOf2()) {
9205 if (NeedsCondInvert) // Invert the condition if needed.
9206 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9207 DAG.getConstant(1, Cond.getValueType()));
9209 // Zero extend the condition if needed.
9210 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9212 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9213 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9214 DAG.getConstant(ShAmt, MVT::i8));
9217 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9218 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9219 if (NeedsCondInvert) // Invert the condition if needed.
9220 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9221 DAG.getConstant(1, Cond.getValueType()));
9223 // Zero extend the condition if needed.
9224 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9225 FalseC->getValueType(0), Cond);
9226 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9227 SDValue(FalseC, 0));
9230 // Optimize cases that will turn into an LEA instruction. This requires
9231 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9232 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9233 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9234 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9236 bool isFastMultiplier = false;
9238 switch ((unsigned char)Diff) {
9240 case 1: // result = add base, cond
9241 case 2: // result = lea base( , cond*2)
9242 case 3: // result = lea base(cond, cond*2)
9243 case 4: // result = lea base( , cond*4)
9244 case 5: // result = lea base(cond, cond*4)
9245 case 8: // result = lea base( , cond*8)
9246 case 9: // result = lea base(cond, cond*8)
9247 isFastMultiplier = true;
9252 if (isFastMultiplier) {
9253 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9254 if (NeedsCondInvert) // Invert the condition if needed.
9255 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9256 DAG.getConstant(1, Cond.getValueType()));
9258 // Zero extend the condition if needed.
9259 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9261 // Scale the condition by the difference.
9263 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9264 DAG.getConstant(Diff, Cond.getValueType()));
9266 // Add the base if non-zero.
9267 if (FalseC->getAPIntValue() != 0)
9268 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9269 SDValue(FalseC, 0));
9279 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9280 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9281 TargetLowering::DAGCombinerInfo &DCI) {
9282 DebugLoc DL = N->getDebugLoc();
9284 // If the flag operand isn't dead, don't touch this CMOV.
9285 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9288 // If this is a select between two integer constants, try to do some
9289 // optimizations. Note that the operands are ordered the opposite of SELECT
9291 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9292 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9293 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9294 // larger than FalseC (the false value).
9295 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9297 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9298 CC = X86::GetOppositeBranchCondition(CC);
9299 std::swap(TrueC, FalseC);
9302 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9303 // This is efficient for any integer data type (including i8/i16) and
9305 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9306 SDValue Cond = N->getOperand(3);
9307 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9308 DAG.getConstant(CC, MVT::i8), Cond);
9310 // Zero extend the condition if needed.
9311 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9313 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9314 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9315 DAG.getConstant(ShAmt, MVT::i8));
9316 if (N->getNumValues() == 2) // Dead flag value?
9317 return DCI.CombineTo(N, Cond, SDValue());
9321 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9322 // for any integer data type, including i8/i16.
9323 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9324 SDValue Cond = N->getOperand(3);
9325 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9326 DAG.getConstant(CC, MVT::i8), Cond);
9328 // Zero extend the condition if needed.
9329 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9330 FalseC->getValueType(0), Cond);
9331 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9332 SDValue(FalseC, 0));
9334 if (N->getNumValues() == 2) // Dead flag value?
9335 return DCI.CombineTo(N, Cond, SDValue());
9339 // Optimize cases that will turn into an LEA instruction. This requires
9340 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9341 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9342 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9343 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9345 bool isFastMultiplier = false;
9347 switch ((unsigned char)Diff) {
9349 case 1: // result = add base, cond
9350 case 2: // result = lea base( , cond*2)
9351 case 3: // result = lea base(cond, cond*2)
9352 case 4: // result = lea base( , cond*4)
9353 case 5: // result = lea base(cond, cond*4)
9354 case 8: // result = lea base( , cond*8)
9355 case 9: // result = lea base(cond, cond*8)
9356 isFastMultiplier = true;
9361 if (isFastMultiplier) {
9362 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9363 SDValue Cond = N->getOperand(3);
9364 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9365 DAG.getConstant(CC, MVT::i8), Cond);
9366 // Zero extend the condition if needed.
9367 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9369 // Scale the condition by the difference.
9371 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9372 DAG.getConstant(Diff, Cond.getValueType()));
9374 // Add the base if non-zero.
9375 if (FalseC->getAPIntValue() != 0)
9376 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9377 SDValue(FalseC, 0));
9378 if (N->getNumValues() == 2) // Dead flag value?
9379 return DCI.CombineTo(N, Cond, SDValue());
9389 /// PerformMulCombine - Optimize a single multiply with constant into two
9390 /// in order to implement it with two cheaper instructions, e.g.
9391 /// LEA + SHL, LEA + LEA.
9392 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9393 TargetLowering::DAGCombinerInfo &DCI) {
9394 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9397 EVT VT = N->getValueType(0);
9401 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9404 uint64_t MulAmt = C->getZExtValue();
9405 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9408 uint64_t MulAmt1 = 0;
9409 uint64_t MulAmt2 = 0;
9410 if ((MulAmt % 9) == 0) {
9412 MulAmt2 = MulAmt / 9;
9413 } else if ((MulAmt % 5) == 0) {
9415 MulAmt2 = MulAmt / 5;
9416 } else if ((MulAmt % 3) == 0) {
9418 MulAmt2 = MulAmt / 3;
9421 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9422 DebugLoc DL = N->getDebugLoc();
9424 if (isPowerOf2_64(MulAmt2) &&
9425 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9426 // If second multiplifer is pow2, issue it first. We want the multiply by
9427 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9429 std::swap(MulAmt1, MulAmt2);
9432 if (isPowerOf2_64(MulAmt1))
9433 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9434 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9436 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9437 DAG.getConstant(MulAmt1, VT));
9439 if (isPowerOf2_64(MulAmt2))
9440 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9441 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9443 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9444 DAG.getConstant(MulAmt2, VT));
9446 // Do not add new nodes to DAG combiner worklist.
9447 DCI.CombineTo(N, NewMul, false);
9452 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9453 SDValue N0 = N->getOperand(0);
9454 SDValue N1 = N->getOperand(1);
9455 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9456 EVT VT = N0.getValueType();
9458 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9459 // since the result of setcc_c is all zero's or all ones.
9460 if (N1C && N0.getOpcode() == ISD::AND &&
9461 N0.getOperand(1).getOpcode() == ISD::Constant) {
9462 SDValue N00 = N0.getOperand(0);
9463 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9464 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9465 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9466 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9467 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9468 APInt ShAmt = N1C->getAPIntValue();
9469 Mask = Mask.shl(ShAmt);
9471 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9472 N00, DAG.getConstant(Mask, VT));
9479 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9481 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9482 const X86Subtarget *Subtarget) {
9483 EVT VT = N->getValueType(0);
9484 if (!VT.isVector() && VT.isInteger() &&
9485 N->getOpcode() == ISD::SHL)
9486 return PerformSHLCombine(N, DAG);
9488 // On X86 with SSE2 support, we can transform this to a vector shift if
9489 // all elements are shifted by the same amount. We can't do this in legalize
9490 // because the a constant vector is typically transformed to a constant pool
9491 // so we have no knowledge of the shift amount.
9492 if (!Subtarget->hasSSE2())
9495 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9498 SDValue ShAmtOp = N->getOperand(1);
9499 EVT EltVT = VT.getVectorElementType();
9500 DebugLoc DL = N->getDebugLoc();
9501 SDValue BaseShAmt = SDValue();
9502 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9503 unsigned NumElts = VT.getVectorNumElements();
9505 for (; i != NumElts; ++i) {
9506 SDValue Arg = ShAmtOp.getOperand(i);
9507 if (Arg.getOpcode() == ISD::UNDEF) continue;
9511 for (; i != NumElts; ++i) {
9512 SDValue Arg = ShAmtOp.getOperand(i);
9513 if (Arg.getOpcode() == ISD::UNDEF) continue;
9514 if (Arg != BaseShAmt) {
9518 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9519 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9520 SDValue InVec = ShAmtOp.getOperand(0);
9521 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9522 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9524 for (; i != NumElts; ++i) {
9525 SDValue Arg = InVec.getOperand(i);
9526 if (Arg.getOpcode() == ISD::UNDEF) continue;
9530 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9532 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9533 if (C->getZExtValue() == SplatIdx)
9534 BaseShAmt = InVec.getOperand(1);
9537 if (BaseShAmt.getNode() == 0)
9538 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9539 DAG.getIntPtrConstant(0));
9543 // The shift amount is an i32.
9544 if (EltVT.bitsGT(MVT::i32))
9545 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9546 else if (EltVT.bitsLT(MVT::i32))
9547 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9549 // The shift amount is identical so we can do a vector shift.
9550 SDValue ValOp = N->getOperand(0);
9551 switch (N->getOpcode()) {
9553 llvm_unreachable("Unknown shift opcode!");
9556 if (VT == MVT::v2i64)
9557 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9558 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9560 if (VT == MVT::v4i32)
9561 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9562 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9564 if (VT == MVT::v8i16)
9565 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9566 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9570 if (VT == MVT::v4i32)
9571 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9572 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9574 if (VT == MVT::v8i16)
9575 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9576 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9580 if (VT == MVT::v2i64)
9581 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9582 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9584 if (VT == MVT::v4i32)
9585 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9586 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9588 if (VT == MVT::v8i16)
9589 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9590 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9597 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9598 TargetLowering::DAGCombinerInfo &DCI,
9599 const X86Subtarget *Subtarget) {
9600 if (DCI.isBeforeLegalizeOps())
9603 EVT VT = N->getValueType(0);
9604 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9607 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9608 SDValue N0 = N->getOperand(0);
9609 SDValue N1 = N->getOperand(1);
9610 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9612 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9614 if (!N0.hasOneUse() || !N1.hasOneUse())
9617 SDValue ShAmt0 = N0.getOperand(1);
9618 if (ShAmt0.getValueType() != MVT::i8)
9620 SDValue ShAmt1 = N1.getOperand(1);
9621 if (ShAmt1.getValueType() != MVT::i8)
9623 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9624 ShAmt0 = ShAmt0.getOperand(0);
9625 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9626 ShAmt1 = ShAmt1.getOperand(0);
9628 DebugLoc DL = N->getDebugLoc();
9629 unsigned Opc = X86ISD::SHLD;
9630 SDValue Op0 = N0.getOperand(0);
9631 SDValue Op1 = N1.getOperand(0);
9632 if (ShAmt0.getOpcode() == ISD::SUB) {
9634 std::swap(Op0, Op1);
9635 std::swap(ShAmt0, ShAmt1);
9638 unsigned Bits = VT.getSizeInBits();
9639 if (ShAmt1.getOpcode() == ISD::SUB) {
9640 SDValue Sum = ShAmt1.getOperand(0);
9641 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9642 if (SumC->getSExtValue() == Bits &&
9643 ShAmt1.getOperand(1) == ShAmt0)
9644 return DAG.getNode(Opc, DL, VT,
9646 DAG.getNode(ISD::TRUNCATE, DL,
9649 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9650 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9652 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9653 return DAG.getNode(Opc, DL, VT,
9654 N0.getOperand(0), N1.getOperand(0),
9655 DAG.getNode(ISD::TRUNCATE, DL,
9662 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9663 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9664 const X86Subtarget *Subtarget) {
9665 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9666 // the FP state in cases where an emms may be missing.
9667 // A preferable solution to the general problem is to figure out the right
9668 // places to insert EMMS. This qualifies as a quick hack.
9670 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9671 StoreSDNode *St = cast<StoreSDNode>(N);
9672 EVT VT = St->getValue().getValueType();
9673 if (VT.getSizeInBits() != 64)
9676 const Function *F = DAG.getMachineFunction().getFunction();
9677 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9678 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9679 && Subtarget->hasSSE2();
9680 if ((VT.isVector() ||
9681 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9682 isa<LoadSDNode>(St->getValue()) &&
9683 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9684 St->getChain().hasOneUse() && !St->isVolatile()) {
9685 SDNode* LdVal = St->getValue().getNode();
9687 int TokenFactorIndex = -1;
9688 SmallVector<SDValue, 8> Ops;
9689 SDNode* ChainVal = St->getChain().getNode();
9690 // Must be a store of a load. We currently handle two cases: the load
9691 // is a direct child, and it's under an intervening TokenFactor. It is
9692 // possible to dig deeper under nested TokenFactors.
9693 if (ChainVal == LdVal)
9694 Ld = cast<LoadSDNode>(St->getChain());
9695 else if (St->getValue().hasOneUse() &&
9696 ChainVal->getOpcode() == ISD::TokenFactor) {
9697 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9698 if (ChainVal->getOperand(i).getNode() == LdVal) {
9699 TokenFactorIndex = i;
9700 Ld = cast<LoadSDNode>(St->getValue());
9702 Ops.push_back(ChainVal->getOperand(i));
9706 if (!Ld || !ISD::isNormalLoad(Ld))
9709 // If this is not the MMX case, i.e. we are just turning i64 load/store
9710 // into f64 load/store, avoid the transformation if there are multiple
9711 // uses of the loaded value.
9712 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9715 DebugLoc LdDL = Ld->getDebugLoc();
9716 DebugLoc StDL = N->getDebugLoc();
9717 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9718 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9720 if (Subtarget->is64Bit() || F64IsLegal) {
9721 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9722 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9723 Ld->getBasePtr(), Ld->getSrcValue(),
9724 Ld->getSrcValueOffset(), Ld->isVolatile(),
9725 Ld->isNonTemporal(), Ld->getAlignment());
9726 SDValue NewChain = NewLd.getValue(1);
9727 if (TokenFactorIndex != -1) {
9728 Ops.push_back(NewChain);
9729 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9732 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9733 St->getSrcValue(), St->getSrcValueOffset(),
9734 St->isVolatile(), St->isNonTemporal(),
9735 St->getAlignment());
9738 // Otherwise, lower to two pairs of 32-bit loads / stores.
9739 SDValue LoAddr = Ld->getBasePtr();
9740 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9741 DAG.getConstant(4, MVT::i32));
9743 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9744 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9745 Ld->isVolatile(), Ld->isNonTemporal(),
9746 Ld->getAlignment());
9747 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9748 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9749 Ld->isVolatile(), Ld->isNonTemporal(),
9750 MinAlign(Ld->getAlignment(), 4));
9752 SDValue NewChain = LoLd.getValue(1);
9753 if (TokenFactorIndex != -1) {
9754 Ops.push_back(LoLd);
9755 Ops.push_back(HiLd);
9756 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9760 LoAddr = St->getBasePtr();
9761 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9762 DAG.getConstant(4, MVT::i32));
9764 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9765 St->getSrcValue(), St->getSrcValueOffset(),
9766 St->isVolatile(), St->isNonTemporal(),
9767 St->getAlignment());
9768 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9770 St->getSrcValueOffset() + 4,
9772 St->isNonTemporal(),
9773 MinAlign(St->getAlignment(), 4));
9774 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9779 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9780 /// X86ISD::FXOR nodes.
9781 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9782 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9783 // F[X]OR(0.0, x) -> x
9784 // F[X]OR(x, 0.0) -> x
9785 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9786 if (C->getValueAPF().isPosZero())
9787 return N->getOperand(1);
9788 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9789 if (C->getValueAPF().isPosZero())
9790 return N->getOperand(0);
9794 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9795 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9796 // FAND(0.0, x) -> 0.0
9797 // FAND(x, 0.0) -> 0.0
9798 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9799 if (C->getValueAPF().isPosZero())
9800 return N->getOperand(0);
9801 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9802 if (C->getValueAPF().isPosZero())
9803 return N->getOperand(1);
9807 static SDValue PerformBTCombine(SDNode *N,
9809 TargetLowering::DAGCombinerInfo &DCI) {
9810 // BT ignores high bits in the bit index operand.
9811 SDValue Op1 = N->getOperand(1);
9812 if (Op1.hasOneUse()) {
9813 unsigned BitWidth = Op1.getValueSizeInBits();
9814 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9815 APInt KnownZero, KnownOne;
9816 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9817 !DCI.isBeforeLegalizeOps());
9818 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9819 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9820 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9821 DCI.CommitTargetLoweringOpt(TLO);
9826 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9827 SDValue Op = N->getOperand(0);
9828 if (Op.getOpcode() == ISD::BIT_CONVERT)
9829 Op = Op.getOperand(0);
9830 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9831 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9832 VT.getVectorElementType().getSizeInBits() ==
9833 OpVT.getVectorElementType().getSizeInBits()) {
9834 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9839 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9840 // Locked instructions, in turn, have implicit fence semantics (all memory
9841 // operations are flushed before issuing the locked instruction, and the
9842 // are not buffered), so we can fold away the common pattern of
9843 // fence-atomic-fence.
9844 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9845 SDValue atomic = N->getOperand(0);
9846 switch (atomic.getOpcode()) {
9847 case ISD::ATOMIC_CMP_SWAP:
9848 case ISD::ATOMIC_SWAP:
9849 case ISD::ATOMIC_LOAD_ADD:
9850 case ISD::ATOMIC_LOAD_SUB:
9851 case ISD::ATOMIC_LOAD_AND:
9852 case ISD::ATOMIC_LOAD_OR:
9853 case ISD::ATOMIC_LOAD_XOR:
9854 case ISD::ATOMIC_LOAD_NAND:
9855 case ISD::ATOMIC_LOAD_MIN:
9856 case ISD::ATOMIC_LOAD_MAX:
9857 case ISD::ATOMIC_LOAD_UMIN:
9858 case ISD::ATOMIC_LOAD_UMAX:
9864 SDValue fence = atomic.getOperand(0);
9865 if (fence.getOpcode() != ISD::MEMBARRIER)
9868 switch (atomic.getOpcode()) {
9869 case ISD::ATOMIC_CMP_SWAP:
9870 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9871 atomic.getOperand(1), atomic.getOperand(2),
9872 atomic.getOperand(3));
9873 case ISD::ATOMIC_SWAP:
9874 case ISD::ATOMIC_LOAD_ADD:
9875 case ISD::ATOMIC_LOAD_SUB:
9876 case ISD::ATOMIC_LOAD_AND:
9877 case ISD::ATOMIC_LOAD_OR:
9878 case ISD::ATOMIC_LOAD_XOR:
9879 case ISD::ATOMIC_LOAD_NAND:
9880 case ISD::ATOMIC_LOAD_MIN:
9881 case ISD::ATOMIC_LOAD_MAX:
9882 case ISD::ATOMIC_LOAD_UMIN:
9883 case ISD::ATOMIC_LOAD_UMAX:
9884 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9885 atomic.getOperand(1), atomic.getOperand(2));
9891 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9892 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9893 // (and (i32 x86isd::setcc_carry), 1)
9894 // This eliminates the zext. This transformation is necessary because
9895 // ISD::SETCC is always legalized to i8.
9896 DebugLoc dl = N->getDebugLoc();
9897 SDValue N0 = N->getOperand(0);
9898 EVT VT = N->getValueType(0);
9899 if (N0.getOpcode() == ISD::AND &&
9901 N0.getOperand(0).hasOneUse()) {
9902 SDValue N00 = N0.getOperand(0);
9903 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9905 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9906 if (!C || C->getZExtValue() != 1)
9908 return DAG.getNode(ISD::AND, dl, VT,
9909 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9910 N00.getOperand(0), N00.getOperand(1)),
9911 DAG.getConstant(1, VT));
9917 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9918 DAGCombinerInfo &DCI) const {
9919 SelectionDAG &DAG = DCI.DAG;
9920 switch (N->getOpcode()) {
9922 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9923 case ISD::EXTRACT_VECTOR_ELT:
9924 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9925 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9926 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9927 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9930 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9931 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
9932 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9934 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9935 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9936 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9937 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9938 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9939 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9945 /// isTypeDesirableForOp - Return true if the target has native support for
9946 /// the specified value type and it is 'desirable' to use the type for the
9947 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9948 /// instruction encodings are longer and some i16 instructions are slow.
9949 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9950 if (!isTypeLegal(VT))
9959 case ISD::SIGN_EXTEND:
9960 case ISD::ZERO_EXTEND:
9961 case ISD::ANY_EXTEND:
9974 static bool MayFoldLoad(SDValue Op) {
9975 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9978 static bool MayFoldIntoStore(SDValue Op) {
9979 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9982 /// IsDesirableToPromoteOp - This method query the target whether it is
9983 /// beneficial for dag combiner to promote the specified node. If true, it
9984 /// should return the desired promotion type by reference.
9985 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9986 EVT VT = Op.getValueType();
9990 bool Promote = false;
9991 bool Commute = false;
9992 switch (Op.getOpcode()) {
9995 LoadSDNode *LD = cast<LoadSDNode>(Op);
9996 // If the non-extending load has a single use and it's not live out, then it
9998 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
10000 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10001 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
10002 // The only case where we'd want to promote LOAD (rather then it being
10003 // promoted as an operand is when it's only use is liveout.
10004 if (UI->getOpcode() != ISD::CopyToReg)
10011 case ISD::SIGN_EXTEND:
10012 case ISD::ZERO_EXTEND:
10013 case ISD::ANY_EXTEND:
10018 SDValue N0 = Op.getOperand(0);
10019 // Look out for (store (shl (load), x)).
10020 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
10033 SDValue N0 = Op.getOperand(0);
10034 SDValue N1 = Op.getOperand(1);
10035 if (!Commute && MayFoldLoad(N1))
10037 // Avoid disabling potential load folding opportunities.
10038 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
10040 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10050 //===----------------------------------------------------------------------===//
10051 // X86 Inline Assembly Support
10052 //===----------------------------------------------------------------------===//
10054 static bool LowerToBSwap(CallInst *CI) {
10055 // FIXME: this should verify that we are targetting a 486 or better. If not,
10056 // we will turn this bswap into something that will be lowered to logical ops
10057 // instead of emitting the bswap asm. For now, we don't support 486 or lower
10058 // so don't worry about this.
10060 // Verify this is a simple bswap.
10061 if (CI->getNumOperands() != 2 ||
10062 CI->getType() != CI->getOperand(1)->getType() ||
10063 !CI->getType()->isIntegerTy())
10066 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10067 if (!Ty || Ty->getBitWidth() % 16 != 0)
10070 // Okay, we can do this xform, do so now.
10071 const Type *Tys[] = { Ty };
10072 Module *M = CI->getParent()->getParent()->getParent();
10073 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10075 Value *Op = CI->getOperand(1);
10076 Op = CallInst::Create(Int, Op, CI->getName(), CI);
10078 CI->replaceAllUsesWith(Op);
10079 CI->eraseFromParent();
10083 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10084 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10085 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10087 std::string AsmStr = IA->getAsmString();
10089 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10090 SmallVector<StringRef, 4> AsmPieces;
10091 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
10093 switch (AsmPieces.size()) {
10094 default: return false;
10096 AsmStr = AsmPieces[0];
10098 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
10101 if (AsmPieces.size() == 2 &&
10102 (AsmPieces[0] == "bswap" ||
10103 AsmPieces[0] == "bswapq" ||
10104 AsmPieces[0] == "bswapl") &&
10105 (AsmPieces[1] == "$0" ||
10106 AsmPieces[1] == "${0:q}")) {
10107 // No need to check constraints, nothing other than the equivalent of
10108 // "=r,0" would be valid here.
10109 return LowerToBSwap(CI);
10111 // rorw $$8, ${0:w} --> llvm.bswap.i16
10112 if (CI->getType()->isIntegerTy(16) &&
10113 AsmPieces.size() == 3 &&
10114 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10115 AsmPieces[1] == "$$8," &&
10116 AsmPieces[2] == "${0:w}" &&
10117 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10119 const std::string &Constraints = IA->getConstraintString();
10120 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10121 std::sort(AsmPieces.begin(), AsmPieces.end());
10122 if (AsmPieces.size() == 4 &&
10123 AsmPieces[0] == "~{cc}" &&
10124 AsmPieces[1] == "~{dirflag}" &&
10125 AsmPieces[2] == "~{flags}" &&
10126 AsmPieces[3] == "~{fpsr}") {
10127 return LowerToBSwap(CI);
10132 if (CI->getType()->isIntegerTy(64) &&
10133 Constraints.size() >= 2 &&
10134 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10135 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10136 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
10137 SmallVector<StringRef, 4> Words;
10138 SplitString(AsmPieces[0], Words, " \t");
10139 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10141 SplitString(AsmPieces[1], Words, " \t");
10142 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10144 SplitString(AsmPieces[2], Words, " \t,");
10145 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10146 Words[2] == "%edx") {
10147 return LowerToBSwap(CI);
10159 /// getConstraintType - Given a constraint letter, return the type of
10160 /// constraint it is for this target.
10161 X86TargetLowering::ConstraintType
10162 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10163 if (Constraint.size() == 1) {
10164 switch (Constraint[0]) {
10176 return C_RegisterClass;
10184 return TargetLowering::getConstraintType(Constraint);
10187 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10188 /// with another that has more specific requirements based on the type of the
10189 /// corresponding operand.
10190 const char *X86TargetLowering::
10191 LowerXConstraint(EVT ConstraintVT) const {
10192 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10193 // 'f' like normal targets.
10194 if (ConstraintVT.isFloatingPoint()) {
10195 if (Subtarget->hasSSE2())
10197 if (Subtarget->hasSSE1())
10201 return TargetLowering::LowerXConstraint(ConstraintVT);
10204 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10205 /// vector. If it is invalid, don't add anything to Ops.
10206 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10209 std::vector<SDValue>&Ops,
10210 SelectionDAG &DAG) const {
10211 SDValue Result(0, 0);
10213 switch (Constraint) {
10216 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10217 if (C->getZExtValue() <= 31) {
10218 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10224 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10225 if (C->getZExtValue() <= 63) {
10226 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10232 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10233 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10234 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10241 if (C->getZExtValue() <= 255) {
10242 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10248 // 32-bit signed value
10249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10250 const ConstantInt *CI = C->getConstantIntValue();
10251 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10252 C->getSExtValue())) {
10253 // Widen to 64 bits here to get it sign extended.
10254 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10257 // FIXME gcc accepts some relocatable values here too, but only in certain
10258 // memory models; it's complicated.
10263 // 32-bit unsigned value
10264 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10265 const ConstantInt *CI = C->getConstantIntValue();
10266 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10267 C->getZExtValue())) {
10268 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10272 // FIXME gcc accepts some relocatable values here too, but only in certain
10273 // memory models; it's complicated.
10277 // Literal immediates are always ok.
10278 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10279 // Widen to 64 bits here to get it sign extended.
10280 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10284 // If we are in non-pic codegen mode, we allow the address of a global (with
10285 // an optional displacement) to be used with 'i'.
10286 GlobalAddressSDNode *GA = 0;
10287 int64_t Offset = 0;
10289 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10291 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10292 Offset += GA->getOffset();
10294 } else if (Op.getOpcode() == ISD::ADD) {
10295 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10296 Offset += C->getZExtValue();
10297 Op = Op.getOperand(0);
10300 } else if (Op.getOpcode() == ISD::SUB) {
10301 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10302 Offset += -C->getZExtValue();
10303 Op = Op.getOperand(0);
10308 // Otherwise, this isn't something we can handle, reject it.
10312 const GlobalValue *GV = GA->getGlobal();
10313 // If we require an extra load to get this address, as in PIC mode, we
10314 // can't accept it.
10315 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10316 getTargetMachine())))
10320 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10322 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10328 if (Result.getNode()) {
10329 Ops.push_back(Result);
10332 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10336 std::vector<unsigned> X86TargetLowering::
10337 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10339 if (Constraint.size() == 1) {
10340 // FIXME: not handling fp-stack yet!
10341 switch (Constraint[0]) { // GCC X86 Constraint Letters
10342 default: break; // Unknown constraint letter
10343 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10344 if (Subtarget->is64Bit()) {
10345 if (VT == MVT::i32)
10346 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10347 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10348 X86::R10D,X86::R11D,X86::R12D,
10349 X86::R13D,X86::R14D,X86::R15D,
10350 X86::EBP, X86::ESP, 0);
10351 else if (VT == MVT::i16)
10352 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10353 X86::SI, X86::DI, X86::R8W,X86::R9W,
10354 X86::R10W,X86::R11W,X86::R12W,
10355 X86::R13W,X86::R14W,X86::R15W,
10356 X86::BP, X86::SP, 0);
10357 else if (VT == MVT::i8)
10358 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10359 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10360 X86::R10B,X86::R11B,X86::R12B,
10361 X86::R13B,X86::R14B,X86::R15B,
10362 X86::BPL, X86::SPL, 0);
10364 else if (VT == MVT::i64)
10365 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10366 X86::RSI, X86::RDI, X86::R8, X86::R9,
10367 X86::R10, X86::R11, X86::R12,
10368 X86::R13, X86::R14, X86::R15,
10369 X86::RBP, X86::RSP, 0);
10373 // 32-bit fallthrough
10374 case 'Q': // Q_REGS
10375 if (VT == MVT::i32)
10376 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10377 else if (VT == MVT::i16)
10378 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10379 else if (VT == MVT::i8)
10380 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10381 else if (VT == MVT::i64)
10382 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10387 return std::vector<unsigned>();
10390 std::pair<unsigned, const TargetRegisterClass*>
10391 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10393 // First, see if this is a constraint that directly corresponds to an LLVM
10395 if (Constraint.size() == 1) {
10396 // GCC Constraint Letters
10397 switch (Constraint[0]) {
10399 case 'r': // GENERAL_REGS
10400 case 'l': // INDEX_REGS
10402 return std::make_pair(0U, X86::GR8RegisterClass);
10403 if (VT == MVT::i16)
10404 return std::make_pair(0U, X86::GR16RegisterClass);
10405 if (VT == MVT::i32 || !Subtarget->is64Bit())
10406 return std::make_pair(0U, X86::GR32RegisterClass);
10407 return std::make_pair(0U, X86::GR64RegisterClass);
10408 case 'R': // LEGACY_REGS
10410 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10411 if (VT == MVT::i16)
10412 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10413 if (VT == MVT::i32 || !Subtarget->is64Bit())
10414 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10415 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10416 case 'f': // FP Stack registers.
10417 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10418 // value to the correct fpstack register class.
10419 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10420 return std::make_pair(0U, X86::RFP32RegisterClass);
10421 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10422 return std::make_pair(0U, X86::RFP64RegisterClass);
10423 return std::make_pair(0U, X86::RFP80RegisterClass);
10424 case 'y': // MMX_REGS if MMX allowed.
10425 if (!Subtarget->hasMMX()) break;
10426 return std::make_pair(0U, X86::VR64RegisterClass);
10427 case 'Y': // SSE_REGS if SSE2 allowed
10428 if (!Subtarget->hasSSE2()) break;
10430 case 'x': // SSE_REGS if SSE1 allowed
10431 if (!Subtarget->hasSSE1()) break;
10433 switch (VT.getSimpleVT().SimpleTy) {
10435 // Scalar SSE types.
10438 return std::make_pair(0U, X86::FR32RegisterClass);
10441 return std::make_pair(0U, X86::FR64RegisterClass);
10449 return std::make_pair(0U, X86::VR128RegisterClass);
10455 // Use the default implementation in TargetLowering to convert the register
10456 // constraint into a member of a register class.
10457 std::pair<unsigned, const TargetRegisterClass*> Res;
10458 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10460 // Not found as a standard register?
10461 if (Res.second == 0) {
10462 // Map st(0) -> st(7) -> ST0
10463 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10464 tolower(Constraint[1]) == 's' &&
10465 tolower(Constraint[2]) == 't' &&
10466 Constraint[3] == '(' &&
10467 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10468 Constraint[5] == ')' &&
10469 Constraint[6] == '}') {
10471 Res.first = X86::ST0+Constraint[4]-'0';
10472 Res.second = X86::RFP80RegisterClass;
10476 // GCC allows "st(0)" to be called just plain "st".
10477 if (StringRef("{st}").equals_lower(Constraint)) {
10478 Res.first = X86::ST0;
10479 Res.second = X86::RFP80RegisterClass;
10484 if (StringRef("{flags}").equals_lower(Constraint)) {
10485 Res.first = X86::EFLAGS;
10486 Res.second = X86::CCRRegisterClass;
10490 // 'A' means EAX + EDX.
10491 if (Constraint == "A") {
10492 Res.first = X86::EAX;
10493 Res.second = X86::GR32_ADRegisterClass;
10499 // Otherwise, check to see if this is a register class of the wrong value
10500 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10501 // turn into {ax},{dx}.
10502 if (Res.second->hasType(VT))
10503 return Res; // Correct type already, nothing to do.
10505 // All of the single-register GCC register classes map their values onto
10506 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10507 // really want an 8-bit or 32-bit register, map to the appropriate register
10508 // class and return the appropriate register.
10509 if (Res.second == X86::GR16RegisterClass) {
10510 if (VT == MVT::i8) {
10511 unsigned DestReg = 0;
10512 switch (Res.first) {
10514 case X86::AX: DestReg = X86::AL; break;
10515 case X86::DX: DestReg = X86::DL; break;
10516 case X86::CX: DestReg = X86::CL; break;
10517 case X86::BX: DestReg = X86::BL; break;
10520 Res.first = DestReg;
10521 Res.second = X86::GR8RegisterClass;
10523 } else if (VT == MVT::i32) {
10524 unsigned DestReg = 0;
10525 switch (Res.first) {
10527 case X86::AX: DestReg = X86::EAX; break;
10528 case X86::DX: DestReg = X86::EDX; break;
10529 case X86::CX: DestReg = X86::ECX; break;
10530 case X86::BX: DestReg = X86::EBX; break;
10531 case X86::SI: DestReg = X86::ESI; break;
10532 case X86::DI: DestReg = X86::EDI; break;
10533 case X86::BP: DestReg = X86::EBP; break;
10534 case X86::SP: DestReg = X86::ESP; break;
10537 Res.first = DestReg;
10538 Res.second = X86::GR32RegisterClass;
10540 } else if (VT == MVT::i64) {
10541 unsigned DestReg = 0;
10542 switch (Res.first) {
10544 case X86::AX: DestReg = X86::RAX; break;
10545 case X86::DX: DestReg = X86::RDX; break;
10546 case X86::CX: DestReg = X86::RCX; break;
10547 case X86::BX: DestReg = X86::RBX; break;
10548 case X86::SI: DestReg = X86::RSI; break;
10549 case X86::DI: DestReg = X86::RDI; break;
10550 case X86::BP: DestReg = X86::RBP; break;
10551 case X86::SP: DestReg = X86::RSP; break;
10554 Res.first = DestReg;
10555 Res.second = X86::GR64RegisterClass;
10558 } else if (Res.second == X86::FR32RegisterClass ||
10559 Res.second == X86::FR64RegisterClass ||
10560 Res.second == X86::VR128RegisterClass) {
10561 // Handle references to XMM physical registers that got mapped into the
10562 // wrong class. This can happen with constraints like {xmm0} where the
10563 // target independent register mapper will just pick the first match it can
10564 // find, ignoring the required type.
10565 if (VT == MVT::f32)
10566 Res.second = X86::FR32RegisterClass;
10567 else if (VT == MVT::f64)
10568 Res.second = X86::FR64RegisterClass;
10569 else if (X86::VR128RegisterClass->hasType(VT))
10570 Res.second = X86::VR128RegisterClass;