1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalAlias.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/VectorExtras.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/raw_ostream.h"
48 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
50 // Forward declarations.
51 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
54 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
55 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
56 default: llvm_unreachable("unknown subtarget type");
57 case X86Subtarget::isDarwin:
58 return new TargetLoweringObjectFileMachO();
59 case X86Subtarget::isELF:
60 return new TargetLoweringObjectFileELF();
61 case X86Subtarget::isMingw:
62 case X86Subtarget::isCygwin:
63 case X86Subtarget::isWindows:
64 return new TargetLoweringObjectFileCOFF();
69 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
70 : TargetLowering(TM, createTLOF(TM)) {
71 Subtarget = &TM.getSubtarget<X86Subtarget>();
72 X86ScalarSSEf64 = Subtarget->hasSSE2();
73 X86ScalarSSEf32 = Subtarget->hasSSE1();
74 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
76 RegInfo = TM.getRegisterInfo();
79 // Set up the TargetLowering object.
81 // X86 is weird, it always uses i8 for shift amounts and setcc results.
82 setShiftAmountType(MVT::i8);
83 setBooleanContents(ZeroOrOneBooleanContent);
84 setSchedulingPreference(SchedulingForRegPressure);
85 setStackPointerRegisterToSaveRestore(X86StackPtr);
87 if (Subtarget->isTargetDarwin()) {
88 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
89 setUseUnderscoreSetJmp(false);
90 setUseUnderscoreLongJmp(false);
91 } else if (Subtarget->isTargetMingw()) {
92 // MS runtime is weird: it exports _setjmp, but longjmp!
93 setUseUnderscoreSetJmp(true);
94 setUseUnderscoreLongJmp(false);
96 setUseUnderscoreSetJmp(true);
97 setUseUnderscoreLongJmp(true);
100 // Set up the register classes.
101 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
102 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
103 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
104 if (Subtarget->is64Bit())
105 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
107 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
109 // We don't accept any truncstore of integer registers.
110 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
111 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
112 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
113 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
114 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
115 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
117 // SETOEQ and SETUNE require checking two conditions.
118 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
119 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
120 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
121 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
122 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
123 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
125 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
127 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
128 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
129 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
131 if (Subtarget->is64Bit()) {
132 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
133 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
134 } else if (!UseSoftFloat) {
135 if (X86ScalarSSEf64) {
136 // We have an impenetrably clever algorithm for ui64->double only.
137 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
139 // We have an algorithm for SSE2, and we turn this into a 64-bit
140 // FILD for other targets.
141 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
144 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
146 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
147 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
150 // SSE has no i16 to fp conversion, only i32
151 if (X86ScalarSSEf32) {
152 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
153 // f32 and f64 cases are Legal, f80 case is not
154 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
156 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
157 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
160 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
161 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
164 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
165 // are Legal, f80 is custom lowered.
166 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
167 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
169 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
171 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
172 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
174 if (X86ScalarSSEf32) {
175 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
176 // f32 and f64 cases are Legal, f80 case is not
177 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
179 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
180 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
183 // Handle FP_TO_UINT by promoting the destination to a larger signed
185 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
186 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
187 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
189 if (Subtarget->is64Bit()) {
190 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
191 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
192 } else if (!UseSoftFloat) {
193 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
194 // Expand FP_TO_UINT into a select.
195 // FIXME: We would like to use a Custom expander here eventually to do
196 // the optimal thing for SSE vs. the default expansion in the legalizer.
197 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
199 // With SSE3 we can use fisttpll to convert to a signed i64; without
200 // SSE, we're stuck with a fistpll.
201 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
204 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
205 if (!X86ScalarSSEf64) {
206 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
207 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
210 // Scalar integer divide and remainder are lowered to use operations that
211 // produce two results, to match the available instructions. This exposes
212 // the two-result form to trivial CSE, which is able to combine x/y and x%y
213 // into a single instruction.
215 // Scalar integer multiply-high is also lowered to use two-result
216 // operations, to match the available instructions. However, plain multiply
217 // (low) operations are left as Legal, as there are single-result
218 // instructions for this in x86. Using the two-result multiply instructions
219 // when both high and low results are needed must be arranged by dagcombine.
220 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
221 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
222 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
223 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
224 setOperationAction(ISD::SREM , MVT::i8 , Expand);
225 setOperationAction(ISD::UREM , MVT::i8 , Expand);
226 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
227 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
228 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
229 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
230 setOperationAction(ISD::SREM , MVT::i16 , Expand);
231 setOperationAction(ISD::UREM , MVT::i16 , Expand);
232 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
233 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
234 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
235 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
236 setOperationAction(ISD::SREM , MVT::i32 , Expand);
237 setOperationAction(ISD::UREM , MVT::i32 , Expand);
238 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
239 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
240 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
241 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
242 setOperationAction(ISD::SREM , MVT::i64 , Expand);
243 setOperationAction(ISD::UREM , MVT::i64 , Expand);
245 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
246 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
247 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
248 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
249 if (Subtarget->is64Bit())
250 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
251 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
252 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
253 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
254 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
255 setOperationAction(ISD::FREM , MVT::f32 , Expand);
256 setOperationAction(ISD::FREM , MVT::f64 , Expand);
257 setOperationAction(ISD::FREM , MVT::f80 , Expand);
258 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
260 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
261 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
262 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
263 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
264 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
265 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
266 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
267 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
268 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
269 if (Subtarget->is64Bit()) {
270 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
271 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
272 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
275 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
276 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
278 // These should be promoted to a larger select which is supported.
279 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
280 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
281 // X86 wants to expand cmov itself.
282 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
283 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
284 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
285 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
286 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
287 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
288 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
289 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
290 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
291 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
292 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
293 if (Subtarget->is64Bit()) {
294 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
295 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
297 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
300 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
301 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
302 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
303 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
304 if (Subtarget->is64Bit())
305 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
306 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
307 if (Subtarget->is64Bit()) {
308 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
309 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
310 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
311 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
313 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
314 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
315 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
316 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
317 if (Subtarget->is64Bit()) {
318 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
319 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
320 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
323 if (Subtarget->hasSSE1())
324 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
326 if (!Subtarget->hasSSE2())
327 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
329 // Expand certain atomics
330 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
331 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
332 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
333 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
335 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
336 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
337 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
338 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
340 if (!Subtarget->is64Bit()) {
341 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
342 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
343 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
344 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
345 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
346 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
347 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
350 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
351 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
352 // FIXME - use subtarget debug flags
353 if (!Subtarget->isTargetDarwin() &&
354 !Subtarget->isTargetELF() &&
355 !Subtarget->isTargetCygMing()) {
356 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
357 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
360 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
361 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
362 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
363 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
364 if (Subtarget->is64Bit()) {
365 setExceptionPointerRegister(X86::RAX);
366 setExceptionSelectorRegister(X86::RDX);
368 setExceptionPointerRegister(X86::EAX);
369 setExceptionSelectorRegister(X86::EDX);
371 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
372 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
374 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
376 setOperationAction(ISD::TRAP, MVT::Other, Legal);
378 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
379 setOperationAction(ISD::VASTART , MVT::Other, Custom);
380 setOperationAction(ISD::VAEND , MVT::Other, Expand);
381 if (Subtarget->is64Bit()) {
382 setOperationAction(ISD::VAARG , MVT::Other, Custom);
383 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
385 setOperationAction(ISD::VAARG , MVT::Other, Expand);
386 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
389 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
390 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
391 if (Subtarget->is64Bit())
392 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
393 if (Subtarget->isTargetCygMing())
394 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
396 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
398 if (!UseSoftFloat && X86ScalarSSEf64) {
399 // f32 and f64 use SSE.
400 // Set up the FP register classes.
401 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
402 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
404 // Use ANDPD to simulate FABS.
405 setOperationAction(ISD::FABS , MVT::f64, Custom);
406 setOperationAction(ISD::FABS , MVT::f32, Custom);
408 // Use XORP to simulate FNEG.
409 setOperationAction(ISD::FNEG , MVT::f64, Custom);
410 setOperationAction(ISD::FNEG , MVT::f32, Custom);
412 // Use ANDPD and ORPD to simulate FCOPYSIGN.
413 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
414 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
416 // We don't support sin/cos/fmod
417 setOperationAction(ISD::FSIN , MVT::f64, Expand);
418 setOperationAction(ISD::FCOS , MVT::f64, Expand);
419 setOperationAction(ISD::FSIN , MVT::f32, Expand);
420 setOperationAction(ISD::FCOS , MVT::f32, Expand);
422 // Expand FP immediates into loads from the stack, except for the special
424 addLegalFPImmediate(APFloat(+0.0)); // xorpd
425 addLegalFPImmediate(APFloat(+0.0f)); // xorps
426 } else if (!UseSoftFloat && X86ScalarSSEf32) {
427 // Use SSE for f32, x87 for f64.
428 // Set up the FP register classes.
429 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
430 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
432 // Use ANDPS to simulate FABS.
433 setOperationAction(ISD::FABS , MVT::f32, Custom);
435 // Use XORP to simulate FNEG.
436 setOperationAction(ISD::FNEG , MVT::f32, Custom);
438 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
440 // Use ANDPS and ORPS to simulate FCOPYSIGN.
441 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
442 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
444 // We don't support sin/cos/fmod
445 setOperationAction(ISD::FSIN , MVT::f32, Expand);
446 setOperationAction(ISD::FCOS , MVT::f32, Expand);
448 // Special cases we handle for FP constants.
449 addLegalFPImmediate(APFloat(+0.0f)); // xorps
450 addLegalFPImmediate(APFloat(+0.0)); // FLD0
451 addLegalFPImmediate(APFloat(+1.0)); // FLD1
452 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
453 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
456 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
457 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
459 } else if (!UseSoftFloat) {
460 // f32 and f64 in x87.
461 // Set up the FP register classes.
462 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
463 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
465 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
466 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
467 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
468 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
471 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
472 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
474 addLegalFPImmediate(APFloat(+0.0)); // FLD0
475 addLegalFPImmediate(APFloat(+1.0)); // FLD1
476 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
477 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
478 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
479 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
480 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
481 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
484 // Long double always uses X87.
486 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
487 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
488 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
491 APFloat TmpFlt(+0.0);
492 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
494 addLegalFPImmediate(TmpFlt); // FLD0
496 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
497 APFloat TmpFlt2(+1.0);
498 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
500 addLegalFPImmediate(TmpFlt2); // FLD1
501 TmpFlt2.changeSign();
502 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
506 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
507 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
511 // Always use a library call for pow.
512 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
513 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
514 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
516 setOperationAction(ISD::FLOG, MVT::f80, Expand);
517 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
518 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
519 setOperationAction(ISD::FEXP, MVT::f80, Expand);
520 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
522 // First set operation action for all vector types to either promote
523 // (for widening) or expand (for scalarization). Then we will selectively
524 // turn on ones that can be effectively codegen'd.
525 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
526 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
527 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
542 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
543 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
577 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
578 // with -msoft-float, disable use of MMX as well.
579 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
580 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
581 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
582 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
583 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
584 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
586 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
587 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
588 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
589 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
591 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
592 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
593 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
594 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
596 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
597 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
599 setOperationAction(ISD::AND, MVT::v8i8, Promote);
600 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
601 setOperationAction(ISD::AND, MVT::v4i16, Promote);
602 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
603 setOperationAction(ISD::AND, MVT::v2i32, Promote);
604 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
605 setOperationAction(ISD::AND, MVT::v1i64, Legal);
607 setOperationAction(ISD::OR, MVT::v8i8, Promote);
608 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
609 setOperationAction(ISD::OR, MVT::v4i16, Promote);
610 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
611 setOperationAction(ISD::OR, MVT::v2i32, Promote);
612 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
613 setOperationAction(ISD::OR, MVT::v1i64, Legal);
615 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
616 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
617 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
618 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
619 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
620 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
621 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
623 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
624 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
625 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
626 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
627 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
628 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
629 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
630 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
631 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
633 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
634 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
635 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
636 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
637 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
639 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
640 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
641 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
642 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
644 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
645 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
646 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
647 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
649 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
651 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
652 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
653 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
654 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
655 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
656 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
657 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
658 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
659 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
662 if (!UseSoftFloat && Subtarget->hasSSE1()) {
663 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
665 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
666 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
667 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
668 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
669 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
670 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
671 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
672 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
673 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
674 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
675 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
676 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
679 if (!UseSoftFloat && Subtarget->hasSSE2()) {
680 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
682 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
683 // registers cannot be used even for integer operations.
684 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
685 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
686 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
687 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
689 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
690 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
691 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
692 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
693 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
694 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
695 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
696 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
697 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
698 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
699 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
700 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
701 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
702 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
703 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
704 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
706 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
707 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
708 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
709 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
711 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
712 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
713 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
714 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
715 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
717 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
718 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
719 EVT VT = (MVT::SimpleValueType)i;
720 // Do not attempt to custom lower non-power-of-2 vectors
721 if (!isPowerOf2_32(VT.getVectorNumElements()))
723 // Do not attempt to custom lower non-128-bit vectors
724 if (!VT.is128BitVector())
726 setOperationAction(ISD::BUILD_VECTOR,
727 VT.getSimpleVT().SimpleTy, Custom);
728 setOperationAction(ISD::VECTOR_SHUFFLE,
729 VT.getSimpleVT().SimpleTy, Custom);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
731 VT.getSimpleVT().SimpleTy, Custom);
734 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
735 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
736 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
737 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
739 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
741 if (Subtarget->is64Bit()) {
742 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
743 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
746 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
747 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
748 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
751 // Do not attempt to promote non-128-bit vectors
752 if (!VT.is128BitVector()) {
755 setOperationAction(ISD::AND, SVT, Promote);
756 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
757 setOperationAction(ISD::OR, SVT, Promote);
758 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
759 setOperationAction(ISD::XOR, SVT, Promote);
760 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
761 setOperationAction(ISD::LOAD, SVT, Promote);
762 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
763 setOperationAction(ISD::SELECT, SVT, Promote);
764 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
767 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
769 // Custom lower v2i64 and v2f64 selects.
770 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
771 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
772 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
773 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
775 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
776 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
777 if (!DisableMMX && Subtarget->hasMMX()) {
778 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
779 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
783 if (Subtarget->hasSSE41()) {
784 // FIXME: Do we need to handle scalar-to-vector here?
785 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
787 // i8 and i16 vectors are custom , because the source register and source
788 // source memory operand types are not the same width. f32 vectors are
789 // custom since the immediate controlling the insert encodes additional
791 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
792 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
793 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
794 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
796 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
797 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
798 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
799 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801 if (Subtarget->is64Bit()) {
802 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
803 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
807 if (Subtarget->hasSSE42()) {
808 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
811 if (!UseSoftFloat && Subtarget->hasAVX()) {
812 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
813 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
814 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
815 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
817 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
818 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
819 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
820 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
821 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
822 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
823 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
824 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
825 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
826 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
827 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
828 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
829 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
830 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
831 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
833 // Operations to consider commented out -v16i16 v32i8
834 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
835 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
836 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
837 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
838 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
839 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
840 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
841 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
842 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
843 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
844 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
845 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
846 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
847 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
849 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
850 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
851 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
852 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
854 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
855 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
856 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
857 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
858 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
860 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
861 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
862 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
863 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
865 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
868 // Not sure we want to do this since there are no 256-bit integer
871 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
872 // This includes 256-bit vectors
873 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
874 EVT VT = (MVT::SimpleValueType)i;
876 // Do not attempt to custom lower non-power-of-2 vectors
877 if (!isPowerOf2_32(VT.getVectorNumElements()))
880 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
881 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
882 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
885 if (Subtarget->is64Bit()) {
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
892 // Not sure we want to do this since there are no 256-bit integer
895 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
896 // Including 256-bit vectors
897 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
898 EVT VT = (MVT::SimpleValueType)i;
900 if (!VT.is256BitVector()) {
903 setOperationAction(ISD::AND, VT, Promote);
904 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
905 setOperationAction(ISD::OR, VT, Promote);
906 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
907 setOperationAction(ISD::XOR, VT, Promote);
908 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
909 setOperationAction(ISD::LOAD, VT, Promote);
910 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
911 setOperationAction(ISD::SELECT, VT, Promote);
912 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
915 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
919 // We want to custom lower some of our intrinsics.
920 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
922 // Add/Sub/Mul with overflow operations are custom lowered.
923 setOperationAction(ISD::SADDO, MVT::i32, Custom);
924 setOperationAction(ISD::SADDO, MVT::i64, Custom);
925 setOperationAction(ISD::UADDO, MVT::i32, Custom);
926 setOperationAction(ISD::UADDO, MVT::i64, Custom);
927 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
928 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
929 setOperationAction(ISD::USUBO, MVT::i32, Custom);
930 setOperationAction(ISD::USUBO, MVT::i64, Custom);
931 setOperationAction(ISD::SMULO, MVT::i32, Custom);
932 setOperationAction(ISD::SMULO, MVT::i64, Custom);
934 if (!Subtarget->is64Bit()) {
935 // These libcalls are not available in 32-bit.
936 setLibcallName(RTLIB::SHL_I128, 0);
937 setLibcallName(RTLIB::SRL_I128, 0);
938 setLibcallName(RTLIB::SRA_I128, 0);
941 // We have target-specific dag combine patterns for the following nodes:
942 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
943 setTargetDAGCombine(ISD::BUILD_VECTOR);
944 setTargetDAGCombine(ISD::SELECT);
945 setTargetDAGCombine(ISD::SHL);
946 setTargetDAGCombine(ISD::SRA);
947 setTargetDAGCombine(ISD::SRL);
948 setTargetDAGCombine(ISD::STORE);
949 setTargetDAGCombine(ISD::MEMBARRIER);
950 if (Subtarget->is64Bit())
951 setTargetDAGCombine(ISD::MUL);
953 computeRegisterProperties();
955 // FIXME: These should be based on subtarget info. Plus, the values should
956 // be smaller when we are in optimizing for size mode.
957 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
958 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
959 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
960 setPrefLoopAlignment(16);
961 benefitFromCodePlacementOpt = true;
965 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
970 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
971 /// the desired ByVal argument alignment.
972 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
975 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
976 if (VTy->getBitWidth() == 128)
978 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
979 unsigned EltAlign = 0;
980 getMaxByValAlign(ATy->getElementType(), EltAlign);
981 if (EltAlign > MaxAlign)
983 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
984 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
985 unsigned EltAlign = 0;
986 getMaxByValAlign(STy->getElementType(i), EltAlign);
987 if (EltAlign > MaxAlign)
996 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
997 /// function arguments in the caller parameter area. For X86, aggregates
998 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
999 /// are at 4-byte boundaries.
1000 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1001 if (Subtarget->is64Bit()) {
1002 // Max of 8 and alignment of type.
1003 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1010 if (Subtarget->hasSSE1())
1011 getMaxByValAlign(Ty, Align);
1015 /// getOptimalMemOpType - Returns the target specific optimal type for load
1016 /// and store operations as a result of memset, memcpy, and memmove
1017 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1020 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1021 bool isSrcConst, bool isSrcStr,
1022 SelectionDAG &DAG) const {
1023 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1024 // linux. This is because the stack realignment code can't handle certain
1025 // cases like PR2962. This should be removed when PR2962 is fixed.
1026 const Function *F = DAG.getMachineFunction().getFunction();
1027 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1028 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1029 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1031 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1034 if (Subtarget->is64Bit() && Size >= 8)
1039 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1041 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1042 SelectionDAG &DAG) const {
1043 if (usesGlobalOffsetTable())
1044 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1045 if (!Subtarget->is64Bit())
1046 // This doesn't have DebugLoc associated with it, but is not really the
1047 // same as a Register.
1048 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1053 /// getFunctionAlignment - Return the Log2 alignment of this function.
1054 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1055 return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 4;
1058 //===----------------------------------------------------------------------===//
1059 // Return Value Calling Convention Implementation
1060 //===----------------------------------------------------------------------===//
1062 #include "X86GenCallingConv.inc"
1065 X86TargetLowering::LowerReturn(SDValue Chain,
1066 unsigned CallConv, bool isVarArg,
1067 const SmallVectorImpl<ISD::OutputArg> &Outs,
1068 DebugLoc dl, SelectionDAG &DAG) {
1070 SmallVector<CCValAssign, 16> RVLocs;
1071 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1072 RVLocs, *DAG.getContext());
1073 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1075 // If this is the first return lowered for this function, add the regs to the
1076 // liveout set for the function.
1077 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1078 for (unsigned i = 0; i != RVLocs.size(); ++i)
1079 if (RVLocs[i].isRegLoc())
1080 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1085 SmallVector<SDValue, 6> RetOps;
1086 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1087 // Operand #1 = Bytes To Pop
1088 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1090 // Copy the result values into the output registers.
1091 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1092 CCValAssign &VA = RVLocs[i];
1093 assert(VA.isRegLoc() && "Can only return in registers!");
1094 SDValue ValToCopy = Outs[i].Val;
1096 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1097 // the RET instruction and handled by the FP Stackifier.
1098 if (VA.getLocReg() == X86::ST0 ||
1099 VA.getLocReg() == X86::ST1) {
1100 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1101 // change the value to the FP stack register class.
1102 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1103 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1104 RetOps.push_back(ValToCopy);
1105 // Don't emit a copytoreg.
1109 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1110 // which is returned in RAX / RDX.
1111 if (Subtarget->is64Bit()) {
1112 EVT ValVT = ValToCopy.getValueType();
1113 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1114 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1115 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1116 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1120 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1121 Flag = Chain.getValue(1);
1124 // The x86-64 ABI for returning structs by value requires that we copy
1125 // the sret argument into %rax for the return. We saved the argument into
1126 // a virtual register in the entry block, so now we copy the value out
1128 if (Subtarget->is64Bit() &&
1129 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1130 MachineFunction &MF = DAG.getMachineFunction();
1131 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1132 unsigned Reg = FuncInfo->getSRetReturnReg();
1134 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1135 FuncInfo->setSRetReturnReg(Reg);
1137 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1139 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1140 Flag = Chain.getValue(1);
1143 RetOps[0] = Chain; // Update chain.
1145 // Add the flag if we have it.
1147 RetOps.push_back(Flag);
1149 return DAG.getNode(X86ISD::RET_FLAG, dl,
1150 MVT::Other, &RetOps[0], RetOps.size());
1153 /// LowerCallResult - Lower the result values of a call into the
1154 /// appropriate copies out of appropriate physical registers.
1157 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1158 unsigned CallConv, bool isVarArg,
1159 const SmallVectorImpl<ISD::InputArg> &Ins,
1160 DebugLoc dl, SelectionDAG &DAG,
1161 SmallVectorImpl<SDValue> &InVals) {
1163 // Assign locations to each value returned by this call.
1164 SmallVector<CCValAssign, 16> RVLocs;
1165 bool Is64Bit = Subtarget->is64Bit();
1166 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1167 RVLocs, *DAG.getContext());
1168 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1170 // Copy all of the result registers out of their specified physreg.
1171 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1172 CCValAssign &VA = RVLocs[i];
1173 EVT CopyVT = VA.getValVT();
1175 // If this is x86-64, and we disabled SSE, we can't return FP values
1176 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1177 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1178 llvm_report_error("SSE register return with SSE disabled");
1181 // If this is a call to a function that returns an fp value on the floating
1182 // point stack, but where we prefer to use the value in xmm registers, copy
1183 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1184 if ((VA.getLocReg() == X86::ST0 ||
1185 VA.getLocReg() == X86::ST1) &&
1186 isScalarFPTypeInSSEReg(VA.getValVT())) {
1191 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1192 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1193 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1194 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1195 MVT::v2i64, InFlag).getValue(1);
1196 Val = Chain.getValue(0);
1197 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1198 Val, DAG.getConstant(0, MVT::i64));
1200 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1201 MVT::i64, InFlag).getValue(1);
1202 Val = Chain.getValue(0);
1204 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1206 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1207 CopyVT, InFlag).getValue(1);
1208 Val = Chain.getValue(0);
1210 InFlag = Chain.getValue(2);
1212 if (CopyVT != VA.getValVT()) {
1213 // Round the F80 the right size, which also moves to the appropriate xmm
1215 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1216 // This truncation won't change the value.
1217 DAG.getIntPtrConstant(1));
1220 InVals.push_back(Val);
1227 //===----------------------------------------------------------------------===//
1228 // C & StdCall & Fast Calling Convention implementation
1229 //===----------------------------------------------------------------------===//
1230 // StdCall calling convention seems to be standard for many Windows' API
1231 // routines and around. It differs from C calling convention just a little:
1232 // callee should clean up the stack, not caller. Symbols should be also
1233 // decorated in some fancy way :) It doesn't support any vector arguments.
1234 // For info on fast calling convention see Fast Calling Convention (tail call)
1235 // implementation LowerX86_32FastCCCallTo.
1237 /// CallIsStructReturn - Determines whether a call uses struct return
1239 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1243 return Outs[0].Flags.isSRet();
1246 /// ArgsAreStructReturn - Determines whether a function uses struct
1247 /// return semantics.
1249 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1253 return Ins[0].Flags.isSRet();
1256 /// IsCalleePop - Determines whether the callee is required to pop its
1257 /// own arguments. Callee pop is necessary to support tail calls.
1258 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1262 switch (CallingConv) {
1265 case CallingConv::X86_StdCall:
1266 return !Subtarget->is64Bit();
1267 case CallingConv::X86_FastCall:
1268 return !Subtarget->is64Bit();
1269 case CallingConv::Fast:
1270 return PerformTailCallOpt;
1274 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1275 /// given CallingConvention value.
1276 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1277 if (Subtarget->is64Bit()) {
1278 if (Subtarget->isTargetWin64())
1279 return CC_X86_Win64_C;
1284 if (CC == CallingConv::X86_FastCall)
1285 return CC_X86_32_FastCall;
1286 else if (CC == CallingConv::Fast)
1287 return CC_X86_32_FastCC;
1292 /// NameDecorationForCallConv - Selects the appropriate decoration to
1293 /// apply to a MachineFunction containing a given calling convention.
1295 X86TargetLowering::NameDecorationForCallConv(unsigned CallConv) {
1296 if (CallConv == CallingConv::X86_FastCall)
1298 else if (CallConv == CallingConv::X86_StdCall)
1304 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1305 /// by "Src" to address "Dst" with size and alignment information specified by
1306 /// the specific parameter attribute. The copy will be passed as a byval
1307 /// function parameter.
1309 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1310 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1312 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1313 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1314 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1318 X86TargetLowering::LowerMemArgument(SDValue Chain,
1320 const SmallVectorImpl<ISD::InputArg> &Ins,
1321 DebugLoc dl, SelectionDAG &DAG,
1322 const CCValAssign &VA,
1323 MachineFrameInfo *MFI,
1326 // Create the nodes corresponding to a load from this parameter slot.
1327 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1328 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1329 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1332 // If value is passed by pointer we have address passed instead of the value
1334 if (VA.getLocInfo() == CCValAssign::Indirect)
1335 ValVT = VA.getLocVT();
1337 ValVT = VA.getValVT();
1339 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1340 // changed with more analysis.
1341 // In case of tail call optimization mark all arguments mutable. Since they
1342 // could be overwritten by lowering of arguments in case of a tail call.
1343 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1344 VA.getLocMemOffset(), isImmutable);
1345 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1346 if (Flags.isByVal())
1348 return DAG.getLoad(ValVT, dl, Chain, FIN,
1349 PseudoSourceValue::getFixedStack(FI), 0);
1353 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1356 const SmallVectorImpl<ISD::InputArg> &Ins,
1359 SmallVectorImpl<SDValue> &InVals) {
1361 MachineFunction &MF = DAG.getMachineFunction();
1362 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1364 const Function* Fn = MF.getFunction();
1365 if (Fn->hasExternalLinkage() &&
1366 Subtarget->isTargetCygMing() &&
1367 Fn->getName() == "main")
1368 FuncInfo->setForceFramePointer(true);
1370 // Decorate the function name.
1371 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1373 MachineFrameInfo *MFI = MF.getFrameInfo();
1374 bool Is64Bit = Subtarget->is64Bit();
1375 bool IsWin64 = Subtarget->isTargetWin64();
1377 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1378 "Var args not supported with calling convention fastcc");
1380 // Assign locations to all of the incoming arguments.
1381 SmallVector<CCValAssign, 16> ArgLocs;
1382 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1383 ArgLocs, *DAG.getContext());
1384 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1386 unsigned LastVal = ~0U;
1388 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1389 CCValAssign &VA = ArgLocs[i];
1390 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1392 assert(VA.getValNo() != LastVal &&
1393 "Don't support value assigned to multiple locs yet");
1394 LastVal = VA.getValNo();
1396 if (VA.isRegLoc()) {
1397 EVT RegVT = VA.getLocVT();
1398 TargetRegisterClass *RC = NULL;
1399 if (RegVT == MVT::i32)
1400 RC = X86::GR32RegisterClass;
1401 else if (Is64Bit && RegVT == MVT::i64)
1402 RC = X86::GR64RegisterClass;
1403 else if (RegVT == MVT::f32)
1404 RC = X86::FR32RegisterClass;
1405 else if (RegVT == MVT::f64)
1406 RC = X86::FR64RegisterClass;
1407 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1408 RC = X86::VR128RegisterClass;
1409 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1410 RC = X86::VR64RegisterClass;
1412 llvm_unreachable("Unknown argument type!");
1414 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1415 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1417 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1418 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1420 if (VA.getLocInfo() == CCValAssign::SExt)
1421 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1422 DAG.getValueType(VA.getValVT()));
1423 else if (VA.getLocInfo() == CCValAssign::ZExt)
1424 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1425 DAG.getValueType(VA.getValVT()));
1426 else if (VA.getLocInfo() == CCValAssign::BCvt)
1427 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1429 if (VA.isExtInLoc()) {
1430 // Handle MMX values passed in XMM regs.
1431 if (RegVT.isVector()) {
1432 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1433 ArgValue, DAG.getConstant(0, MVT::i64));
1434 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1436 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1439 assert(VA.isMemLoc());
1440 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1443 // If value is passed via pointer - do a load.
1444 if (VA.getLocInfo() == CCValAssign::Indirect)
1445 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1447 InVals.push_back(ArgValue);
1450 // The x86-64 ABI for returning structs by value requires that we copy
1451 // the sret argument into %rax for the return. Save the argument into
1452 // a virtual register so that we can access it from the return points.
1453 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1454 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1455 unsigned Reg = FuncInfo->getSRetReturnReg();
1457 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1458 FuncInfo->setSRetReturnReg(Reg);
1460 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1461 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1464 unsigned StackSize = CCInfo.getNextStackOffset();
1465 // align stack specially for tail calls
1466 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1467 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1469 // If the function takes variable number of arguments, make a frame index for
1470 // the start of the first vararg value... for expansion of llvm.va_start.
1472 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1473 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1476 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1478 // FIXME: We should really autogenerate these arrays
1479 static const unsigned GPR64ArgRegsWin64[] = {
1480 X86::RCX, X86::RDX, X86::R8, X86::R9
1482 static const unsigned XMMArgRegsWin64[] = {
1483 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1485 static const unsigned GPR64ArgRegs64Bit[] = {
1486 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1488 static const unsigned XMMArgRegs64Bit[] = {
1489 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1490 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1492 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1495 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1496 GPR64ArgRegs = GPR64ArgRegsWin64;
1497 XMMArgRegs = XMMArgRegsWin64;
1499 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1500 GPR64ArgRegs = GPR64ArgRegs64Bit;
1501 XMMArgRegs = XMMArgRegs64Bit;
1503 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1505 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1508 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1509 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1510 "SSE register cannot be used when SSE is disabled!");
1511 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1512 "SSE register cannot be used when SSE is disabled!");
1513 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1514 // Kernel mode asks for SSE to be disabled, so don't push them
1516 TotalNumXMMRegs = 0;
1518 // For X86-64, if there are vararg parameters that are passed via
1519 // registers, then we must store them to their spots on the stack so they
1520 // may be loaded by deferencing the result of va_next.
1521 VarArgsGPOffset = NumIntRegs * 8;
1522 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1523 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1524 TotalNumXMMRegs * 16, 16);
1526 // Store the integer parameter registers.
1527 SmallVector<SDValue, 8> MemOps;
1528 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1529 unsigned Offset = VarArgsGPOffset;
1530 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1531 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1532 DAG.getIntPtrConstant(Offset));
1533 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1534 X86::GR64RegisterClass);
1535 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1537 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1538 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1540 MemOps.push_back(Store);
1544 if (!MemOps.empty())
1545 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1546 &MemOps[0], MemOps.size());
1548 // Now store the XMM (fp + vector) parameter registers.
1549 SmallVector<SDValue, 11> SaveXMMOps;
1550 SaveXMMOps.push_back(Chain);
1552 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1553 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1554 SaveXMMOps.push_back(ALVal);
1556 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1557 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1559 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1560 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1561 X86::VR128RegisterClass);
1562 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1563 SaveXMMOps.push_back(Val);
1565 Chain = DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, MVT::Other,
1566 &SaveXMMOps[0], SaveXMMOps.size());
1570 // Some CCs need callee pop.
1571 if (IsCalleePop(isVarArg, CallConv)) {
1572 BytesToPopOnReturn = StackSize; // Callee pops everything.
1573 BytesCallerReserves = 0;
1575 BytesToPopOnReturn = 0; // Callee pops nothing.
1576 // If this is an sret function, the return should pop the hidden pointer.
1577 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1578 BytesToPopOnReturn = 4;
1579 BytesCallerReserves = StackSize;
1583 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1584 if (CallConv == CallingConv::X86_FastCall)
1585 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1588 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1594 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1595 SDValue StackPtr, SDValue Arg,
1596 DebugLoc dl, SelectionDAG &DAG,
1597 const CCValAssign &VA,
1598 ISD::ArgFlagsTy Flags) {
1599 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1600 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1601 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1602 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1603 if (Flags.isByVal()) {
1604 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1606 return DAG.getStore(Chain, dl, Arg, PtrOff,
1607 PseudoSourceValue::getStack(), LocMemOffset);
1610 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1611 /// optimization is performed and it is required.
1613 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1614 SDValue &OutRetAddr,
1620 if (!IsTailCall || FPDiff==0) return Chain;
1622 // Adjust the Return address stack slot.
1623 EVT VT = getPointerTy();
1624 OutRetAddr = getReturnAddressFrameIndex(DAG);
1626 // Load the "old" Return address.
1627 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1628 return SDValue(OutRetAddr.getNode(), 1);
1631 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1632 /// optimization is performed and it is required (FPDiff!=0).
1634 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1635 SDValue Chain, SDValue RetAddrFrIdx,
1636 bool Is64Bit, int FPDiff, DebugLoc dl) {
1637 // Store the return address to the appropriate stack slot.
1638 if (!FPDiff) return Chain;
1639 // Calculate the new stack slot for the return address.
1640 int SlotSize = Is64Bit ? 8 : 4;
1641 int NewReturnAddrFI =
1642 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1643 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1644 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1645 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1646 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1651 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1652 unsigned CallConv, bool isVarArg, bool isTailCall,
1653 const SmallVectorImpl<ISD::OutputArg> &Outs,
1654 const SmallVectorImpl<ISD::InputArg> &Ins,
1655 DebugLoc dl, SelectionDAG &DAG,
1656 SmallVectorImpl<SDValue> &InVals) {
1658 MachineFunction &MF = DAG.getMachineFunction();
1659 bool Is64Bit = Subtarget->is64Bit();
1660 bool IsStructRet = CallIsStructReturn(Outs);
1662 assert((!isTailCall ||
1663 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1664 "IsEligibleForTailCallOptimization missed a case!");
1665 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1666 "Var args not supported with calling convention fastcc");
1668 // Analyze operands of the call, assigning locations to each operand.
1669 SmallVector<CCValAssign, 16> ArgLocs;
1670 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1671 ArgLocs, *DAG.getContext());
1672 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1674 // Get a count of how many bytes are to be pushed on the stack.
1675 unsigned NumBytes = CCInfo.getNextStackOffset();
1676 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1677 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1681 // Lower arguments at fp - stackoffset + fpdiff.
1682 unsigned NumBytesCallerPushed =
1683 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1684 FPDiff = NumBytesCallerPushed - NumBytes;
1686 // Set the delta of movement of the returnaddr stackslot.
1687 // But only set if delta is greater than previous delta.
1688 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1689 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1692 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1694 SDValue RetAddrFrIdx;
1695 // Load return adress for tail calls.
1696 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1699 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1700 SmallVector<SDValue, 8> MemOpChains;
1703 // Walk the register/memloc assignments, inserting copies/loads. In the case
1704 // of tail call optimization arguments are handle later.
1705 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1706 CCValAssign &VA = ArgLocs[i];
1707 EVT RegVT = VA.getLocVT();
1708 SDValue Arg = Outs[i].Val;
1709 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1710 bool isByVal = Flags.isByVal();
1712 // Promote the value if needed.
1713 switch (VA.getLocInfo()) {
1714 default: llvm_unreachable("Unknown loc info!");
1715 case CCValAssign::Full: break;
1716 case CCValAssign::SExt:
1717 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1719 case CCValAssign::ZExt:
1720 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1722 case CCValAssign::AExt:
1723 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1724 // Special case: passing MMX values in XMM registers.
1725 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1726 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1727 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1729 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1731 case CCValAssign::BCvt:
1732 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1734 case CCValAssign::Indirect: {
1735 // Store the argument.
1736 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1737 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1738 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1739 PseudoSourceValue::getFixedStack(FI), 0);
1745 if (VA.isRegLoc()) {
1746 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1748 if (!isTailCall || (isTailCall && isByVal)) {
1749 assert(VA.isMemLoc());
1750 if (StackPtr.getNode() == 0)
1751 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1753 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1754 dl, DAG, VA, Flags));
1759 if (!MemOpChains.empty())
1760 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1761 &MemOpChains[0], MemOpChains.size());
1763 // Build a sequence of copy-to-reg nodes chained together with token chain
1764 // and flag operands which copy the outgoing args into registers.
1766 // Tail call byval lowering might overwrite argument registers so in case of
1767 // tail call optimization the copies to registers are lowered later.
1769 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1770 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1771 RegsToPass[i].second, InFlag);
1772 InFlag = Chain.getValue(1);
1776 if (Subtarget->isPICStyleGOT()) {
1777 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1780 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1781 DAG.getNode(X86ISD::GlobalBaseReg,
1782 DebugLoc::getUnknownLoc(),
1785 InFlag = Chain.getValue(1);
1787 // If we are tail calling and generating PIC/GOT style code load the
1788 // address of the callee into ECX. The value in ecx is used as target of
1789 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1790 // for tail calls on PIC/GOT architectures. Normally we would just put the
1791 // address of GOT into ebx and then call target@PLT. But for tail calls
1792 // ebx would be restored (since ebx is callee saved) before jumping to the
1795 // Note: The actual moving to ECX is done further down.
1796 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1797 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1798 !G->getGlobal()->hasProtectedVisibility())
1799 Callee = LowerGlobalAddress(Callee, DAG);
1800 else if (isa<ExternalSymbolSDNode>(Callee))
1801 Callee = LowerExternalSymbol(Callee, DAG);
1805 if (Is64Bit && isVarArg) {
1806 // From AMD64 ABI document:
1807 // For calls that may call functions that use varargs or stdargs
1808 // (prototype-less calls or calls to functions containing ellipsis (...) in
1809 // the declaration) %al is used as hidden argument to specify the number
1810 // of SSE registers used. The contents of %al do not need to match exactly
1811 // the number of registers, but must be an ubound on the number of SSE
1812 // registers used and is in the range 0 - 8 inclusive.
1814 // FIXME: Verify this on Win64
1815 // Count the number of XMM registers allocated.
1816 static const unsigned XMMArgRegs[] = {
1817 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1818 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1820 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1821 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1822 && "SSE registers cannot be used when SSE is disabled");
1824 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1825 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1826 InFlag = Chain.getValue(1);
1830 // For tail calls lower the arguments to the 'real' stack slot.
1832 // Force all the incoming stack arguments to be loaded from the stack
1833 // before any new outgoing arguments are stored to the stack, because the
1834 // outgoing stack slots may alias the incoming argument stack slots, and
1835 // the alias isn't otherwise explicit. This is slightly more conservative
1836 // than necessary, because it means that each store effectively depends
1837 // on every argument instead of just those arguments it would clobber.
1838 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1840 SmallVector<SDValue, 8> MemOpChains2;
1843 // Do not flag preceeding copytoreg stuff together with the following stuff.
1845 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1846 CCValAssign &VA = ArgLocs[i];
1847 if (!VA.isRegLoc()) {
1848 assert(VA.isMemLoc());
1849 SDValue Arg = Outs[i].Val;
1850 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1851 // Create frame index.
1852 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1853 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1854 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1855 FIN = DAG.getFrameIndex(FI, getPointerTy());
1857 if (Flags.isByVal()) {
1858 // Copy relative to framepointer.
1859 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1860 if (StackPtr.getNode() == 0)
1861 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1863 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1865 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1869 // Store relative to framepointer.
1870 MemOpChains2.push_back(
1871 DAG.getStore(ArgChain, dl, Arg, FIN,
1872 PseudoSourceValue::getFixedStack(FI), 0));
1877 if (!MemOpChains2.empty())
1878 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1879 &MemOpChains2[0], MemOpChains2.size());
1881 // Copy arguments to their registers.
1882 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1883 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1884 RegsToPass[i].second, InFlag);
1885 InFlag = Chain.getValue(1);
1889 // Store the return address to the appropriate stack slot.
1890 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1894 // If the callee is a GlobalAddress node (quite common, every direct call is)
1895 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1896 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1897 // We should use extra load for direct calls to dllimported functions in
1899 GlobalValue *GV = G->getGlobal();
1900 if (!GV->hasDLLImportLinkage()) {
1901 unsigned char OpFlags = 0;
1903 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1904 // external symbols most go through the PLT in PIC mode. If the symbol
1905 // has hidden or protected visibility, or if it is static or local, then
1906 // we don't need to use the PLT - we can directly call it.
1907 if (Subtarget->isTargetELF() &&
1908 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1909 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1910 OpFlags = X86II::MO_PLT;
1911 } else if (Subtarget->isPICStyleStubAny() &&
1912 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1913 Subtarget->getDarwinVers() < 9) {
1914 // PC-relative references to external symbols should go through $stub,
1915 // unless we're building with the leopard linker or later, which
1916 // automatically synthesizes these stubs.
1917 OpFlags = X86II::MO_DARWIN_STUB;
1920 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1921 G->getOffset(), OpFlags);
1923 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1924 unsigned char OpFlags = 0;
1926 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1927 // symbols should go through the PLT.
1928 if (Subtarget->isTargetELF() &&
1929 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1930 OpFlags = X86II::MO_PLT;
1931 } else if (Subtarget->isPICStyleStubAny() &&
1932 Subtarget->getDarwinVers() < 9) {
1933 // PC-relative references to external symbols should go through $stub,
1934 // unless we're building with the leopard linker or later, which
1935 // automatically synthesizes these stubs.
1936 OpFlags = X86II::MO_DARWIN_STUB;
1939 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
1941 } else if (isTailCall) {
1942 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1944 Chain = DAG.getCopyToReg(Chain, dl,
1945 DAG.getRegister(Opc, getPointerTy()),
1947 Callee = DAG.getRegister(Opc, getPointerTy());
1948 // Add register as live out.
1949 MF.getRegInfo().addLiveOut(Opc);
1952 // Returns a chain & a flag for retval copy to use.
1953 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1954 SmallVector<SDValue, 8> Ops;
1957 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1958 DAG.getIntPtrConstant(0, true), InFlag);
1959 InFlag = Chain.getValue(1);
1962 Ops.push_back(Chain);
1963 Ops.push_back(Callee);
1966 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1968 // Add argument registers to the end of the list so that they are known live
1970 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1971 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1972 RegsToPass[i].second.getValueType()));
1974 // Add an implicit use GOT pointer in EBX.
1975 if (!isTailCall && Subtarget->isPICStyleGOT())
1976 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1978 // Add an implicit use of AL for x86 vararg functions.
1979 if (Is64Bit && isVarArg)
1980 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1982 if (InFlag.getNode())
1983 Ops.push_back(InFlag);
1986 // If this is the first return lowered for this function, add the regs
1987 // to the liveout set for the function.
1988 if (MF.getRegInfo().liveout_empty()) {
1989 SmallVector<CCValAssign, 16> RVLocs;
1990 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1992 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1993 for (unsigned i = 0; i != RVLocs.size(); ++i)
1994 if (RVLocs[i].isRegLoc())
1995 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1998 assert(((Callee.getOpcode() == ISD::Register &&
1999 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2000 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
2001 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2002 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2003 "Expecting an global address, external symbol, or register");
2005 return DAG.getNode(X86ISD::TC_RETURN, dl,
2006 NodeTys, &Ops[0], Ops.size());
2009 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2010 InFlag = Chain.getValue(1);
2012 // Create the CALLSEQ_END node.
2013 unsigned NumBytesForCalleeToPush;
2014 if (IsCalleePop(isVarArg, CallConv))
2015 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2016 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2017 // If this is is a call to a struct-return function, the callee
2018 // pops the hidden struct pointer, so we have to push it back.
2019 // This is common for Darwin/X86, Linux & Mingw32 targets.
2020 NumBytesForCalleeToPush = 4;
2022 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2024 // Returns a flag for retval copy to use.
2025 Chain = DAG.getCALLSEQ_END(Chain,
2026 DAG.getIntPtrConstant(NumBytes, true),
2027 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2030 InFlag = Chain.getValue(1);
2032 // Handle result values, copying them out of physregs into vregs that we
2034 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2035 Ins, dl, DAG, InVals);
2039 //===----------------------------------------------------------------------===//
2040 // Fast Calling Convention (tail call) implementation
2041 //===----------------------------------------------------------------------===//
2043 // Like std call, callee cleans arguments, convention except that ECX is
2044 // reserved for storing the tail called function address. Only 2 registers are
2045 // free for argument passing (inreg). Tail call optimization is performed
2047 // * tailcallopt is enabled
2048 // * caller/callee are fastcc
2049 // On X86_64 architecture with GOT-style position independent code only local
2050 // (within module) calls are supported at the moment.
2051 // To keep the stack aligned according to platform abi the function
2052 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2053 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2054 // If a tail called function callee has more arguments than the caller the
2055 // caller needs to make sure that there is room to move the RETADDR to. This is
2056 // achieved by reserving an area the size of the argument delta right after the
2057 // original REtADDR, but before the saved framepointer or the spilled registers
2058 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2070 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2071 /// for a 16 byte align requirement.
2072 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2073 SelectionDAG& DAG) {
2074 MachineFunction &MF = DAG.getMachineFunction();
2075 const TargetMachine &TM = MF.getTarget();
2076 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2077 unsigned StackAlignment = TFI.getStackAlignment();
2078 uint64_t AlignMask = StackAlignment - 1;
2079 int64_t Offset = StackSize;
2080 uint64_t SlotSize = TD->getPointerSize();
2081 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2082 // Number smaller than 12 so just add the difference.
2083 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2085 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2086 Offset = ((~AlignMask) & Offset) + StackAlignment +
2087 (StackAlignment-SlotSize);
2092 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2093 /// for tail call optimization. Targets which want to do tail call
2094 /// optimization should implement this function.
2096 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2099 const SmallVectorImpl<ISD::InputArg> &Ins,
2100 SelectionDAG& DAG) const {
2101 MachineFunction &MF = DAG.getMachineFunction();
2102 unsigned CallerCC = MF.getFunction()->getCallingConv();
2103 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2107 X86TargetLowering::createFastISel(MachineFunction &mf,
2108 MachineModuleInfo *mmo,
2110 DenseMap<const Value *, unsigned> &vm,
2111 DenseMap<const BasicBlock *,
2112 MachineBasicBlock *> &bm,
2113 DenseMap<const AllocaInst *, int> &am
2115 , SmallSet<Instruction*, 8> &cil
2118 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2126 //===----------------------------------------------------------------------===//
2127 // Other Lowering Hooks
2128 //===----------------------------------------------------------------------===//
2131 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2132 MachineFunction &MF = DAG.getMachineFunction();
2133 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2134 int ReturnAddrIndex = FuncInfo->getRAIndex();
2136 if (ReturnAddrIndex == 0) {
2137 // Set up a frame object for the return address.
2138 uint64_t SlotSize = TD->getPointerSize();
2139 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2140 FuncInfo->setRAIndex(ReturnAddrIndex);
2143 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2147 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2148 bool hasSymbolicDisplacement) {
2149 // Offset should fit into 32 bit immediate field.
2150 if (!isInt32(Offset))
2153 // If we don't have a symbolic displacement - we don't have any extra
2155 if (!hasSymbolicDisplacement)
2158 // FIXME: Some tweaks might be needed for medium code model.
2159 if (M != CodeModel::Small && M != CodeModel::Kernel)
2162 // For small code model we assume that latest object is 16MB before end of 31
2163 // bits boundary. We may also accept pretty large negative constants knowing
2164 // that all objects are in the positive half of address space.
2165 if (M == CodeModel::Small && Offset < 16*1024*1024)
2168 // For kernel code model we know that all object resist in the negative half
2169 // of 32bits address space. We may not accept negative offsets, since they may
2170 // be just off and we may accept pretty large positive ones.
2171 if (M == CodeModel::Kernel && Offset > 0)
2177 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2178 /// specific condition code, returning the condition code and the LHS/RHS of the
2179 /// comparison to make.
2180 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2181 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2183 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2184 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2185 // X > -1 -> X == 0, jump !sign.
2186 RHS = DAG.getConstant(0, RHS.getValueType());
2187 return X86::COND_NS;
2188 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2189 // X < 0 -> X == 0, jump on sign.
2191 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2193 RHS = DAG.getConstant(0, RHS.getValueType());
2194 return X86::COND_LE;
2198 switch (SetCCOpcode) {
2199 default: llvm_unreachable("Invalid integer condition!");
2200 case ISD::SETEQ: return X86::COND_E;
2201 case ISD::SETGT: return X86::COND_G;
2202 case ISD::SETGE: return X86::COND_GE;
2203 case ISD::SETLT: return X86::COND_L;
2204 case ISD::SETLE: return X86::COND_LE;
2205 case ISD::SETNE: return X86::COND_NE;
2206 case ISD::SETULT: return X86::COND_B;
2207 case ISD::SETUGT: return X86::COND_A;
2208 case ISD::SETULE: return X86::COND_BE;
2209 case ISD::SETUGE: return X86::COND_AE;
2213 // First determine if it is required or is profitable to flip the operands.
2215 // If LHS is a foldable load, but RHS is not, flip the condition.
2216 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2217 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2218 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2219 std::swap(LHS, RHS);
2222 switch (SetCCOpcode) {
2228 std::swap(LHS, RHS);
2232 // On a floating point condition, the flags are set as follows:
2234 // 0 | 0 | 0 | X > Y
2235 // 0 | 0 | 1 | X < Y
2236 // 1 | 0 | 0 | X == Y
2237 // 1 | 1 | 1 | unordered
2238 switch (SetCCOpcode) {
2239 default: llvm_unreachable("Condcode should be pre-legalized away");
2241 case ISD::SETEQ: return X86::COND_E;
2242 case ISD::SETOLT: // flipped
2244 case ISD::SETGT: return X86::COND_A;
2245 case ISD::SETOLE: // flipped
2247 case ISD::SETGE: return X86::COND_AE;
2248 case ISD::SETUGT: // flipped
2250 case ISD::SETLT: return X86::COND_B;
2251 case ISD::SETUGE: // flipped
2253 case ISD::SETLE: return X86::COND_BE;
2255 case ISD::SETNE: return X86::COND_NE;
2256 case ISD::SETUO: return X86::COND_P;
2257 case ISD::SETO: return X86::COND_NP;
2261 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2262 /// code. Current x86 isa includes the following FP cmov instructions:
2263 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2264 static bool hasFPCMov(unsigned X86CC) {
2280 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2281 /// the specified range (L, H].
2282 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2283 return (Val < 0) || (Val >= Low && Val < Hi);
2286 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2287 /// specified value.
2288 static bool isUndefOrEqual(int Val, int CmpVal) {
2289 if (Val < 0 || Val == CmpVal)
2294 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2295 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2296 /// the second operand.
2297 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2298 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2299 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2300 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2301 return (Mask[0] < 2 && Mask[1] < 2);
2305 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2306 SmallVector<int, 8> M;
2308 return ::isPSHUFDMask(M, N->getValueType(0));
2311 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2312 /// is suitable for input to PSHUFHW.
2313 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2314 if (VT != MVT::v8i16)
2317 // Lower quadword copied in order or undef.
2318 for (int i = 0; i != 4; ++i)
2319 if (Mask[i] >= 0 && Mask[i] != i)
2322 // Upper quadword shuffled.
2323 for (int i = 4; i != 8; ++i)
2324 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2330 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2331 SmallVector<int, 8> M;
2333 return ::isPSHUFHWMask(M, N->getValueType(0));
2336 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2337 /// is suitable for input to PSHUFLW.
2338 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2339 if (VT != MVT::v8i16)
2342 // Upper quadword copied in order.
2343 for (int i = 4; i != 8; ++i)
2344 if (Mask[i] >= 0 && Mask[i] != i)
2347 // Lower quadword shuffled.
2348 for (int i = 0; i != 4; ++i)
2355 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2356 SmallVector<int, 8> M;
2358 return ::isPSHUFLWMask(M, N->getValueType(0));
2361 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2362 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2363 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2364 int NumElems = VT.getVectorNumElements();
2365 if (NumElems != 2 && NumElems != 4)
2368 int Half = NumElems / 2;
2369 for (int i = 0; i < Half; ++i)
2370 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2372 for (int i = Half; i < NumElems; ++i)
2373 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2379 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2380 SmallVector<int, 8> M;
2382 return ::isSHUFPMask(M, N->getValueType(0));
2385 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2386 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2387 /// half elements to come from vector 1 (which would equal the dest.) and
2388 /// the upper half to come from vector 2.
2389 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2390 int NumElems = VT.getVectorNumElements();
2392 if (NumElems != 2 && NumElems != 4)
2395 int Half = NumElems / 2;
2396 for (int i = 0; i < Half; ++i)
2397 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2399 for (int i = Half; i < NumElems; ++i)
2400 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2405 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2406 SmallVector<int, 8> M;
2408 return isCommutedSHUFPMask(M, N->getValueType(0));
2411 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2412 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2413 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2414 if (N->getValueType(0).getVectorNumElements() != 4)
2417 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2418 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2419 isUndefOrEqual(N->getMaskElt(1), 7) &&
2420 isUndefOrEqual(N->getMaskElt(2), 2) &&
2421 isUndefOrEqual(N->getMaskElt(3), 3);
2424 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2425 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2426 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2427 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2429 if (NumElems != 2 && NumElems != 4)
2432 for (unsigned i = 0; i < NumElems/2; ++i)
2433 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2436 for (unsigned i = NumElems/2; i < NumElems; ++i)
2437 if (!isUndefOrEqual(N->getMaskElt(i), i))
2443 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2444 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2446 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2447 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2449 if (NumElems != 2 && NumElems != 4)
2452 for (unsigned i = 0; i < NumElems/2; ++i)
2453 if (!isUndefOrEqual(N->getMaskElt(i), i))
2456 for (unsigned i = 0; i < NumElems/2; ++i)
2457 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2463 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2464 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2466 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2467 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2472 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2473 isUndefOrEqual(N->getMaskElt(1), 3) &&
2474 isUndefOrEqual(N->getMaskElt(2), 2) &&
2475 isUndefOrEqual(N->getMaskElt(3), 3);
2478 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2479 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2480 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2481 bool V2IsSplat = false) {
2482 int NumElts = VT.getVectorNumElements();
2483 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2486 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2488 int BitI1 = Mask[i+1];
2489 if (!isUndefOrEqual(BitI, j))
2492 if (!isUndefOrEqual(BitI1, NumElts))
2495 if (!isUndefOrEqual(BitI1, j + NumElts))
2502 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2503 SmallVector<int, 8> M;
2505 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2508 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2509 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2510 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2511 bool V2IsSplat = false) {
2512 int NumElts = VT.getVectorNumElements();
2513 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2516 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2518 int BitI1 = Mask[i+1];
2519 if (!isUndefOrEqual(BitI, j + NumElts/2))
2522 if (isUndefOrEqual(BitI1, NumElts))
2525 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2532 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2533 SmallVector<int, 8> M;
2535 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2538 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2539 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2541 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2542 int NumElems = VT.getVectorNumElements();
2543 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2546 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2548 int BitI1 = Mask[i+1];
2549 if (!isUndefOrEqual(BitI, j))
2551 if (!isUndefOrEqual(BitI1, j))
2557 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2558 SmallVector<int, 8> M;
2560 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2563 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2564 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2566 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2567 int NumElems = VT.getVectorNumElements();
2568 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2571 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2573 int BitI1 = Mask[i+1];
2574 if (!isUndefOrEqual(BitI, j))
2576 if (!isUndefOrEqual(BitI1, j))
2582 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2583 SmallVector<int, 8> M;
2585 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2588 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2589 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2590 /// MOVSD, and MOVD, i.e. setting the lowest element.
2591 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2592 if (VT.getVectorElementType().getSizeInBits() < 32)
2595 int NumElts = VT.getVectorNumElements();
2597 if (!isUndefOrEqual(Mask[0], NumElts))
2600 for (int i = 1; i < NumElts; ++i)
2601 if (!isUndefOrEqual(Mask[i], i))
2607 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2608 SmallVector<int, 8> M;
2610 return ::isMOVLMask(M, N->getValueType(0));
2613 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2614 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2615 /// element of vector 2 and the other elements to come from vector 1 in order.
2616 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2617 bool V2IsSplat = false, bool V2IsUndef = false) {
2618 int NumOps = VT.getVectorNumElements();
2619 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2622 if (!isUndefOrEqual(Mask[0], 0))
2625 for (int i = 1; i < NumOps; ++i)
2626 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2627 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2628 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2634 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2635 bool V2IsUndef = false) {
2636 SmallVector<int, 8> M;
2638 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2641 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2642 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2643 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2644 if (N->getValueType(0).getVectorNumElements() != 4)
2647 // Expect 1, 1, 3, 3
2648 for (unsigned i = 0; i < 2; ++i) {
2649 int Elt = N->getMaskElt(i);
2650 if (Elt >= 0 && Elt != 1)
2655 for (unsigned i = 2; i < 4; ++i) {
2656 int Elt = N->getMaskElt(i);
2657 if (Elt >= 0 && Elt != 3)
2662 // Don't use movshdup if it can be done with a shufps.
2663 // FIXME: verify that matching u, u, 3, 3 is what we want.
2667 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2668 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2669 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2670 if (N->getValueType(0).getVectorNumElements() != 4)
2673 // Expect 0, 0, 2, 2
2674 for (unsigned i = 0; i < 2; ++i)
2675 if (N->getMaskElt(i) > 0)
2679 for (unsigned i = 2; i < 4; ++i) {
2680 int Elt = N->getMaskElt(i);
2681 if (Elt >= 0 && Elt != 2)
2686 // Don't use movsldup if it can be done with a shufps.
2690 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2691 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2692 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2693 int e = N->getValueType(0).getVectorNumElements() / 2;
2695 for (int i = 0; i < e; ++i)
2696 if (!isUndefOrEqual(N->getMaskElt(i), i))
2698 for (int i = 0; i < e; ++i)
2699 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2704 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2705 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2707 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2708 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2709 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2711 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2713 for (int i = 0; i < NumOperands; ++i) {
2714 int Val = SVOp->getMaskElt(NumOperands-i-1);
2715 if (Val < 0) Val = 0;
2716 if (Val >= NumOperands) Val -= NumOperands;
2718 if (i != NumOperands - 1)
2724 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2725 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2727 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2730 // 8 nodes, but we only care about the last 4.
2731 for (unsigned i = 7; i >= 4; --i) {
2732 int Val = SVOp->getMaskElt(i);
2741 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2742 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2744 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2745 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2747 // 8 nodes, but we only care about the first 4.
2748 for (int i = 3; i >= 0; --i) {
2749 int Val = SVOp->getMaskElt(i);
2758 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2760 bool X86::isZeroNode(SDValue Elt) {
2761 return ((isa<ConstantSDNode>(Elt) &&
2762 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2763 (isa<ConstantFPSDNode>(Elt) &&
2764 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2767 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2768 /// their permute mask.
2769 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2770 SelectionDAG &DAG) {
2771 EVT VT = SVOp->getValueType(0);
2772 unsigned NumElems = VT.getVectorNumElements();
2773 SmallVector<int, 8> MaskVec;
2775 for (unsigned i = 0; i != NumElems; ++i) {
2776 int idx = SVOp->getMaskElt(i);
2778 MaskVec.push_back(idx);
2779 else if (idx < (int)NumElems)
2780 MaskVec.push_back(idx + NumElems);
2782 MaskVec.push_back(idx - NumElems);
2784 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2785 SVOp->getOperand(0), &MaskVec[0]);
2788 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2789 /// the two vector operands have swapped position.
2790 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2791 unsigned NumElems = VT.getVectorNumElements();
2792 for (unsigned i = 0; i != NumElems; ++i) {
2796 else if (idx < (int)NumElems)
2797 Mask[i] = idx + NumElems;
2799 Mask[i] = idx - NumElems;
2803 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2804 /// match movhlps. The lower half elements should come from upper half of
2805 /// V1 (and in order), and the upper half elements should come from the upper
2806 /// half of V2 (and in order).
2807 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2808 if (Op->getValueType(0).getVectorNumElements() != 4)
2810 for (unsigned i = 0, e = 2; i != e; ++i)
2811 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2813 for (unsigned i = 2; i != 4; ++i)
2814 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2819 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2820 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2822 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2823 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2825 N = N->getOperand(0).getNode();
2826 if (!ISD::isNON_EXTLoad(N))
2829 *LD = cast<LoadSDNode>(N);
2833 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2834 /// match movlp{s|d}. The lower half elements should come from lower half of
2835 /// V1 (and in order), and the upper half elements should come from the upper
2836 /// half of V2 (and in order). And since V1 will become the source of the
2837 /// MOVLP, it must be either a vector load or a scalar load to vector.
2838 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2839 ShuffleVectorSDNode *Op) {
2840 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2842 // Is V2 is a vector load, don't do this transformation. We will try to use
2843 // load folding shufps op.
2844 if (ISD::isNON_EXTLoad(V2))
2847 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2849 if (NumElems != 2 && NumElems != 4)
2851 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2852 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2854 for (unsigned i = NumElems/2; i != NumElems; ++i)
2855 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2860 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2862 static bool isSplatVector(SDNode *N) {
2863 if (N->getOpcode() != ISD::BUILD_VECTOR)
2866 SDValue SplatValue = N->getOperand(0);
2867 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2868 if (N->getOperand(i) != SplatValue)
2873 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2874 /// to an zero vector.
2875 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2876 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2877 SDValue V1 = N->getOperand(0);
2878 SDValue V2 = N->getOperand(1);
2879 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2880 for (unsigned i = 0; i != NumElems; ++i) {
2881 int Idx = N->getMaskElt(i);
2882 if (Idx >= (int)NumElems) {
2883 unsigned Opc = V2.getOpcode();
2884 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2886 if (Opc != ISD::BUILD_VECTOR ||
2887 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
2889 } else if (Idx >= 0) {
2890 unsigned Opc = V1.getOpcode();
2891 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2893 if (Opc != ISD::BUILD_VECTOR ||
2894 !X86::isZeroNode(V1.getOperand(Idx)))
2901 /// getZeroVector - Returns a vector of specified type with all zero elements.
2903 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
2905 assert(VT.isVector() && "Expected a vector type");
2907 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2908 // type. This ensures they get CSE'd.
2910 if (VT.getSizeInBits() == 64) { // MMX
2911 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2912 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2913 } else if (HasSSE2) { // SSE2
2914 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2915 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2917 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2918 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2920 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2923 /// getOnesVector - Returns a vector of specified type with all bits set.
2925 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2926 assert(VT.isVector() && "Expected a vector type");
2928 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2929 // type. This ensures they get CSE'd.
2930 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2932 if (VT.getSizeInBits() == 64) // MMX
2933 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2935 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2936 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2940 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2941 /// that point to V2 points to its first element.
2942 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2943 EVT VT = SVOp->getValueType(0);
2944 unsigned NumElems = VT.getVectorNumElements();
2946 bool Changed = false;
2947 SmallVector<int, 8> MaskVec;
2948 SVOp->getMask(MaskVec);
2950 for (unsigned i = 0; i != NumElems; ++i) {
2951 if (MaskVec[i] > (int)NumElems) {
2952 MaskVec[i] = NumElems;
2957 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2958 SVOp->getOperand(1), &MaskVec[0]);
2959 return SDValue(SVOp, 0);
2962 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2963 /// operation of specified width.
2964 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
2966 unsigned NumElems = VT.getVectorNumElements();
2967 SmallVector<int, 8> Mask;
2968 Mask.push_back(NumElems);
2969 for (unsigned i = 1; i != NumElems; ++i)
2971 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2974 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2975 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
2977 unsigned NumElems = VT.getVectorNumElements();
2978 SmallVector<int, 8> Mask;
2979 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2981 Mask.push_back(i + NumElems);
2983 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2986 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2987 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
2989 unsigned NumElems = VT.getVectorNumElements();
2990 unsigned Half = NumElems/2;
2991 SmallVector<int, 8> Mask;
2992 for (unsigned i = 0; i != Half; ++i) {
2993 Mask.push_back(i + Half);
2994 Mask.push_back(i + NumElems + Half);
2996 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2999 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3000 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3002 if (SV->getValueType(0).getVectorNumElements() <= 4)
3003 return SDValue(SV, 0);
3005 EVT PVT = MVT::v4f32;
3006 EVT VT = SV->getValueType(0);
3007 DebugLoc dl = SV->getDebugLoc();
3008 SDValue V1 = SV->getOperand(0);
3009 int NumElems = VT.getVectorNumElements();
3010 int EltNo = SV->getSplatIndex();
3012 // unpack elements to the correct location
3013 while (NumElems > 4) {
3014 if (EltNo < NumElems/2) {
3015 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3017 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3018 EltNo -= NumElems/2;
3023 // Perform the splat.
3024 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3025 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3026 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3027 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3030 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3031 /// vector of zero or undef vector. This produces a shuffle where the low
3032 /// element of V2 is swizzled into the zero/undef vector, landing at element
3033 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3034 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3035 bool isZero, bool HasSSE2,
3036 SelectionDAG &DAG) {
3037 EVT VT = V2.getValueType();
3039 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3040 unsigned NumElems = VT.getVectorNumElements();
3041 SmallVector<int, 16> MaskVec;
3042 for (unsigned i = 0; i != NumElems; ++i)
3043 // If this is the insertion idx, put the low elt of V2 here.
3044 MaskVec.push_back(i == Idx ? NumElems : i);
3045 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3048 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3049 /// a shuffle that is zero.
3051 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3052 bool Low, SelectionDAG &DAG) {
3053 unsigned NumZeros = 0;
3054 for (int i = 0; i < NumElems; ++i) {
3055 unsigned Index = Low ? i : NumElems-i-1;
3056 int Idx = SVOp->getMaskElt(Index);
3061 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3062 if (Elt.getNode() && X86::isZeroNode(Elt))
3070 /// isVectorShift - Returns true if the shuffle can be implemented as a
3071 /// logical left or right shift of a vector.
3072 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3073 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3074 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3075 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3078 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3081 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3085 bool SeenV1 = false;
3086 bool SeenV2 = false;
3087 for (int i = NumZeros; i < NumElems; ++i) {
3088 int Val = isLeft ? (i - NumZeros) : i;
3089 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3101 if (SeenV1 && SeenV2)
3104 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3110 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3112 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3113 unsigned NumNonZero, unsigned NumZero,
3114 SelectionDAG &DAG, TargetLowering &TLI) {
3118 DebugLoc dl = Op.getDebugLoc();
3121 for (unsigned i = 0; i < 16; ++i) {
3122 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3123 if (ThisIsNonZero && First) {
3125 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3127 V = DAG.getUNDEF(MVT::v8i16);
3132 SDValue ThisElt(0, 0), LastElt(0, 0);
3133 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3134 if (LastIsNonZero) {
3135 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3136 MVT::i16, Op.getOperand(i-1));
3138 if (ThisIsNonZero) {
3139 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3140 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3141 ThisElt, DAG.getConstant(8, MVT::i8));
3143 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3147 if (ThisElt.getNode())
3148 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3149 DAG.getIntPtrConstant(i/2));
3153 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3156 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3158 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3159 unsigned NumNonZero, unsigned NumZero,
3160 SelectionDAG &DAG, TargetLowering &TLI) {
3164 DebugLoc dl = Op.getDebugLoc();
3167 for (unsigned i = 0; i < 8; ++i) {
3168 bool isNonZero = (NonZeros & (1 << i)) != 0;
3172 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3174 V = DAG.getUNDEF(MVT::v8i16);
3177 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3178 MVT::v8i16, V, Op.getOperand(i),
3179 DAG.getIntPtrConstant(i));
3186 /// getVShift - Return a vector logical shift node.
3188 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3189 unsigned NumBits, SelectionDAG &DAG,
3190 const TargetLowering &TLI, DebugLoc dl) {
3191 bool isMMX = VT.getSizeInBits() == 64;
3192 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3193 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3194 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3195 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3196 DAG.getNode(Opc, dl, ShVT, SrcOp,
3197 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3201 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3202 DebugLoc dl = Op.getDebugLoc();
3203 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3204 if (ISD::isBuildVectorAllZeros(Op.getNode())
3205 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3206 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3207 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3208 // eliminated on x86-32 hosts.
3209 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3212 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3213 return getOnesVector(Op.getValueType(), DAG, dl);
3214 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3217 EVT VT = Op.getValueType();
3218 EVT ExtVT = VT.getVectorElementType();
3219 unsigned EVTBits = ExtVT.getSizeInBits();
3221 unsigned NumElems = Op.getNumOperands();
3222 unsigned NumZero = 0;
3223 unsigned NumNonZero = 0;
3224 unsigned NonZeros = 0;
3225 bool IsAllConstants = true;
3226 SmallSet<SDValue, 8> Values;
3227 for (unsigned i = 0; i < NumElems; ++i) {
3228 SDValue Elt = Op.getOperand(i);
3229 if (Elt.getOpcode() == ISD::UNDEF)
3232 if (Elt.getOpcode() != ISD::Constant &&
3233 Elt.getOpcode() != ISD::ConstantFP)
3234 IsAllConstants = false;
3235 if (X86::isZeroNode(Elt))
3238 NonZeros |= (1 << i);
3243 if (NumNonZero == 0) {
3244 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3245 return DAG.getUNDEF(VT);
3248 // Special case for single non-zero, non-undef, element.
3249 if (NumNonZero == 1) {
3250 unsigned Idx = CountTrailingZeros_32(NonZeros);
3251 SDValue Item = Op.getOperand(Idx);
3253 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3254 // the value are obviously zero, truncate the value to i32 and do the
3255 // insertion that way. Only do this if the value is non-constant or if the
3256 // value is a constant being inserted into element 0. It is cheaper to do
3257 // a constant pool load than it is to do a movd + shuffle.
3258 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3259 (!IsAllConstants || Idx == 0)) {
3260 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3261 // Handle MMX and SSE both.
3262 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3263 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3265 // Truncate the value (which may itself be a constant) to i32, and
3266 // convert it to a vector with movd (S2V+shuffle to zero extend).
3267 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3268 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3269 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3270 Subtarget->hasSSE2(), DAG);
3272 // Now we have our 32-bit value zero extended in the low element of
3273 // a vector. If Idx != 0, swizzle it into place.
3275 SmallVector<int, 4> Mask;
3276 Mask.push_back(Idx);
3277 for (unsigned i = 1; i != VecElts; ++i)
3279 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3280 DAG.getUNDEF(Item.getValueType()),
3283 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3287 // If we have a constant or non-constant insertion into the low element of
3288 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3289 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3290 // depending on what the source datatype is.
3293 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3294 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3295 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3296 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3297 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3298 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3300 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3301 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3302 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3303 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3304 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3305 Subtarget->hasSSE2(), DAG);
3306 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3310 // Is it a vector logical left shift?
3311 if (NumElems == 2 && Idx == 1 &&
3312 X86::isZeroNode(Op.getOperand(0)) &&
3313 !X86::isZeroNode(Op.getOperand(1))) {
3314 unsigned NumBits = VT.getSizeInBits();
3315 return getVShift(true, VT,
3316 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3317 VT, Op.getOperand(1)),
3318 NumBits/2, DAG, *this, dl);
3321 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3324 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3325 // is a non-constant being inserted into an element other than the low one,
3326 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3327 // movd/movss) to move this into the low element, then shuffle it into
3329 if (EVTBits == 32) {
3330 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3332 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3333 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3334 Subtarget->hasSSE2(), DAG);
3335 SmallVector<int, 8> MaskVec;
3336 for (unsigned i = 0; i < NumElems; i++)
3337 MaskVec.push_back(i == Idx ? 0 : 1);
3338 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3342 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3343 if (Values.size() == 1)
3346 // A vector full of immediates; various special cases are already
3347 // handled, so this is best done with a single constant-pool load.
3351 // Let legalizer expand 2-wide build_vectors.
3352 if (EVTBits == 64) {
3353 if (NumNonZero == 1) {
3354 // One half is zero or undef.
3355 unsigned Idx = CountTrailingZeros_32(NonZeros);
3356 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3357 Op.getOperand(Idx));
3358 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3359 Subtarget->hasSSE2(), DAG);
3364 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3365 if (EVTBits == 8 && NumElems == 16) {
3366 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3368 if (V.getNode()) return V;
3371 if (EVTBits == 16 && NumElems == 8) {
3372 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3374 if (V.getNode()) return V;
3377 // If element VT is == 32 bits, turn it into a number of shuffles.
3378 SmallVector<SDValue, 8> V;
3380 if (NumElems == 4 && NumZero > 0) {
3381 for (unsigned i = 0; i < 4; ++i) {
3382 bool isZero = !(NonZeros & (1 << i));
3384 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3386 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3389 for (unsigned i = 0; i < 2; ++i) {
3390 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3393 V[i] = V[i*2]; // Must be a zero vector.
3396 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3399 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3402 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3407 SmallVector<int, 8> MaskVec;
3408 bool Reverse = (NonZeros & 0x3) == 2;
3409 for (unsigned i = 0; i < 2; ++i)
3410 MaskVec.push_back(Reverse ? 1-i : i);
3411 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3412 for (unsigned i = 0; i < 2; ++i)
3413 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3414 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3417 if (Values.size() > 2) {
3418 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3419 // values to be inserted is equal to the number of elements, in which case
3420 // use the unpack code below in the hopes of matching the consecutive elts
3421 // load merge pattern for shuffles.
3422 // FIXME: We could probably just check that here directly.
3423 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3424 getSubtarget()->hasSSE41()) {
3425 V[0] = DAG.getUNDEF(VT);
3426 for (unsigned i = 0; i < NumElems; ++i)
3427 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3428 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3429 Op.getOperand(i), DAG.getIntPtrConstant(i));
3432 // Expand into a number of unpckl*.
3434 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3435 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3436 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3437 for (unsigned i = 0; i < NumElems; ++i)
3438 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3440 while (NumElems != 0) {
3441 for (unsigned i = 0; i < NumElems; ++i)
3442 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3451 // v8i16 shuffles - Prefer shuffles in the following order:
3452 // 1. [all] pshuflw, pshufhw, optional move
3453 // 2. [ssse3] 1 x pshufb
3454 // 3. [ssse3] 2 x pshufb + 1 x por
3455 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3457 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3458 SelectionDAG &DAG, X86TargetLowering &TLI) {
3459 SDValue V1 = SVOp->getOperand(0);
3460 SDValue V2 = SVOp->getOperand(1);
3461 DebugLoc dl = SVOp->getDebugLoc();
3462 SmallVector<int, 8> MaskVals;
3464 // Determine if more than 1 of the words in each of the low and high quadwords
3465 // of the result come from the same quadword of one of the two inputs. Undef
3466 // mask values count as coming from any quadword, for better codegen.
3467 SmallVector<unsigned, 4> LoQuad(4);
3468 SmallVector<unsigned, 4> HiQuad(4);
3469 BitVector InputQuads(4);
3470 for (unsigned i = 0; i < 8; ++i) {
3471 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3472 int EltIdx = SVOp->getMaskElt(i);
3473 MaskVals.push_back(EltIdx);
3482 InputQuads.set(EltIdx / 4);
3485 int BestLoQuad = -1;
3486 unsigned MaxQuad = 1;
3487 for (unsigned i = 0; i < 4; ++i) {
3488 if (LoQuad[i] > MaxQuad) {
3490 MaxQuad = LoQuad[i];
3494 int BestHiQuad = -1;
3496 for (unsigned i = 0; i < 4; ++i) {
3497 if (HiQuad[i] > MaxQuad) {
3499 MaxQuad = HiQuad[i];
3503 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3504 // of the two input vectors, shuffle them into one input vector so only a
3505 // single pshufb instruction is necessary. If There are more than 2 input
3506 // quads, disable the next transformation since it does not help SSSE3.
3507 bool V1Used = InputQuads[0] || InputQuads[1];
3508 bool V2Used = InputQuads[2] || InputQuads[3];
3509 if (TLI.getSubtarget()->hasSSSE3()) {
3510 if (InputQuads.count() == 2 && V1Used && V2Used) {
3511 BestLoQuad = InputQuads.find_first();
3512 BestHiQuad = InputQuads.find_next(BestLoQuad);
3514 if (InputQuads.count() > 2) {
3520 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3521 // the shuffle mask. If a quad is scored as -1, that means that it contains
3522 // words from all 4 input quadwords.
3524 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3525 SmallVector<int, 8> MaskV;
3526 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3527 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3528 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3529 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3530 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3531 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3533 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3534 // source words for the shuffle, to aid later transformations.
3535 bool AllWordsInNewV = true;
3536 bool InOrder[2] = { true, true };
3537 for (unsigned i = 0; i != 8; ++i) {
3538 int idx = MaskVals[i];
3540 InOrder[i/4] = false;
3541 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3543 AllWordsInNewV = false;
3547 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3548 if (AllWordsInNewV) {
3549 for (int i = 0; i != 8; ++i) {
3550 int idx = MaskVals[i];
3553 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3554 if ((idx != i) && idx < 4)
3556 if ((idx != i) && idx > 3)
3565 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3566 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3567 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3568 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3569 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3573 // If we have SSSE3, and all words of the result are from 1 input vector,
3574 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3575 // is present, fall back to case 4.
3576 if (TLI.getSubtarget()->hasSSSE3()) {
3577 SmallVector<SDValue,16> pshufbMask;
3579 // If we have elements from both input vectors, set the high bit of the
3580 // shuffle mask element to zero out elements that come from V2 in the V1
3581 // mask, and elements that come from V1 in the V2 mask, so that the two
3582 // results can be OR'd together.
3583 bool TwoInputs = V1Used && V2Used;
3584 for (unsigned i = 0; i != 8; ++i) {
3585 int EltIdx = MaskVals[i] * 2;
3586 if (TwoInputs && (EltIdx >= 16)) {
3587 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3588 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3591 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3592 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3594 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3595 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3596 DAG.getNode(ISD::BUILD_VECTOR, dl,
3597 MVT::v16i8, &pshufbMask[0], 16));
3599 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3601 // Calculate the shuffle mask for the second input, shuffle it, and
3602 // OR it with the first shuffled input.
3604 for (unsigned i = 0; i != 8; ++i) {
3605 int EltIdx = MaskVals[i] * 2;
3607 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3608 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3611 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3612 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3614 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3615 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3616 DAG.getNode(ISD::BUILD_VECTOR, dl,
3617 MVT::v16i8, &pshufbMask[0], 16));
3618 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3619 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3622 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3623 // and update MaskVals with new element order.
3624 BitVector InOrder(8);
3625 if (BestLoQuad >= 0) {
3626 SmallVector<int, 8> MaskV;
3627 for (int i = 0; i != 4; ++i) {
3628 int idx = MaskVals[i];
3630 MaskV.push_back(-1);
3632 } else if ((idx / 4) == BestLoQuad) {
3633 MaskV.push_back(idx & 3);
3636 MaskV.push_back(-1);
3639 for (unsigned i = 4; i != 8; ++i)
3641 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3645 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3646 // and update MaskVals with the new element order.
3647 if (BestHiQuad >= 0) {
3648 SmallVector<int, 8> MaskV;
3649 for (unsigned i = 0; i != 4; ++i)
3651 for (unsigned i = 4; i != 8; ++i) {
3652 int idx = MaskVals[i];
3654 MaskV.push_back(-1);
3656 } else if ((idx / 4) == BestHiQuad) {
3657 MaskV.push_back((idx & 3) + 4);
3660 MaskV.push_back(-1);
3663 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3667 // In case BestHi & BestLo were both -1, which means each quadword has a word
3668 // from each of the four input quadwords, calculate the InOrder bitvector now
3669 // before falling through to the insert/extract cleanup.
3670 if (BestLoQuad == -1 && BestHiQuad == -1) {
3672 for (int i = 0; i != 8; ++i)
3673 if (MaskVals[i] < 0 || MaskVals[i] == i)
3677 // The other elements are put in the right place using pextrw and pinsrw.
3678 for (unsigned i = 0; i != 8; ++i) {
3681 int EltIdx = MaskVals[i];
3684 SDValue ExtOp = (EltIdx < 8)
3685 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3686 DAG.getIntPtrConstant(EltIdx))
3687 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3688 DAG.getIntPtrConstant(EltIdx - 8));
3689 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3690 DAG.getIntPtrConstant(i));
3695 // v16i8 shuffles - Prefer shuffles in the following order:
3696 // 1. [ssse3] 1 x pshufb
3697 // 2. [ssse3] 2 x pshufb + 1 x por
3698 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3700 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3701 SelectionDAG &DAG, X86TargetLowering &TLI) {
3702 SDValue V1 = SVOp->getOperand(0);
3703 SDValue V2 = SVOp->getOperand(1);
3704 DebugLoc dl = SVOp->getDebugLoc();
3705 SmallVector<int, 16> MaskVals;
3706 SVOp->getMask(MaskVals);
3708 // If we have SSSE3, case 1 is generated when all result bytes come from
3709 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3710 // present, fall back to case 3.
3711 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3714 for (unsigned i = 0; i < 16; ++i) {
3715 int EltIdx = MaskVals[i];
3724 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3725 if (TLI.getSubtarget()->hasSSSE3()) {
3726 SmallVector<SDValue,16> pshufbMask;
3728 // If all result elements are from one input vector, then only translate
3729 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3731 // Otherwise, we have elements from both input vectors, and must zero out
3732 // elements that come from V2 in the first mask, and V1 in the second mask
3733 // so that we can OR them together.
3734 bool TwoInputs = !(V1Only || V2Only);
3735 for (unsigned i = 0; i != 16; ++i) {
3736 int EltIdx = MaskVals[i];
3737 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3738 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3741 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3743 // If all the elements are from V2, assign it to V1 and return after
3744 // building the first pshufb.
3747 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3748 DAG.getNode(ISD::BUILD_VECTOR, dl,
3749 MVT::v16i8, &pshufbMask[0], 16));
3753 // Calculate the shuffle mask for the second input, shuffle it, and
3754 // OR it with the first shuffled input.
3756 for (unsigned i = 0; i != 16; ++i) {
3757 int EltIdx = MaskVals[i];
3759 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3762 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3764 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3765 DAG.getNode(ISD::BUILD_VECTOR, dl,
3766 MVT::v16i8, &pshufbMask[0], 16));
3767 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3770 // No SSSE3 - Calculate in place words and then fix all out of place words
3771 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3772 // the 16 different words that comprise the two doublequadword input vectors.
3773 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3774 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3775 SDValue NewV = V2Only ? V2 : V1;
3776 for (int i = 0; i != 8; ++i) {
3777 int Elt0 = MaskVals[i*2];
3778 int Elt1 = MaskVals[i*2+1];
3780 // This word of the result is all undef, skip it.
3781 if (Elt0 < 0 && Elt1 < 0)
3784 // This word of the result is already in the correct place, skip it.
3785 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3787 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3790 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3791 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3794 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3795 // using a single extract together, load it and store it.
3796 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3797 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3798 DAG.getIntPtrConstant(Elt1 / 2));
3799 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3800 DAG.getIntPtrConstant(i));
3804 // If Elt1 is defined, extract it from the appropriate source. If the
3805 // source byte is not also odd, shift the extracted word left 8 bits
3806 // otherwise clear the bottom 8 bits if we need to do an or.
3808 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3809 DAG.getIntPtrConstant(Elt1 / 2));
3810 if ((Elt1 & 1) == 0)
3811 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3812 DAG.getConstant(8, TLI.getShiftAmountTy()));
3814 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3815 DAG.getConstant(0xFF00, MVT::i16));
3817 // If Elt0 is defined, extract it from the appropriate source. If the
3818 // source byte is not also even, shift the extracted word right 8 bits. If
3819 // Elt1 was also defined, OR the extracted values together before
3820 // inserting them in the result.
3822 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3823 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3824 if ((Elt0 & 1) != 0)
3825 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3826 DAG.getConstant(8, TLI.getShiftAmountTy()));
3828 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3829 DAG.getConstant(0x00FF, MVT::i16));
3830 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3833 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3834 DAG.getIntPtrConstant(i));
3836 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3839 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3840 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3841 /// done when every pair / quad of shuffle mask elements point to elements in
3842 /// the right sequence. e.g.
3843 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3845 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3847 TargetLowering &TLI, DebugLoc dl) {
3848 EVT VT = SVOp->getValueType(0);
3849 SDValue V1 = SVOp->getOperand(0);
3850 SDValue V2 = SVOp->getOperand(1);
3851 unsigned NumElems = VT.getVectorNumElements();
3852 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3853 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3854 EVT MaskEltVT = MaskVT.getVectorElementType();
3856 switch (VT.getSimpleVT().SimpleTy) {
3857 default: assert(false && "Unexpected!");
3858 case MVT::v4f32: NewVT = MVT::v2f64; break;
3859 case MVT::v4i32: NewVT = MVT::v2i64; break;
3860 case MVT::v8i16: NewVT = MVT::v4i32; break;
3861 case MVT::v16i8: NewVT = MVT::v4i32; break;
3864 if (NewWidth == 2) {
3870 int Scale = NumElems / NewWidth;
3871 SmallVector<int, 8> MaskVec;
3872 for (unsigned i = 0; i < NumElems; i += Scale) {
3874 for (int j = 0; j < Scale; ++j) {
3875 int EltIdx = SVOp->getMaskElt(i+j);
3879 StartIdx = EltIdx - (EltIdx % Scale);
3880 if (EltIdx != StartIdx + j)
3884 MaskVec.push_back(-1);
3886 MaskVec.push_back(StartIdx / Scale);
3889 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3890 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3891 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3894 /// getVZextMovL - Return a zero-extending vector move low node.
3896 static SDValue getVZextMovL(EVT VT, EVT OpVT,
3897 SDValue SrcOp, SelectionDAG &DAG,
3898 const X86Subtarget *Subtarget, DebugLoc dl) {
3899 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3900 LoadSDNode *LD = NULL;
3901 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3902 LD = dyn_cast<LoadSDNode>(SrcOp);
3904 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3906 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3907 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
3908 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3909 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3910 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
3912 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3913 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3914 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3915 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3923 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3924 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3925 DAG.getNode(ISD::BIT_CONVERT, dl,
3929 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3932 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3933 SDValue V1 = SVOp->getOperand(0);
3934 SDValue V2 = SVOp->getOperand(1);
3935 DebugLoc dl = SVOp->getDebugLoc();
3936 EVT VT = SVOp->getValueType(0);
3938 SmallVector<std::pair<int, int>, 8> Locs;
3940 SmallVector<int, 8> Mask1(4U, -1);
3941 SmallVector<int, 8> PermMask;
3942 SVOp->getMask(PermMask);
3946 for (unsigned i = 0; i != 4; ++i) {
3947 int Idx = PermMask[i];
3949 Locs[i] = std::make_pair(-1, -1);
3951 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3953 Locs[i] = std::make_pair(0, NumLo);
3957 Locs[i] = std::make_pair(1, NumHi);
3959 Mask1[2+NumHi] = Idx;
3965 if (NumLo <= 2 && NumHi <= 2) {
3966 // If no more than two elements come from either vector. This can be
3967 // implemented with two shuffles. First shuffle gather the elements.
3968 // The second shuffle, which takes the first shuffle as both of its
3969 // vector operands, put the elements into the right order.
3970 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3972 SmallVector<int, 8> Mask2(4U, -1);
3974 for (unsigned i = 0; i != 4; ++i) {
3975 if (Locs[i].first == -1)
3978 unsigned Idx = (i < 2) ? 0 : 4;
3979 Idx += Locs[i].first * 2 + Locs[i].second;
3984 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3985 } else if (NumLo == 3 || NumHi == 3) {
3986 // Otherwise, we must have three elements from one vector, call it X, and
3987 // one element from the other, call it Y. First, use a shufps to build an
3988 // intermediate vector with the one element from Y and the element from X
3989 // that will be in the same half in the final destination (the indexes don't
3990 // matter). Then, use a shufps to build the final vector, taking the half
3991 // containing the element from Y from the intermediate, and the other half
3994 // Normalize it so the 3 elements come from V1.
3995 CommuteVectorShuffleMask(PermMask, VT);
3999 // Find the element from V2.
4001 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4002 int Val = PermMask[HiIndex];
4009 Mask1[0] = PermMask[HiIndex];
4011 Mask1[2] = PermMask[HiIndex^1];
4013 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4016 Mask1[0] = PermMask[0];
4017 Mask1[1] = PermMask[1];
4018 Mask1[2] = HiIndex & 1 ? 6 : 4;
4019 Mask1[3] = HiIndex & 1 ? 4 : 6;
4020 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4022 Mask1[0] = HiIndex & 1 ? 2 : 0;
4023 Mask1[1] = HiIndex & 1 ? 0 : 2;
4024 Mask1[2] = PermMask[2];
4025 Mask1[3] = PermMask[3];
4030 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4034 // Break it into (shuffle shuffle_hi, shuffle_lo).
4036 SmallVector<int,8> LoMask(4U, -1);
4037 SmallVector<int,8> HiMask(4U, -1);
4039 SmallVector<int,8> *MaskPtr = &LoMask;
4040 unsigned MaskIdx = 0;
4043 for (unsigned i = 0; i != 4; ++i) {
4050 int Idx = PermMask[i];
4052 Locs[i] = std::make_pair(-1, -1);
4053 } else if (Idx < 4) {
4054 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4055 (*MaskPtr)[LoIdx] = Idx;
4058 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4059 (*MaskPtr)[HiIdx] = Idx;
4064 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4065 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4066 SmallVector<int, 8> MaskOps;
4067 for (unsigned i = 0; i != 4; ++i) {
4068 if (Locs[i].first == -1) {
4069 MaskOps.push_back(-1);
4071 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4072 MaskOps.push_back(Idx);
4075 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4079 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4080 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4081 SDValue V1 = Op.getOperand(0);
4082 SDValue V2 = Op.getOperand(1);
4083 EVT VT = Op.getValueType();
4084 DebugLoc dl = Op.getDebugLoc();
4085 unsigned NumElems = VT.getVectorNumElements();
4086 bool isMMX = VT.getSizeInBits() == 64;
4087 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4088 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4089 bool V1IsSplat = false;
4090 bool V2IsSplat = false;
4092 if (isZeroShuffle(SVOp))
4093 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4095 // Promote splats to v4f32.
4096 if (SVOp->isSplat()) {
4097 if (isMMX || NumElems < 4)
4099 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4102 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4104 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4105 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4106 if (NewOp.getNode())
4107 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4108 LowerVECTOR_SHUFFLE(NewOp, DAG));
4109 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4110 // FIXME: Figure out a cleaner way to do this.
4111 // Try to make use of movq to zero out the top part.
4112 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4113 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4114 if (NewOp.getNode()) {
4115 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4116 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4117 DAG, Subtarget, dl);
4119 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4120 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4121 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4122 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4123 DAG, Subtarget, dl);
4127 if (X86::isPSHUFDMask(SVOp))
4130 // Check if this can be converted into a logical shift.
4131 bool isLeft = false;
4134 bool isShift = getSubtarget()->hasSSE2() &&
4135 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4136 if (isShift && ShVal.hasOneUse()) {
4137 // If the shifted value has multiple uses, it may be cheaper to use
4138 // v_set0 + movlhps or movhlps, etc.
4139 EVT EVT = VT.getVectorElementType();
4140 ShAmt *= EVT.getSizeInBits();
4141 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4144 if (X86::isMOVLMask(SVOp)) {
4147 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4148 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4153 // FIXME: fold these into legal mask.
4154 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4155 X86::isMOVSLDUPMask(SVOp) ||
4156 X86::isMOVHLPSMask(SVOp) ||
4157 X86::isMOVHPMask(SVOp) ||
4158 X86::isMOVLPMask(SVOp)))
4161 if (ShouldXformToMOVHLPS(SVOp) ||
4162 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4163 return CommuteVectorShuffle(SVOp, DAG);
4166 // No better options. Use a vshl / vsrl.
4167 EVT EVT = VT.getVectorElementType();
4168 ShAmt *= EVT.getSizeInBits();
4169 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4172 bool Commuted = false;
4173 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4174 // 1,1,1,1 -> v8i16 though.
4175 V1IsSplat = isSplatVector(V1.getNode());
4176 V2IsSplat = isSplatVector(V2.getNode());
4178 // Canonicalize the splat or undef, if present, to be on the RHS.
4179 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4180 Op = CommuteVectorShuffle(SVOp, DAG);
4181 SVOp = cast<ShuffleVectorSDNode>(Op);
4182 V1 = SVOp->getOperand(0);
4183 V2 = SVOp->getOperand(1);
4184 std::swap(V1IsSplat, V2IsSplat);
4185 std::swap(V1IsUndef, V2IsUndef);
4189 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4190 // Shuffling low element of v1 into undef, just return v1.
4193 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4194 // the instruction selector will not match, so get a canonical MOVL with
4195 // swapped operands to undo the commute.
4196 return getMOVL(DAG, dl, VT, V2, V1);
4199 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4200 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4201 X86::isUNPCKLMask(SVOp) ||
4202 X86::isUNPCKHMask(SVOp))
4206 // Normalize mask so all entries that point to V2 points to its first
4207 // element then try to match unpck{h|l} again. If match, return a
4208 // new vector_shuffle with the corrected mask.
4209 SDValue NewMask = NormalizeMask(SVOp, DAG);
4210 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4211 if (NSVOp != SVOp) {
4212 if (X86::isUNPCKLMask(NSVOp, true)) {
4214 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4221 // Commute is back and try unpck* again.
4222 // FIXME: this seems wrong.
4223 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4224 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4225 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4226 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4227 X86::isUNPCKLMask(NewSVOp) ||
4228 X86::isUNPCKHMask(NewSVOp))
4232 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4234 // Normalize the node to match x86 shuffle ops if needed
4235 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4236 return CommuteVectorShuffle(SVOp, DAG);
4238 // Check for legal shuffle and return?
4239 SmallVector<int, 16> PermMask;
4240 SVOp->getMask(PermMask);
4241 if (isShuffleMaskLegal(PermMask, VT))
4244 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4245 if (VT == MVT::v8i16) {
4246 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4247 if (NewOp.getNode())
4251 if (VT == MVT::v16i8) {
4252 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4253 if (NewOp.getNode())
4257 // Handle all 4 wide cases with a number of shuffles except for MMX.
4258 if (NumElems == 4 && !isMMX)
4259 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4265 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4266 SelectionDAG &DAG) {
4267 EVT VT = Op.getValueType();
4268 DebugLoc dl = Op.getDebugLoc();
4269 if (VT.getSizeInBits() == 8) {
4270 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4271 Op.getOperand(0), Op.getOperand(1));
4272 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4273 DAG.getValueType(VT));
4274 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4275 } else if (VT.getSizeInBits() == 16) {
4276 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4277 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4279 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4280 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4281 DAG.getNode(ISD::BIT_CONVERT, dl,
4285 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4286 Op.getOperand(0), Op.getOperand(1));
4287 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4288 DAG.getValueType(VT));
4289 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4290 } else if (VT == MVT::f32) {
4291 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4292 // the result back to FR32 register. It's only worth matching if the
4293 // result has a single use which is a store or a bitcast to i32. And in
4294 // the case of a store, it's not worth it if the index is a constant 0,
4295 // because a MOVSSmr can be used instead, which is smaller and faster.
4296 if (!Op.hasOneUse())
4298 SDNode *User = *Op.getNode()->use_begin();
4299 if ((User->getOpcode() != ISD::STORE ||
4300 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4301 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4302 (User->getOpcode() != ISD::BIT_CONVERT ||
4303 User->getValueType(0) != MVT::i32))
4305 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4306 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4309 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4310 } else if (VT == MVT::i32) {
4311 // ExtractPS works with constant index.
4312 if (isa<ConstantSDNode>(Op.getOperand(1)))
4320 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4321 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4324 if (Subtarget->hasSSE41()) {
4325 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4330 EVT VT = Op.getValueType();
4331 DebugLoc dl = Op.getDebugLoc();
4332 // TODO: handle v16i8.
4333 if (VT.getSizeInBits() == 16) {
4334 SDValue Vec = Op.getOperand(0);
4335 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4337 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4338 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4339 DAG.getNode(ISD::BIT_CONVERT, dl,
4342 // Transform it so it match pextrw which produces a 32-bit result.
4343 EVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy+1);
4344 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4345 Op.getOperand(0), Op.getOperand(1));
4346 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4347 DAG.getValueType(VT));
4348 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4349 } else if (VT.getSizeInBits() == 32) {
4350 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4354 // SHUFPS the element to the lowest double word, then movss.
4355 int Mask[4] = { Idx, -1, -1, -1 };
4356 EVT VVT = Op.getOperand(0).getValueType();
4357 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4358 DAG.getUNDEF(VVT), Mask);
4359 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4360 DAG.getIntPtrConstant(0));
4361 } else if (VT.getSizeInBits() == 64) {
4362 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4363 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4364 // to match extract_elt for f64.
4365 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4369 // UNPCKHPD the element to the lowest double word, then movsd.
4370 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4371 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4372 int Mask[2] = { 1, -1 };
4373 EVT VVT = Op.getOperand(0).getValueType();
4374 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4375 DAG.getUNDEF(VVT), Mask);
4376 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4377 DAG.getIntPtrConstant(0));
4384 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4385 EVT VT = Op.getValueType();
4386 EVT EVT = VT.getVectorElementType();
4387 DebugLoc dl = Op.getDebugLoc();
4389 SDValue N0 = Op.getOperand(0);
4390 SDValue N1 = Op.getOperand(1);
4391 SDValue N2 = Op.getOperand(2);
4393 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4394 isa<ConstantSDNode>(N2)) {
4395 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4397 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4399 if (N1.getValueType() != MVT::i32)
4400 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4401 if (N2.getValueType() != MVT::i32)
4402 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4403 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4404 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4405 // Bits [7:6] of the constant are the source select. This will always be
4406 // zero here. The DAG Combiner may combine an extract_elt index into these
4407 // bits. For example (insert (extract, 3), 2) could be matched by putting
4408 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4409 // Bits [5:4] of the constant are the destination select. This is the
4410 // value of the incoming immediate.
4411 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4412 // combine either bitwise AND or insert of float 0.0 to set these bits.
4413 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4414 // Create this as a scalar to vector..
4415 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4416 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4417 } else if (EVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4418 // PINSR* works with constant index.
4425 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4426 EVT VT = Op.getValueType();
4427 EVT EVT = VT.getVectorElementType();
4429 if (Subtarget->hasSSE41())
4430 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4435 DebugLoc dl = Op.getDebugLoc();
4436 SDValue N0 = Op.getOperand(0);
4437 SDValue N1 = Op.getOperand(1);
4438 SDValue N2 = Op.getOperand(2);
4440 if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4441 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4442 // as its second argument.
4443 if (N1.getValueType() != MVT::i32)
4444 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4445 if (N2.getValueType() != MVT::i32)
4446 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4447 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4453 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4454 DebugLoc dl = Op.getDebugLoc();
4455 if (Op.getValueType() == MVT::v2f32)
4456 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4457 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4458 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4459 Op.getOperand(0))));
4461 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4462 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4464 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4465 EVT VT = MVT::v2i32;
4466 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4473 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4474 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4477 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4478 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4479 // one of the above mentioned nodes. It has to be wrapped because otherwise
4480 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4481 // be used to form addressing mode. These wrapped nodes will be selected
4484 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4485 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4487 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4489 unsigned char OpFlag = 0;
4490 unsigned WrapperKind = X86ISD::Wrapper;
4491 CodeModel::Model M = getTargetMachine().getCodeModel();
4493 if (Subtarget->isPICStyleRIPRel() &&
4494 (M == CodeModel::Small || M == CodeModel::Kernel))
4495 WrapperKind = X86ISD::WrapperRIP;
4496 else if (Subtarget->isPICStyleGOT())
4497 OpFlag = X86II::MO_GOTOFF;
4498 else if (Subtarget->isPICStyleStubPIC())
4499 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4501 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4503 CP->getOffset(), OpFlag);
4504 DebugLoc DL = CP->getDebugLoc();
4505 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4506 // With PIC, the address is actually $g + Offset.
4508 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4509 DAG.getNode(X86ISD::GlobalBaseReg,
4510 DebugLoc::getUnknownLoc(), getPointerTy()),
4517 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4518 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4520 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4522 unsigned char OpFlag = 0;
4523 unsigned WrapperKind = X86ISD::Wrapper;
4524 CodeModel::Model M = getTargetMachine().getCodeModel();
4526 if (Subtarget->isPICStyleRIPRel() &&
4527 (M == CodeModel::Small || M == CodeModel::Kernel))
4528 WrapperKind = X86ISD::WrapperRIP;
4529 else if (Subtarget->isPICStyleGOT())
4530 OpFlag = X86II::MO_GOTOFF;
4531 else if (Subtarget->isPICStyleStubPIC())
4532 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4534 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4536 DebugLoc DL = JT->getDebugLoc();
4537 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4539 // With PIC, the address is actually $g + Offset.
4541 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4542 DAG.getNode(X86ISD::GlobalBaseReg,
4543 DebugLoc::getUnknownLoc(), getPointerTy()),
4551 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4552 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4554 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4556 unsigned char OpFlag = 0;
4557 unsigned WrapperKind = X86ISD::Wrapper;
4558 CodeModel::Model M = getTargetMachine().getCodeModel();
4560 if (Subtarget->isPICStyleRIPRel() &&
4561 (M == CodeModel::Small || M == CodeModel::Kernel))
4562 WrapperKind = X86ISD::WrapperRIP;
4563 else if (Subtarget->isPICStyleGOT())
4564 OpFlag = X86II::MO_GOTOFF;
4565 else if (Subtarget->isPICStyleStubPIC())
4566 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4568 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4570 DebugLoc DL = Op.getDebugLoc();
4571 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4574 // With PIC, the address is actually $g + Offset.
4575 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4576 !Subtarget->is64Bit()) {
4577 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4578 DAG.getNode(X86ISD::GlobalBaseReg,
4579 DebugLoc::getUnknownLoc(),
4588 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4590 SelectionDAG &DAG) const {
4591 // Create the TargetGlobalAddress node, folding in the constant
4592 // offset if it is legal.
4593 unsigned char OpFlags =
4594 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4595 CodeModel::Model M = getTargetMachine().getCodeModel();
4597 if (OpFlags == X86II::MO_NO_FLAG &&
4598 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4599 // A direct static reference to a global.
4600 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4603 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4606 if (Subtarget->isPICStyleRIPRel() &&
4607 (M == CodeModel::Small || M == CodeModel::Kernel))
4608 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4610 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4612 // With PIC, the address is actually $g + Offset.
4613 if (isGlobalRelativeToPICBase(OpFlags)) {
4614 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4615 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4619 // For globals that require a load from a stub to get the address, emit the
4621 if (isGlobalStubReference(OpFlags))
4622 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4623 PseudoSourceValue::getGOT(), 0);
4625 // If there was a non-zero offset that we didn't fold, create an explicit
4628 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4629 DAG.getConstant(Offset, getPointerTy()));
4635 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4636 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4637 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4638 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4642 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4643 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4644 unsigned char OperandFlags) {
4645 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4646 DebugLoc dl = GA->getDebugLoc();
4647 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4648 GA->getValueType(0),
4652 SDValue Ops[] = { Chain, TGA, *InFlag };
4653 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4655 SDValue Ops[] = { Chain, TGA };
4656 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4658 SDValue Flag = Chain.getValue(1);
4659 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4662 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4664 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4667 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4668 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4669 DAG.getNode(X86ISD::GlobalBaseReg,
4670 DebugLoc::getUnknownLoc(),
4672 InFlag = Chain.getValue(1);
4674 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4677 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4679 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4681 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4682 X86::RAX, X86II::MO_TLSGD);
4685 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4686 // "local exec" model.
4687 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4688 const EVT PtrVT, TLSModel::Model model,
4690 DebugLoc dl = GA->getDebugLoc();
4691 // Get the Thread Pointer
4692 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4693 DebugLoc::getUnknownLoc(), PtrVT,
4694 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4697 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4700 unsigned char OperandFlags = 0;
4701 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4703 unsigned WrapperKind = X86ISD::Wrapper;
4704 if (model == TLSModel::LocalExec) {
4705 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4706 } else if (is64Bit) {
4707 assert(model == TLSModel::InitialExec);
4708 OperandFlags = X86II::MO_GOTTPOFF;
4709 WrapperKind = X86ISD::WrapperRIP;
4711 assert(model == TLSModel::InitialExec);
4712 OperandFlags = X86II::MO_INDNTPOFF;
4715 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4717 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4718 GA->getOffset(), OperandFlags);
4719 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4721 if (model == TLSModel::InitialExec)
4722 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4723 PseudoSourceValue::getGOT(), 0);
4725 // The address of the thread local variable is the add of the thread
4726 // pointer with the offset of the variable.
4727 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4731 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4732 // TODO: implement the "local dynamic" model
4733 // TODO: implement the "initial exec"model for pic executables
4734 assert(Subtarget->isTargetELF() &&
4735 "TLS not implemented for non-ELF targets");
4736 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4737 const GlobalValue *GV = GA->getGlobal();
4739 // If GV is an alias then use the aliasee for determining
4740 // thread-localness.
4741 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4742 GV = GA->resolveAliasedGlobal(false);
4744 TLSModel::Model model = getTLSModel(GV,
4745 getTargetMachine().getRelocationModel());
4748 case TLSModel::GeneralDynamic:
4749 case TLSModel::LocalDynamic: // not implemented
4750 if (Subtarget->is64Bit())
4751 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4752 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4754 case TLSModel::InitialExec:
4755 case TLSModel::LocalExec:
4756 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4757 Subtarget->is64Bit());
4760 llvm_unreachable("Unreachable");
4765 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4766 /// take a 2 x i32 value to shift plus a shift amount.
4767 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4768 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4769 EVT VT = Op.getValueType();
4770 unsigned VTBits = VT.getSizeInBits();
4771 DebugLoc dl = Op.getDebugLoc();
4772 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4773 SDValue ShOpLo = Op.getOperand(0);
4774 SDValue ShOpHi = Op.getOperand(1);
4775 SDValue ShAmt = Op.getOperand(2);
4776 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4777 DAG.getConstant(VTBits - 1, MVT::i8))
4778 : DAG.getConstant(0, VT);
4781 if (Op.getOpcode() == ISD::SHL_PARTS) {
4782 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4783 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4785 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4786 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4789 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4790 DAG.getConstant(VTBits, MVT::i8));
4791 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4792 AndNode, DAG.getConstant(0, MVT::i8));
4795 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4796 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4797 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4799 if (Op.getOpcode() == ISD::SHL_PARTS) {
4800 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4801 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4803 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4804 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4807 SDValue Ops[2] = { Lo, Hi };
4808 return DAG.getMergeValues(Ops, 2, dl);
4811 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4812 EVT SrcVT = Op.getOperand(0).getValueType();
4814 if (SrcVT.isVector()) {
4815 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4821 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4822 "Unknown SINT_TO_FP to lower!");
4824 // These are really Legal; return the operand so the caller accepts it as
4826 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4828 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4829 Subtarget->is64Bit()) {
4833 DebugLoc dl = Op.getDebugLoc();
4834 unsigned Size = SrcVT.getSizeInBits()/8;
4835 MachineFunction &MF = DAG.getMachineFunction();
4836 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4837 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4838 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4840 PseudoSourceValue::getFixedStack(SSFI), 0);
4841 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4844 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
4846 SelectionDAG &DAG) {
4848 DebugLoc dl = Op.getDebugLoc();
4850 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4852 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4854 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4855 SmallVector<SDValue, 8> Ops;
4856 Ops.push_back(Chain);
4857 Ops.push_back(StackSlot);
4858 Ops.push_back(DAG.getValueType(SrcVT));
4859 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4860 Tys, &Ops[0], Ops.size());
4863 Chain = Result.getValue(1);
4864 SDValue InFlag = Result.getValue(2);
4866 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4867 // shouldn't be necessary except that RFP cannot be live across
4868 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4869 MachineFunction &MF = DAG.getMachineFunction();
4870 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4871 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4872 Tys = DAG.getVTList(MVT::Other);
4873 SmallVector<SDValue, 8> Ops;
4874 Ops.push_back(Chain);
4875 Ops.push_back(Result);
4876 Ops.push_back(StackSlot);
4877 Ops.push_back(DAG.getValueType(Op.getValueType()));
4878 Ops.push_back(InFlag);
4879 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4880 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4881 PseudoSourceValue::getFixedStack(SSFI), 0);
4887 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4888 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4889 // This algorithm is not obvious. Here it is in C code, more or less:
4891 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4892 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4893 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4895 // Copy ints to xmm registers.
4896 __m128i xh = _mm_cvtsi32_si128( hi );
4897 __m128i xl = _mm_cvtsi32_si128( lo );
4899 // Combine into low half of a single xmm register.
4900 __m128i x = _mm_unpacklo_epi32( xh, xl );
4904 // Merge in appropriate exponents to give the integer bits the right
4906 x = _mm_unpacklo_epi32( x, exp );
4908 // Subtract away the biases to deal with the IEEE-754 double precision
4910 d = _mm_sub_pd( (__m128d) x, bias );
4912 // All conversions up to here are exact. The correctly rounded result is
4913 // calculated using the current rounding mode using the following
4915 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4916 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4917 // store doesn't really need to be here (except
4918 // maybe to zero the other double)
4923 DebugLoc dl = Op.getDebugLoc();
4924 LLVMContext *Context = DAG.getContext();
4926 // Build some magic constants.
4927 std::vector<Constant*> CV0;
4928 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
4929 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
4930 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4931 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4932 Constant *C0 = ConstantVector::get(CV0);
4933 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4935 std::vector<Constant*> CV1;
4937 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
4939 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
4940 Constant *C1 = ConstantVector::get(CV1);
4941 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4943 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4944 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4946 DAG.getIntPtrConstant(1)));
4947 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4948 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4950 DAG.getIntPtrConstant(0)));
4951 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4952 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4953 PseudoSourceValue::getConstantPool(), 0,
4955 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4956 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4957 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4958 PseudoSourceValue::getConstantPool(), 0,
4960 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4962 // Add the halves; easiest way is to swap them into another reg first.
4963 int ShufMask[2] = { 1, -1 };
4964 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4965 DAG.getUNDEF(MVT::v2f64), ShufMask);
4966 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4967 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4968 DAG.getIntPtrConstant(0));
4971 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4972 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4973 DebugLoc dl = Op.getDebugLoc();
4974 // FP constant to bias correct the final result.
4975 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4978 // Load the 32-bit value into an XMM register.
4979 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4980 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4982 DAG.getIntPtrConstant(0)));
4984 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4985 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4986 DAG.getIntPtrConstant(0));
4988 // Or the load with the bias.
4989 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4990 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4993 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4994 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4995 MVT::v2f64, Bias)));
4996 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4997 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4998 DAG.getIntPtrConstant(0));
5000 // Subtract the bias.
5001 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5003 // Handle final rounding.
5004 EVT DestVT = Op.getValueType();
5006 if (DestVT.bitsLT(MVT::f64)) {
5007 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5008 DAG.getIntPtrConstant(0));
5009 } else if (DestVT.bitsGT(MVT::f64)) {
5010 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5013 // Handle final rounding.
5017 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5018 SDValue N0 = Op.getOperand(0);
5019 DebugLoc dl = Op.getDebugLoc();
5021 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5022 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5023 // the optimization here.
5024 if (DAG.SignBitIsZero(N0))
5025 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5027 EVT SrcVT = N0.getValueType();
5028 if (SrcVT == MVT::i64) {
5029 // We only handle SSE2 f64 target here; caller can expand the rest.
5030 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5033 return LowerUINT_TO_FP_i64(Op, DAG);
5034 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5035 return LowerUINT_TO_FP_i32(Op, DAG);
5038 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5040 // Make a 64-bit buffer, and use it to build an FILD.
5041 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5042 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5043 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5044 getPointerTy(), StackSlot, WordOff);
5045 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5046 StackSlot, NULL, 0);
5047 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5048 OffsetSlot, NULL, 0);
5049 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5052 std::pair<SDValue,SDValue> X86TargetLowering::
5053 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5054 DebugLoc dl = Op.getDebugLoc();
5056 EVT DstTy = Op.getValueType();
5059 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5063 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5064 DstTy.getSimpleVT() >= MVT::i16 &&
5065 "Unknown FP_TO_SINT to lower!");
5067 // These are really Legal.
5068 if (DstTy == MVT::i32 &&
5069 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5070 return std::make_pair(SDValue(), SDValue());
5071 if (Subtarget->is64Bit() &&
5072 DstTy == MVT::i64 &&
5073 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5074 return std::make_pair(SDValue(), SDValue());
5076 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5078 MachineFunction &MF = DAG.getMachineFunction();
5079 unsigned MemSize = DstTy.getSizeInBits()/8;
5080 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5081 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5084 switch (DstTy.getSimpleVT().SimpleTy) {
5085 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5086 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5087 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5088 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5091 SDValue Chain = DAG.getEntryNode();
5092 SDValue Value = Op.getOperand(0);
5093 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5094 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5095 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5096 PseudoSourceValue::getFixedStack(SSFI), 0);
5097 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5099 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5101 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5102 Chain = Value.getValue(1);
5103 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5104 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5107 // Build the FP_TO_INT*_IN_MEM
5108 SDValue Ops[] = { Chain, Value, StackSlot };
5109 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5111 return std::make_pair(FIST, StackSlot);
5114 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5115 if (Op.getValueType().isVector()) {
5116 if (Op.getValueType() == MVT::v2i32 &&
5117 Op.getOperand(0).getValueType() == MVT::v2f64) {
5123 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5124 SDValue FIST = Vals.first, StackSlot = Vals.second;
5125 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5126 if (FIST.getNode() == 0) return Op;
5129 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5130 FIST, StackSlot, NULL, 0);
5133 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5134 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5135 SDValue FIST = Vals.first, StackSlot = Vals.second;
5136 assert(FIST.getNode() && "Unexpected failure");
5139 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5140 FIST, StackSlot, NULL, 0);
5143 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5144 LLVMContext *Context = DAG.getContext();
5145 DebugLoc dl = Op.getDebugLoc();
5146 EVT VT = Op.getValueType();
5149 EltVT = VT.getVectorElementType();
5150 std::vector<Constant*> CV;
5151 if (EltVT == MVT::f64) {
5152 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5156 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5162 Constant *C = ConstantVector::get(CV);
5163 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5164 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5165 PseudoSourceValue::getConstantPool(), 0,
5167 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5170 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5171 LLVMContext *Context = DAG.getContext();
5172 DebugLoc dl = Op.getDebugLoc();
5173 EVT VT = Op.getValueType();
5175 unsigned EltNum = 1;
5176 if (VT.isVector()) {
5177 EltVT = VT.getVectorElementType();
5178 EltNum = VT.getVectorNumElements();
5180 std::vector<Constant*> CV;
5181 if (EltVT == MVT::f64) {
5182 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5186 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5192 Constant *C = ConstantVector::get(CV);
5193 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5194 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5195 PseudoSourceValue::getConstantPool(), 0,
5197 if (VT.isVector()) {
5198 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5199 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5200 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5202 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5204 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5208 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5209 LLVMContext *Context = DAG.getContext();
5210 SDValue Op0 = Op.getOperand(0);
5211 SDValue Op1 = Op.getOperand(1);
5212 DebugLoc dl = Op.getDebugLoc();
5213 EVT VT = Op.getValueType();
5214 EVT SrcVT = Op1.getValueType();
5216 // If second operand is smaller, extend it first.
5217 if (SrcVT.bitsLT(VT)) {
5218 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5221 // And if it is bigger, shrink it first.
5222 if (SrcVT.bitsGT(VT)) {
5223 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5227 // At this point the operands and the result should have the same
5228 // type, and that won't be f80 since that is not custom lowered.
5230 // First get the sign bit of second operand.
5231 std::vector<Constant*> CV;
5232 if (SrcVT == MVT::f64) {
5233 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5234 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5236 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5237 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5238 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5239 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5241 Constant *C = ConstantVector::get(CV);
5242 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5243 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5244 PseudoSourceValue::getConstantPool(), 0,
5246 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5248 // Shift sign bit right or left if the two operands have different types.
5249 if (SrcVT.bitsGT(VT)) {
5250 // Op0 is MVT::f32, Op1 is MVT::f64.
5251 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5252 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5253 DAG.getConstant(32, MVT::i32));
5254 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5255 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5256 DAG.getIntPtrConstant(0));
5259 // Clear first operand sign bit.
5261 if (VT == MVT::f64) {
5262 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5263 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5265 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5266 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5267 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5268 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5270 C = ConstantVector::get(CV);
5271 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5272 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5273 PseudoSourceValue::getConstantPool(), 0,
5275 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5277 // Or the value with the sign bit.
5278 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5281 /// Emit nodes that will be selected as "test Op0,Op0", or something
5283 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5284 SelectionDAG &DAG) {
5285 DebugLoc dl = Op.getDebugLoc();
5287 // CF and OF aren't always set the way we want. Determine which
5288 // of these we need.
5289 bool NeedCF = false;
5290 bool NeedOF = false;
5292 case X86::COND_A: case X86::COND_AE:
5293 case X86::COND_B: case X86::COND_BE:
5296 case X86::COND_G: case X86::COND_GE:
5297 case X86::COND_L: case X86::COND_LE:
5298 case X86::COND_O: case X86::COND_NO:
5304 // See if we can use the EFLAGS value from the operand instead of
5305 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5306 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5307 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5308 unsigned Opcode = 0;
5309 unsigned NumOperands = 0;
5310 switch (Op.getNode()->getOpcode()) {
5312 // Due to an isel shortcoming, be conservative if this add is likely to
5313 // be selected as part of a load-modify-store instruction. When the root
5314 // node in a match is a store, isel doesn't know how to remap non-chain
5315 // non-flag uses of other nodes in the match, such as the ADD in this
5316 // case. This leads to the ADD being left around and reselected, with
5317 // the result being two adds in the output.
5318 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5319 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5320 if (UI->getOpcode() == ISD::STORE)
5322 if (ConstantSDNode *C =
5323 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5324 // An add of one will be selected as an INC.
5325 if (C->getAPIntValue() == 1) {
5326 Opcode = X86ISD::INC;
5330 // An add of negative one (subtract of one) will be selected as a DEC.
5331 if (C->getAPIntValue().isAllOnesValue()) {
5332 Opcode = X86ISD::DEC;
5337 // Otherwise use a regular EFLAGS-setting add.
5338 Opcode = X86ISD::ADD;
5342 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5343 // likely to be selected as part of a load-modify-store instruction.
5344 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5345 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5346 if (UI->getOpcode() == ISD::STORE)
5348 // Otherwise use a regular EFLAGS-setting sub.
5349 Opcode = X86ISD::SUB;
5356 return SDValue(Op.getNode(), 1);
5362 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5363 SmallVector<SDValue, 4> Ops;
5364 for (unsigned i = 0; i != NumOperands; ++i)
5365 Ops.push_back(Op.getOperand(i));
5366 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5367 DAG.ReplaceAllUsesWith(Op, New);
5368 return SDValue(New.getNode(), 1);
5372 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5373 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5374 DAG.getConstant(0, Op.getValueType()));
5377 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5379 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5380 SelectionDAG &DAG) {
5381 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5382 if (C->getAPIntValue() == 0)
5383 return EmitTest(Op0, X86CC, DAG);
5385 DebugLoc dl = Op0.getDebugLoc();
5386 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5389 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5390 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5391 SDValue Op0 = Op.getOperand(0);
5392 SDValue Op1 = Op.getOperand(1);
5393 DebugLoc dl = Op.getDebugLoc();
5394 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5396 // Lower (X & (1 << N)) == 0 to BT(X, N).
5397 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5398 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5399 if (Op0.getOpcode() == ISD::AND &&
5401 Op1.getOpcode() == ISD::Constant &&
5402 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5403 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5405 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5406 if (ConstantSDNode *Op010C =
5407 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5408 if (Op010C->getZExtValue() == 1) {
5409 LHS = Op0.getOperand(0);
5410 RHS = Op0.getOperand(1).getOperand(1);
5412 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5413 if (ConstantSDNode *Op000C =
5414 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5415 if (Op000C->getZExtValue() == 1) {
5416 LHS = Op0.getOperand(1);
5417 RHS = Op0.getOperand(0).getOperand(1);
5419 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5420 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5421 SDValue AndLHS = Op0.getOperand(0);
5422 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5423 LHS = AndLHS.getOperand(0);
5424 RHS = AndLHS.getOperand(1);
5428 if (LHS.getNode()) {
5429 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5430 // instruction. Since the shift amount is in-range-or-undefined, we know
5431 // that doing a bittest on the i16 value is ok. We extend to i32 because
5432 // the encoding for the i16 version is larger than the i32 version.
5433 if (LHS.getValueType() == MVT::i8)
5434 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5436 // If the operand types disagree, extend the shift amount to match. Since
5437 // BT ignores high bits (like shifts) we can use anyextend.
5438 if (LHS.getValueType() != RHS.getValueType())
5439 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5441 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5442 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5443 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5444 DAG.getConstant(Cond, MVT::i8), BT);
5448 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5449 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5451 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5452 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5453 DAG.getConstant(X86CC, MVT::i8), Cond);
5456 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5458 SDValue Op0 = Op.getOperand(0);
5459 SDValue Op1 = Op.getOperand(1);
5460 SDValue CC = Op.getOperand(2);
5461 EVT VT = Op.getValueType();
5462 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5463 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5464 DebugLoc dl = Op.getDebugLoc();
5468 EVT VT0 = Op0.getValueType();
5469 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5470 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5473 switch (SetCCOpcode) {
5476 case ISD::SETEQ: SSECC = 0; break;
5478 case ISD::SETGT: Swap = true; // Fallthrough
5480 case ISD::SETOLT: SSECC = 1; break;
5482 case ISD::SETGE: Swap = true; // Fallthrough
5484 case ISD::SETOLE: SSECC = 2; break;
5485 case ISD::SETUO: SSECC = 3; break;
5487 case ISD::SETNE: SSECC = 4; break;
5488 case ISD::SETULE: Swap = true;
5489 case ISD::SETUGE: SSECC = 5; break;
5490 case ISD::SETULT: Swap = true;
5491 case ISD::SETUGT: SSECC = 6; break;
5492 case ISD::SETO: SSECC = 7; break;
5495 std::swap(Op0, Op1);
5497 // In the two special cases we can't handle, emit two comparisons.
5499 if (SetCCOpcode == ISD::SETUEQ) {
5501 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5502 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5503 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5505 else if (SetCCOpcode == ISD::SETONE) {
5507 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5508 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5509 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5511 llvm_unreachable("Illegal FP comparison");
5513 // Handle all other FP comparisons here.
5514 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5517 // We are handling one of the integer comparisons here. Since SSE only has
5518 // GT and EQ comparisons for integer, swapping operands and multiple
5519 // operations may be required for some comparisons.
5520 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5521 bool Swap = false, Invert = false, FlipSigns = false;
5523 switch (VT.getSimpleVT().SimpleTy) {
5526 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5528 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5530 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5531 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5534 switch (SetCCOpcode) {
5536 case ISD::SETNE: Invert = true;
5537 case ISD::SETEQ: Opc = EQOpc; break;
5538 case ISD::SETLT: Swap = true;
5539 case ISD::SETGT: Opc = GTOpc; break;
5540 case ISD::SETGE: Swap = true;
5541 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5542 case ISD::SETULT: Swap = true;
5543 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5544 case ISD::SETUGE: Swap = true;
5545 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5548 std::swap(Op0, Op1);
5550 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5551 // bits of the inputs before performing those operations.
5553 EVT EltVT = VT.getVectorElementType();
5554 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5556 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5557 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5559 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5560 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5563 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5565 // If the logical-not of the result is required, perform that now.
5567 Result = DAG.getNOT(dl, Result, VT);
5572 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5573 static bool isX86LogicalCmp(SDValue Op) {
5574 unsigned Opc = Op.getNode()->getOpcode();
5575 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5577 if (Op.getResNo() == 1 &&
5578 (Opc == X86ISD::ADD ||
5579 Opc == X86ISD::SUB ||
5580 Opc == X86ISD::SMUL ||
5581 Opc == X86ISD::UMUL ||
5582 Opc == X86ISD::INC ||
5583 Opc == X86ISD::DEC))
5589 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5590 bool addTest = true;
5591 SDValue Cond = Op.getOperand(0);
5592 DebugLoc dl = Op.getDebugLoc();
5595 if (Cond.getOpcode() == ISD::SETCC)
5596 Cond = LowerSETCC(Cond, DAG);
5598 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5599 // setting operand in place of the X86ISD::SETCC.
5600 if (Cond.getOpcode() == X86ISD::SETCC) {
5601 CC = Cond.getOperand(0);
5603 SDValue Cmp = Cond.getOperand(1);
5604 unsigned Opc = Cmp.getOpcode();
5605 EVT VT = Op.getValueType();
5607 bool IllegalFPCMov = false;
5608 if (VT.isFloatingPoint() && !VT.isVector() &&
5609 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5610 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5612 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5613 Opc == X86ISD::BT) { // FIXME
5620 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5621 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5624 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5625 SmallVector<SDValue, 4> Ops;
5626 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5627 // condition is true.
5628 Ops.push_back(Op.getOperand(2));
5629 Ops.push_back(Op.getOperand(1));
5631 Ops.push_back(Cond);
5632 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5635 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5636 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5637 // from the AND / OR.
5638 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5639 Opc = Op.getOpcode();
5640 if (Opc != ISD::OR && Opc != ISD::AND)
5642 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5643 Op.getOperand(0).hasOneUse() &&
5644 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5645 Op.getOperand(1).hasOneUse());
5648 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5649 // 1 and that the SETCC node has a single use.
5650 static bool isXor1OfSetCC(SDValue Op) {
5651 if (Op.getOpcode() != ISD::XOR)
5653 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5654 if (N1C && N1C->getAPIntValue() == 1) {
5655 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5656 Op.getOperand(0).hasOneUse();
5661 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5662 bool addTest = true;
5663 SDValue Chain = Op.getOperand(0);
5664 SDValue Cond = Op.getOperand(1);
5665 SDValue Dest = Op.getOperand(2);
5666 DebugLoc dl = Op.getDebugLoc();
5669 if (Cond.getOpcode() == ISD::SETCC)
5670 Cond = LowerSETCC(Cond, DAG);
5672 // FIXME: LowerXALUO doesn't handle these!!
5673 else if (Cond.getOpcode() == X86ISD::ADD ||
5674 Cond.getOpcode() == X86ISD::SUB ||
5675 Cond.getOpcode() == X86ISD::SMUL ||
5676 Cond.getOpcode() == X86ISD::UMUL)
5677 Cond = LowerXALUO(Cond, DAG);
5680 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5681 // setting operand in place of the X86ISD::SETCC.
5682 if (Cond.getOpcode() == X86ISD::SETCC) {
5683 CC = Cond.getOperand(0);
5685 SDValue Cmp = Cond.getOperand(1);
5686 unsigned Opc = Cmp.getOpcode();
5687 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5688 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5692 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5696 // These can only come from an arithmetic instruction with overflow,
5697 // e.g. SADDO, UADDO.
5698 Cond = Cond.getNode()->getOperand(1);
5705 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5706 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5707 if (CondOpc == ISD::OR) {
5708 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5709 // two branches instead of an explicit OR instruction with a
5711 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5712 isX86LogicalCmp(Cmp)) {
5713 CC = Cond.getOperand(0).getOperand(0);
5714 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5715 Chain, Dest, CC, Cmp);
5716 CC = Cond.getOperand(1).getOperand(0);
5720 } else { // ISD::AND
5721 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5722 // two branches instead of an explicit AND instruction with a
5723 // separate test. However, we only do this if this block doesn't
5724 // have a fall-through edge, because this requires an explicit
5725 // jmp when the condition is false.
5726 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5727 isX86LogicalCmp(Cmp) &&
5728 Op.getNode()->hasOneUse()) {
5729 X86::CondCode CCode =
5730 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5731 CCode = X86::GetOppositeBranchCondition(CCode);
5732 CC = DAG.getConstant(CCode, MVT::i8);
5733 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5734 // Look for an unconditional branch following this conditional branch.
5735 // We need this because we need to reverse the successors in order
5736 // to implement FCMP_OEQ.
5737 if (User.getOpcode() == ISD::BR) {
5738 SDValue FalseBB = User.getOperand(1);
5740 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5741 assert(NewBR == User);
5744 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5745 Chain, Dest, CC, Cmp);
5746 X86::CondCode CCode =
5747 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5748 CCode = X86::GetOppositeBranchCondition(CCode);
5749 CC = DAG.getConstant(CCode, MVT::i8);
5755 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5756 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5757 // It should be transformed during dag combiner except when the condition
5758 // is set by a arithmetics with overflow node.
5759 X86::CondCode CCode =
5760 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5761 CCode = X86::GetOppositeBranchCondition(CCode);
5762 CC = DAG.getConstant(CCode, MVT::i8);
5763 Cond = Cond.getOperand(0).getOperand(1);
5769 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5770 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5772 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5773 Chain, Dest, CC, Cond);
5777 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5778 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5779 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5780 // that the guard pages used by the OS virtual memory manager are allocated in
5781 // correct sequence.
5783 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5784 SelectionDAG &DAG) {
5785 assert(Subtarget->isTargetCygMing() &&
5786 "This should be used only on Cygwin/Mingw targets");
5787 DebugLoc dl = Op.getDebugLoc();
5790 SDValue Chain = Op.getOperand(0);
5791 SDValue Size = Op.getOperand(1);
5792 // FIXME: Ensure alignment here
5796 EVT IntPtr = getPointerTy();
5797 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5799 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5801 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5802 Flag = Chain.getValue(1);
5804 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5805 SDValue Ops[] = { Chain,
5806 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5807 DAG.getRegister(X86::EAX, IntPtr),
5808 DAG.getRegister(X86StackPtr, SPTy),
5810 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5811 Flag = Chain.getValue(1);
5813 Chain = DAG.getCALLSEQ_END(Chain,
5814 DAG.getIntPtrConstant(0, true),
5815 DAG.getIntPtrConstant(0, true),
5818 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5820 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5821 return DAG.getMergeValues(Ops1, 2, dl);
5825 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5827 SDValue Dst, SDValue Src,
5828 SDValue Size, unsigned Align,
5830 uint64_t DstSVOff) {
5831 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5833 // If not DWORD aligned or size is more than the threshold, call the library.
5834 // The libc version is likely to be faster for these cases. It can use the
5835 // address value and run time information about the CPU.
5836 if ((Align & 3) != 0 ||
5838 ConstantSize->getZExtValue() >
5839 getSubtarget()->getMaxInlineSizeThreshold()) {
5840 SDValue InFlag(0, 0);
5842 // Check to see if there is a specialized entry-point for memory zeroing.
5843 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5845 if (const char *bzeroEntry = V &&
5846 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5847 EVT IntPtr = getPointerTy();
5848 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
5849 TargetLowering::ArgListTy Args;
5850 TargetLowering::ArgListEntry Entry;
5852 Entry.Ty = IntPtrTy;
5853 Args.push_back(Entry);
5855 Args.push_back(Entry);
5856 std::pair<SDValue,SDValue> CallResult =
5857 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
5858 false, false, false, false,
5859 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
5860 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5861 return CallResult.second;
5864 // Otherwise have the target-independent code call memset.
5868 uint64_t SizeVal = ConstantSize->getZExtValue();
5869 SDValue InFlag(0, 0);
5872 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5873 unsigned BytesLeft = 0;
5874 bool TwoRepStos = false;
5877 uint64_t Val = ValC->getZExtValue() & 255;
5879 // If the value is a constant, then we can potentially use larger sets.
5880 switch (Align & 3) {
5881 case 2: // WORD aligned
5884 Val = (Val << 8) | Val;
5886 case 0: // DWORD aligned
5889 Val = (Val << 8) | Val;
5890 Val = (Val << 16) | Val;
5891 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5894 Val = (Val << 32) | Val;
5897 default: // Byte aligned
5900 Count = DAG.getIntPtrConstant(SizeVal);
5904 if (AVT.bitsGT(MVT::i8)) {
5905 unsigned UBytes = AVT.getSizeInBits() / 8;
5906 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5907 BytesLeft = SizeVal % UBytes;
5910 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5912 InFlag = Chain.getValue(1);
5915 Count = DAG.getIntPtrConstant(SizeVal);
5916 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5917 InFlag = Chain.getValue(1);
5920 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5923 InFlag = Chain.getValue(1);
5924 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5927 InFlag = Chain.getValue(1);
5929 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5930 SmallVector<SDValue, 8> Ops;
5931 Ops.push_back(Chain);
5932 Ops.push_back(DAG.getValueType(AVT));
5933 Ops.push_back(InFlag);
5934 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5937 InFlag = Chain.getValue(1);
5939 EVT CVT = Count.getValueType();
5940 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5941 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5942 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5945 InFlag = Chain.getValue(1);
5946 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5948 Ops.push_back(Chain);
5949 Ops.push_back(DAG.getValueType(MVT::i8));
5950 Ops.push_back(InFlag);
5951 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5952 } else if (BytesLeft) {
5953 // Handle the last 1 - 7 bytes.
5954 unsigned Offset = SizeVal - BytesLeft;
5955 EVT AddrVT = Dst.getValueType();
5956 EVT SizeVT = Size.getValueType();
5958 Chain = DAG.getMemset(Chain, dl,
5959 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5960 DAG.getConstant(Offset, AddrVT)),
5962 DAG.getConstant(BytesLeft, SizeVT),
5963 Align, DstSV, DstSVOff + Offset);
5966 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5971 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5972 SDValue Chain, SDValue Dst, SDValue Src,
5973 SDValue Size, unsigned Align,
5975 const Value *DstSV, uint64_t DstSVOff,
5976 const Value *SrcSV, uint64_t SrcSVOff) {
5977 // This requires the copy size to be a constant, preferrably
5978 // within a subtarget-specific limit.
5979 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5982 uint64_t SizeVal = ConstantSize->getZExtValue();
5983 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5986 /// If not DWORD aligned, call the library.
5987 if ((Align & 3) != 0)
5992 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5995 unsigned UBytes = AVT.getSizeInBits() / 8;
5996 unsigned CountVal = SizeVal / UBytes;
5997 SDValue Count = DAG.getIntPtrConstant(CountVal);
5998 unsigned BytesLeft = SizeVal % UBytes;
6000 SDValue InFlag(0, 0);
6001 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6004 InFlag = Chain.getValue(1);
6005 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6008 InFlag = Chain.getValue(1);
6009 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6012 InFlag = Chain.getValue(1);
6014 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6015 SmallVector<SDValue, 8> Ops;
6016 Ops.push_back(Chain);
6017 Ops.push_back(DAG.getValueType(AVT));
6018 Ops.push_back(InFlag);
6019 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6021 SmallVector<SDValue, 4> Results;
6022 Results.push_back(RepMovs);
6024 // Handle the last 1 - 7 bytes.
6025 unsigned Offset = SizeVal - BytesLeft;
6026 EVT DstVT = Dst.getValueType();
6027 EVT SrcVT = Src.getValueType();
6028 EVT SizeVT = Size.getValueType();
6029 Results.push_back(DAG.getMemcpy(Chain, dl,
6030 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6031 DAG.getConstant(Offset, DstVT)),
6032 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6033 DAG.getConstant(Offset, SrcVT)),
6034 DAG.getConstant(BytesLeft, SizeVT),
6035 Align, AlwaysInline,
6036 DstSV, DstSVOff + Offset,
6037 SrcSV, SrcSVOff + Offset));
6040 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6041 &Results[0], Results.size());
6044 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6045 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6046 DebugLoc dl = Op.getDebugLoc();
6048 if (!Subtarget->is64Bit()) {
6049 // vastart just stores the address of the VarArgsFrameIndex slot into the
6050 // memory location argument.
6051 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6052 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6056 // gp_offset (0 - 6 * 8)
6057 // fp_offset (48 - 48 + 8 * 16)
6058 // overflow_arg_area (point to parameters coming in memory).
6060 SmallVector<SDValue, 8> MemOps;
6061 SDValue FIN = Op.getOperand(1);
6063 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6064 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6066 MemOps.push_back(Store);
6069 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6070 FIN, DAG.getIntPtrConstant(4));
6071 Store = DAG.getStore(Op.getOperand(0), dl,
6072 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6074 MemOps.push_back(Store);
6076 // Store ptr to overflow_arg_area
6077 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6078 FIN, DAG.getIntPtrConstant(4));
6079 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6080 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6081 MemOps.push_back(Store);
6083 // Store ptr to reg_save_area.
6084 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6085 FIN, DAG.getIntPtrConstant(8));
6086 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6087 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6088 MemOps.push_back(Store);
6089 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6090 &MemOps[0], MemOps.size());
6093 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6094 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6095 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6096 SDValue Chain = Op.getOperand(0);
6097 SDValue SrcPtr = Op.getOperand(1);
6098 SDValue SrcSV = Op.getOperand(2);
6100 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6104 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6105 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6106 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6107 SDValue Chain = Op.getOperand(0);
6108 SDValue DstPtr = Op.getOperand(1);
6109 SDValue SrcPtr = Op.getOperand(2);
6110 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6111 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6112 DebugLoc dl = Op.getDebugLoc();
6114 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6115 DAG.getIntPtrConstant(24), 8, false,
6116 DstSV, 0, SrcSV, 0);
6120 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6121 DebugLoc dl = Op.getDebugLoc();
6122 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6124 default: return SDValue(); // Don't custom lower most intrinsics.
6125 // Comparison intrinsics.
6126 case Intrinsic::x86_sse_comieq_ss:
6127 case Intrinsic::x86_sse_comilt_ss:
6128 case Intrinsic::x86_sse_comile_ss:
6129 case Intrinsic::x86_sse_comigt_ss:
6130 case Intrinsic::x86_sse_comige_ss:
6131 case Intrinsic::x86_sse_comineq_ss:
6132 case Intrinsic::x86_sse_ucomieq_ss:
6133 case Intrinsic::x86_sse_ucomilt_ss:
6134 case Intrinsic::x86_sse_ucomile_ss:
6135 case Intrinsic::x86_sse_ucomigt_ss:
6136 case Intrinsic::x86_sse_ucomige_ss:
6137 case Intrinsic::x86_sse_ucomineq_ss:
6138 case Intrinsic::x86_sse2_comieq_sd:
6139 case Intrinsic::x86_sse2_comilt_sd:
6140 case Intrinsic::x86_sse2_comile_sd:
6141 case Intrinsic::x86_sse2_comigt_sd:
6142 case Intrinsic::x86_sse2_comige_sd:
6143 case Intrinsic::x86_sse2_comineq_sd:
6144 case Intrinsic::x86_sse2_ucomieq_sd:
6145 case Intrinsic::x86_sse2_ucomilt_sd:
6146 case Intrinsic::x86_sse2_ucomile_sd:
6147 case Intrinsic::x86_sse2_ucomigt_sd:
6148 case Intrinsic::x86_sse2_ucomige_sd:
6149 case Intrinsic::x86_sse2_ucomineq_sd: {
6151 ISD::CondCode CC = ISD::SETCC_INVALID;
6154 case Intrinsic::x86_sse_comieq_ss:
6155 case Intrinsic::x86_sse2_comieq_sd:
6159 case Intrinsic::x86_sse_comilt_ss:
6160 case Intrinsic::x86_sse2_comilt_sd:
6164 case Intrinsic::x86_sse_comile_ss:
6165 case Intrinsic::x86_sse2_comile_sd:
6169 case Intrinsic::x86_sse_comigt_ss:
6170 case Intrinsic::x86_sse2_comigt_sd:
6174 case Intrinsic::x86_sse_comige_ss:
6175 case Intrinsic::x86_sse2_comige_sd:
6179 case Intrinsic::x86_sse_comineq_ss:
6180 case Intrinsic::x86_sse2_comineq_sd:
6184 case Intrinsic::x86_sse_ucomieq_ss:
6185 case Intrinsic::x86_sse2_ucomieq_sd:
6186 Opc = X86ISD::UCOMI;
6189 case Intrinsic::x86_sse_ucomilt_ss:
6190 case Intrinsic::x86_sse2_ucomilt_sd:
6191 Opc = X86ISD::UCOMI;
6194 case Intrinsic::x86_sse_ucomile_ss:
6195 case Intrinsic::x86_sse2_ucomile_sd:
6196 Opc = X86ISD::UCOMI;
6199 case Intrinsic::x86_sse_ucomigt_ss:
6200 case Intrinsic::x86_sse2_ucomigt_sd:
6201 Opc = X86ISD::UCOMI;
6204 case Intrinsic::x86_sse_ucomige_ss:
6205 case Intrinsic::x86_sse2_ucomige_sd:
6206 Opc = X86ISD::UCOMI;
6209 case Intrinsic::x86_sse_ucomineq_ss:
6210 case Intrinsic::x86_sse2_ucomineq_sd:
6211 Opc = X86ISD::UCOMI;
6216 SDValue LHS = Op.getOperand(1);
6217 SDValue RHS = Op.getOperand(2);
6218 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6219 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6220 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6221 DAG.getConstant(X86CC, MVT::i8), Cond);
6222 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6224 // ptest intrinsics. The intrinsic these come from are designed to return
6225 // an integer value, not just an instruction so lower it to the ptest
6226 // pattern and a setcc for the result.
6227 case Intrinsic::x86_sse41_ptestz:
6228 case Intrinsic::x86_sse41_ptestc:
6229 case Intrinsic::x86_sse41_ptestnzc:{
6232 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6233 case Intrinsic::x86_sse41_ptestz:
6235 X86CC = X86::COND_E;
6237 case Intrinsic::x86_sse41_ptestc:
6239 X86CC = X86::COND_B;
6241 case Intrinsic::x86_sse41_ptestnzc:
6243 X86CC = X86::COND_A;
6247 SDValue LHS = Op.getOperand(1);
6248 SDValue RHS = Op.getOperand(2);
6249 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6250 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6251 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6252 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6255 // Fix vector shift instructions where the last operand is a non-immediate
6257 case Intrinsic::x86_sse2_pslli_w:
6258 case Intrinsic::x86_sse2_pslli_d:
6259 case Intrinsic::x86_sse2_pslli_q:
6260 case Intrinsic::x86_sse2_psrli_w:
6261 case Intrinsic::x86_sse2_psrli_d:
6262 case Intrinsic::x86_sse2_psrli_q:
6263 case Intrinsic::x86_sse2_psrai_w:
6264 case Intrinsic::x86_sse2_psrai_d:
6265 case Intrinsic::x86_mmx_pslli_w:
6266 case Intrinsic::x86_mmx_pslli_d:
6267 case Intrinsic::x86_mmx_pslli_q:
6268 case Intrinsic::x86_mmx_psrli_w:
6269 case Intrinsic::x86_mmx_psrli_d:
6270 case Intrinsic::x86_mmx_psrli_q:
6271 case Intrinsic::x86_mmx_psrai_w:
6272 case Intrinsic::x86_mmx_psrai_d: {
6273 SDValue ShAmt = Op.getOperand(2);
6274 if (isa<ConstantSDNode>(ShAmt))
6277 unsigned NewIntNo = 0;
6278 EVT ShAmtVT = MVT::v4i32;
6280 case Intrinsic::x86_sse2_pslli_w:
6281 NewIntNo = Intrinsic::x86_sse2_psll_w;
6283 case Intrinsic::x86_sse2_pslli_d:
6284 NewIntNo = Intrinsic::x86_sse2_psll_d;
6286 case Intrinsic::x86_sse2_pslli_q:
6287 NewIntNo = Intrinsic::x86_sse2_psll_q;
6289 case Intrinsic::x86_sse2_psrli_w:
6290 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6292 case Intrinsic::x86_sse2_psrli_d:
6293 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6295 case Intrinsic::x86_sse2_psrli_q:
6296 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6298 case Intrinsic::x86_sse2_psrai_w:
6299 NewIntNo = Intrinsic::x86_sse2_psra_w;
6301 case Intrinsic::x86_sse2_psrai_d:
6302 NewIntNo = Intrinsic::x86_sse2_psra_d;
6305 ShAmtVT = MVT::v2i32;
6307 case Intrinsic::x86_mmx_pslli_w:
6308 NewIntNo = Intrinsic::x86_mmx_psll_w;
6310 case Intrinsic::x86_mmx_pslli_d:
6311 NewIntNo = Intrinsic::x86_mmx_psll_d;
6313 case Intrinsic::x86_mmx_pslli_q:
6314 NewIntNo = Intrinsic::x86_mmx_psll_q;
6316 case Intrinsic::x86_mmx_psrli_w:
6317 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6319 case Intrinsic::x86_mmx_psrli_d:
6320 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6322 case Intrinsic::x86_mmx_psrli_q:
6323 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6325 case Intrinsic::x86_mmx_psrai_w:
6326 NewIntNo = Intrinsic::x86_mmx_psra_w;
6328 case Intrinsic::x86_mmx_psrai_d:
6329 NewIntNo = Intrinsic::x86_mmx_psra_d;
6331 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6336 EVT VT = Op.getValueType();
6337 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6338 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6339 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6340 DAG.getConstant(NewIntNo, MVT::i32),
6341 Op.getOperand(1), ShAmt);
6346 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6347 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6348 DebugLoc dl = Op.getDebugLoc();
6351 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6353 DAG.getConstant(TD->getPointerSize(),
6354 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6355 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6356 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6361 // Just load the return address.
6362 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6363 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6364 RetAddrFI, NULL, 0);
6367 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6368 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6369 MFI->setFrameAddressIsTaken(true);
6370 EVT VT = Op.getValueType();
6371 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6372 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6373 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6374 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6376 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6380 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6381 SelectionDAG &DAG) {
6382 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6385 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6387 MachineFunction &MF = DAG.getMachineFunction();
6388 SDValue Chain = Op.getOperand(0);
6389 SDValue Offset = Op.getOperand(1);
6390 SDValue Handler = Op.getOperand(2);
6391 DebugLoc dl = Op.getDebugLoc();
6393 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6395 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6397 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6398 DAG.getIntPtrConstant(-TD->getPointerSize()));
6399 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6400 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6401 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6402 MF.getRegInfo().addLiveOut(StoreAddrReg);
6404 return DAG.getNode(X86ISD::EH_RETURN, dl,
6406 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6409 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6410 SelectionDAG &DAG) {
6411 SDValue Root = Op.getOperand(0);
6412 SDValue Trmp = Op.getOperand(1); // trampoline
6413 SDValue FPtr = Op.getOperand(2); // nested function
6414 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6415 DebugLoc dl = Op.getDebugLoc();
6417 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6419 const X86InstrInfo *TII =
6420 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6422 if (Subtarget->is64Bit()) {
6423 SDValue OutChains[6];
6425 // Large code-model.
6427 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6428 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6430 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6431 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6433 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6435 // Load the pointer to the nested function into R11.
6436 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6437 SDValue Addr = Trmp;
6438 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6441 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6442 DAG.getConstant(2, MVT::i64));
6443 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6445 // Load the 'nest' parameter value into R10.
6446 // R10 is specified in X86CallingConv.td
6447 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6448 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6449 DAG.getConstant(10, MVT::i64));
6450 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6451 Addr, TrmpAddr, 10);
6453 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6454 DAG.getConstant(12, MVT::i64));
6455 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6457 // Jump to the nested function.
6458 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6459 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6460 DAG.getConstant(20, MVT::i64));
6461 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6462 Addr, TrmpAddr, 20);
6464 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6465 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6466 DAG.getConstant(22, MVT::i64));
6467 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6471 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6472 return DAG.getMergeValues(Ops, 2, dl);
6474 const Function *Func =
6475 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6476 unsigned CC = Func->getCallingConv();
6481 llvm_unreachable("Unsupported calling convention");
6482 case CallingConv::C:
6483 case CallingConv::X86_StdCall: {
6484 // Pass 'nest' parameter in ECX.
6485 // Must be kept in sync with X86CallingConv.td
6488 // Check that ECX wasn't needed by an 'inreg' parameter.
6489 const FunctionType *FTy = Func->getFunctionType();
6490 const AttrListPtr &Attrs = Func->getAttributes();
6492 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6493 unsigned InRegCount = 0;
6496 for (FunctionType::param_iterator I = FTy->param_begin(),
6497 E = FTy->param_end(); I != E; ++I, ++Idx)
6498 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6499 // FIXME: should only count parameters that are lowered to integers.
6500 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6502 if (InRegCount > 2) {
6503 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6508 case CallingConv::X86_FastCall:
6509 case CallingConv::Fast:
6510 // Pass 'nest' parameter in EAX.
6511 // Must be kept in sync with X86CallingConv.td
6516 SDValue OutChains[4];
6519 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6520 DAG.getConstant(10, MVT::i32));
6521 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6523 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6524 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6525 OutChains[0] = DAG.getStore(Root, dl,
6526 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6529 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6530 DAG.getConstant(1, MVT::i32));
6531 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6533 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6534 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6535 DAG.getConstant(5, MVT::i32));
6536 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6537 TrmpAddr, 5, false, 1);
6539 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6540 DAG.getConstant(6, MVT::i32));
6541 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6544 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6545 return DAG.getMergeValues(Ops, 2, dl);
6549 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6551 The rounding mode is in bits 11:10 of FPSR, and has the following
6558 FLT_ROUNDS, on the other hand, expects the following:
6565 To perform the conversion, we do:
6566 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6569 MachineFunction &MF = DAG.getMachineFunction();
6570 const TargetMachine &TM = MF.getTarget();
6571 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6572 unsigned StackAlignment = TFI.getStackAlignment();
6573 EVT VT = Op.getValueType();
6574 DebugLoc dl = Op.getDebugLoc();
6576 // Save FP Control Word to stack slot
6577 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6578 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6580 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6581 DAG.getEntryNode(), StackSlot);
6583 // Load FP Control Word from stack slot
6584 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6586 // Transform as necessary
6588 DAG.getNode(ISD::SRL, dl, MVT::i16,
6589 DAG.getNode(ISD::AND, dl, MVT::i16,
6590 CWD, DAG.getConstant(0x800, MVT::i16)),
6591 DAG.getConstant(11, MVT::i8));
6593 DAG.getNode(ISD::SRL, dl, MVT::i16,
6594 DAG.getNode(ISD::AND, dl, MVT::i16,
6595 CWD, DAG.getConstant(0x400, MVT::i16)),
6596 DAG.getConstant(9, MVT::i8));
6599 DAG.getNode(ISD::AND, dl, MVT::i16,
6600 DAG.getNode(ISD::ADD, dl, MVT::i16,
6601 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6602 DAG.getConstant(1, MVT::i16)),
6603 DAG.getConstant(3, MVT::i16));
6606 return DAG.getNode((VT.getSizeInBits() < 16 ?
6607 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6610 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6611 EVT VT = Op.getValueType();
6613 unsigned NumBits = VT.getSizeInBits();
6614 DebugLoc dl = Op.getDebugLoc();
6616 Op = Op.getOperand(0);
6617 if (VT == MVT::i8) {
6618 // Zero extend to i32 since there is not an i8 bsr.
6620 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6623 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6624 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6625 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6627 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6628 SmallVector<SDValue, 4> Ops;
6630 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6631 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6632 Ops.push_back(Op.getValue(1));
6633 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6635 // Finally xor with NumBits-1.
6636 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6639 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6643 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6644 EVT VT = Op.getValueType();
6646 unsigned NumBits = VT.getSizeInBits();
6647 DebugLoc dl = Op.getDebugLoc();
6649 Op = Op.getOperand(0);
6650 if (VT == MVT::i8) {
6652 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6655 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6656 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6657 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6659 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6660 SmallVector<SDValue, 4> Ops;
6662 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6663 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6664 Ops.push_back(Op.getValue(1));
6665 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6668 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6672 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6673 EVT VT = Op.getValueType();
6674 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6675 DebugLoc dl = Op.getDebugLoc();
6677 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6678 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6679 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6680 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6681 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6683 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6684 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6685 // return AloBlo + AloBhi + AhiBlo;
6687 SDValue A = Op.getOperand(0);
6688 SDValue B = Op.getOperand(1);
6690 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6691 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6692 A, DAG.getConstant(32, MVT::i32));
6693 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6694 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6695 B, DAG.getConstant(32, MVT::i32));
6696 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6697 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6699 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6700 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6702 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6703 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6705 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6706 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6707 AloBhi, DAG.getConstant(32, MVT::i32));
6708 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6709 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6710 AhiBlo, DAG.getConstant(32, MVT::i32));
6711 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6712 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6717 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6718 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6719 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6720 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6721 // has only one use.
6722 SDNode *N = Op.getNode();
6723 SDValue LHS = N->getOperand(0);
6724 SDValue RHS = N->getOperand(1);
6725 unsigned BaseOp = 0;
6727 DebugLoc dl = Op.getDebugLoc();
6729 switch (Op.getOpcode()) {
6730 default: llvm_unreachable("Unknown ovf instruction!");
6732 // A subtract of one will be selected as a INC. Note that INC doesn't
6733 // set CF, so we can't do this for UADDO.
6734 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6735 if (C->getAPIntValue() == 1) {
6736 BaseOp = X86ISD::INC;
6740 BaseOp = X86ISD::ADD;
6744 BaseOp = X86ISD::ADD;
6748 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6749 // set CF, so we can't do this for USUBO.
6750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6751 if (C->getAPIntValue() == 1) {
6752 BaseOp = X86ISD::DEC;
6756 BaseOp = X86ISD::SUB;
6760 BaseOp = X86ISD::SUB;
6764 BaseOp = X86ISD::SMUL;
6768 BaseOp = X86ISD::UMUL;
6773 // Also sets EFLAGS.
6774 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6775 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6778 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6779 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6781 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6785 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6786 EVT T = Op.getValueType();
6787 DebugLoc dl = Op.getDebugLoc();
6790 switch(T.getSimpleVT().SimpleTy) {
6792 assert(false && "Invalid value type!");
6793 case MVT::i8: Reg = X86::AL; size = 1; break;
6794 case MVT::i16: Reg = X86::AX; size = 2; break;
6795 case MVT::i32: Reg = X86::EAX; size = 4; break;
6797 assert(Subtarget->is64Bit() && "Node not type legal!");
6798 Reg = X86::RAX; size = 8;
6801 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6802 Op.getOperand(2), SDValue());
6803 SDValue Ops[] = { cpIn.getValue(0),
6806 DAG.getTargetConstant(size, MVT::i8),
6808 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6809 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6811 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6815 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6816 SelectionDAG &DAG) {
6817 assert(Subtarget->is64Bit() && "Result not type legalized?");
6818 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6819 SDValue TheChain = Op.getOperand(0);
6820 DebugLoc dl = Op.getDebugLoc();
6821 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6822 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6823 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6825 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6826 DAG.getConstant(32, MVT::i8));
6828 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6831 return DAG.getMergeValues(Ops, 2, dl);
6834 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6835 SDNode *Node = Op.getNode();
6836 DebugLoc dl = Node->getDebugLoc();
6837 EVT T = Node->getValueType(0);
6838 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6839 DAG.getConstant(0, T), Node->getOperand(2));
6840 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6841 cast<AtomicSDNode>(Node)->getMemoryVT(),
6842 Node->getOperand(0),
6843 Node->getOperand(1), negOp,
6844 cast<AtomicSDNode>(Node)->getSrcValue(),
6845 cast<AtomicSDNode>(Node)->getAlignment());
6848 /// LowerOperation - Provide custom lowering hooks for some operations.
6850 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6851 switch (Op.getOpcode()) {
6852 default: llvm_unreachable("Should not custom lower this!");
6853 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6854 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6855 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6856 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6857 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6858 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6859 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6860 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6861 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6862 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6863 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6864 case ISD::SHL_PARTS:
6865 case ISD::SRA_PARTS:
6866 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6867 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6868 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6869 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6870 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6871 case ISD::FABS: return LowerFABS(Op, DAG);
6872 case ISD::FNEG: return LowerFNEG(Op, DAG);
6873 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6874 case ISD::SETCC: return LowerSETCC(Op, DAG);
6875 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6876 case ISD::SELECT: return LowerSELECT(Op, DAG);
6877 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6878 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6879 case ISD::VASTART: return LowerVASTART(Op, DAG);
6880 case ISD::VAARG: return LowerVAARG(Op, DAG);
6881 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6882 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6883 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6884 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6885 case ISD::FRAME_TO_ARGS_OFFSET:
6886 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6887 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6888 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6889 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6890 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6891 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6892 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6893 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6899 case ISD::UMULO: return LowerXALUO(Op, DAG);
6900 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6904 void X86TargetLowering::
6905 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6906 SelectionDAG &DAG, unsigned NewOp) {
6907 EVT T = Node->getValueType(0);
6908 DebugLoc dl = Node->getDebugLoc();
6909 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6911 SDValue Chain = Node->getOperand(0);
6912 SDValue In1 = Node->getOperand(1);
6913 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6914 Node->getOperand(2), DAG.getIntPtrConstant(0));
6915 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6916 Node->getOperand(2), DAG.getIntPtrConstant(1));
6917 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6918 // have a MemOperand. Pass the info through as a normal operand.
6919 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6920 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6921 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6922 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6923 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6924 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6925 Results.push_back(Result.getValue(2));
6928 /// ReplaceNodeResults - Replace a node with an illegal result type
6929 /// with a new node built out of custom code.
6930 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6931 SmallVectorImpl<SDValue>&Results,
6932 SelectionDAG &DAG) {
6933 DebugLoc dl = N->getDebugLoc();
6934 switch (N->getOpcode()) {
6936 assert(false && "Do not know how to custom type legalize this operation!");
6938 case ISD::FP_TO_SINT: {
6939 std::pair<SDValue,SDValue> Vals =
6940 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6941 SDValue FIST = Vals.first, StackSlot = Vals.second;
6942 if (FIST.getNode() != 0) {
6943 EVT VT = N->getValueType(0);
6944 // Return a load from the stack slot.
6945 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6949 case ISD::READCYCLECOUNTER: {
6950 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6951 SDValue TheChain = N->getOperand(0);
6952 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6953 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6955 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6957 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6958 SDValue Ops[] = { eax, edx };
6959 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6960 Results.push_back(edx.getValue(1));
6963 case ISD::ATOMIC_CMP_SWAP: {
6964 EVT T = N->getValueType(0);
6965 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6966 SDValue cpInL, cpInH;
6967 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6968 DAG.getConstant(0, MVT::i32));
6969 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6970 DAG.getConstant(1, MVT::i32));
6971 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6972 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6974 SDValue swapInL, swapInH;
6975 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6976 DAG.getConstant(0, MVT::i32));
6977 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6978 DAG.getConstant(1, MVT::i32));
6979 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6981 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6982 swapInL.getValue(1));
6983 SDValue Ops[] = { swapInH.getValue(0),
6985 swapInH.getValue(1) };
6986 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6987 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6988 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6989 MVT::i32, Result.getValue(1));
6990 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6991 MVT::i32, cpOutL.getValue(2));
6992 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6993 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6994 Results.push_back(cpOutH.getValue(1));
6997 case ISD::ATOMIC_LOAD_ADD:
6998 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7000 case ISD::ATOMIC_LOAD_AND:
7001 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7003 case ISD::ATOMIC_LOAD_NAND:
7004 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7006 case ISD::ATOMIC_LOAD_OR:
7007 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7009 case ISD::ATOMIC_LOAD_SUB:
7010 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7012 case ISD::ATOMIC_LOAD_XOR:
7013 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7015 case ISD::ATOMIC_SWAP:
7016 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7021 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7023 default: return NULL;
7024 case X86ISD::BSF: return "X86ISD::BSF";
7025 case X86ISD::BSR: return "X86ISD::BSR";
7026 case X86ISD::SHLD: return "X86ISD::SHLD";
7027 case X86ISD::SHRD: return "X86ISD::SHRD";
7028 case X86ISD::FAND: return "X86ISD::FAND";
7029 case X86ISD::FOR: return "X86ISD::FOR";
7030 case X86ISD::FXOR: return "X86ISD::FXOR";
7031 case X86ISD::FSRL: return "X86ISD::FSRL";
7032 case X86ISD::FILD: return "X86ISD::FILD";
7033 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7034 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7035 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7036 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7037 case X86ISD::FLD: return "X86ISD::FLD";
7038 case X86ISD::FST: return "X86ISD::FST";
7039 case X86ISD::CALL: return "X86ISD::CALL";
7040 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7041 case X86ISD::BT: return "X86ISD::BT";
7042 case X86ISD::CMP: return "X86ISD::CMP";
7043 case X86ISD::COMI: return "X86ISD::COMI";
7044 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7045 case X86ISD::SETCC: return "X86ISD::SETCC";
7046 case X86ISD::CMOV: return "X86ISD::CMOV";
7047 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7048 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7049 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7050 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7051 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7052 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7053 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7054 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7055 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7056 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7057 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7058 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7059 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7060 case X86ISD::FMAX: return "X86ISD::FMAX";
7061 case X86ISD::FMIN: return "X86ISD::FMIN";
7062 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7063 case X86ISD::FRCP: return "X86ISD::FRCP";
7064 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7065 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7066 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7067 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7068 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7069 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7070 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7071 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7072 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7073 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7074 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7075 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7076 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7077 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7078 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7079 case X86ISD::VSHL: return "X86ISD::VSHL";
7080 case X86ISD::VSRL: return "X86ISD::VSRL";
7081 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7082 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7083 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7084 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7085 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7086 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7087 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7088 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7089 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7090 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7091 case X86ISD::ADD: return "X86ISD::ADD";
7092 case X86ISD::SUB: return "X86ISD::SUB";
7093 case X86ISD::SMUL: return "X86ISD::SMUL";
7094 case X86ISD::UMUL: return "X86ISD::UMUL";
7095 case X86ISD::INC: return "X86ISD::INC";
7096 case X86ISD::DEC: return "X86ISD::DEC";
7097 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7098 case X86ISD::PTEST: return "X86ISD::PTEST";
7099 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7103 // isLegalAddressingMode - Return true if the addressing mode represented
7104 // by AM is legal for this target, for a load/store of the specified type.
7105 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7106 const Type *Ty) const {
7107 // X86 supports extremely general addressing modes.
7108 CodeModel::Model M = getTargetMachine().getCodeModel();
7110 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7111 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7116 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7118 // If a reference to this global requires an extra load, we can't fold it.
7119 if (isGlobalStubReference(GVFlags))
7122 // If BaseGV requires a register for the PIC base, we cannot also have a
7123 // BaseReg specified.
7124 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7127 // If lower 4G is not available, then we must use rip-relative addressing.
7128 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7138 // These scales always work.
7143 // These scales are formed with basereg+scalereg. Only accept if there is
7148 default: // Other stuff never works.
7156 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7157 if (!Ty1->isInteger() || !Ty2->isInteger())
7159 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7160 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7161 if (NumBits1 <= NumBits2)
7163 return Subtarget->is64Bit() || NumBits1 < 64;
7166 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7167 if (!VT1.isInteger() || !VT2.isInteger())
7169 unsigned NumBits1 = VT1.getSizeInBits();
7170 unsigned NumBits2 = VT2.getSizeInBits();
7171 if (NumBits1 <= NumBits2)
7173 return Subtarget->is64Bit() || NumBits1 < 64;
7176 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7177 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7178 return Ty1 == Type::getInt32Ty(Ty1->getContext()) &&
7179 Ty2 == Type::getInt64Ty(Ty1->getContext()) && Subtarget->is64Bit();
7182 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7183 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7184 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7187 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7188 // i16 instructions are longer (0x66 prefix) and potentially slower.
7189 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7192 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7193 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7194 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7195 /// are assumed to be legal.
7197 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7199 // Only do shuffles on 128-bit vector types for now.
7200 if (VT.getSizeInBits() == 64)
7203 // FIXME: pshufb, blends, palignr, shifts.
7204 return (VT.getVectorNumElements() == 2 ||
7205 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7206 isMOVLMask(M, VT) ||
7207 isSHUFPMask(M, VT) ||
7208 isPSHUFDMask(M, VT) ||
7209 isPSHUFHWMask(M, VT) ||
7210 isPSHUFLWMask(M, VT) ||
7211 isUNPCKLMask(M, VT) ||
7212 isUNPCKHMask(M, VT) ||
7213 isUNPCKL_v_undef_Mask(M, VT) ||
7214 isUNPCKH_v_undef_Mask(M, VT));
7218 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7220 unsigned NumElts = VT.getVectorNumElements();
7221 // FIXME: This collection of masks seems suspect.
7224 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7225 return (isMOVLMask(Mask, VT) ||
7226 isCommutedMOVLMask(Mask, VT, true) ||
7227 isSHUFPMask(Mask, VT) ||
7228 isCommutedSHUFPMask(Mask, VT));
7233 //===----------------------------------------------------------------------===//
7234 // X86 Scheduler Hooks
7235 //===----------------------------------------------------------------------===//
7237 // private utility function
7239 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7240 MachineBasicBlock *MBB,
7248 TargetRegisterClass *RC,
7249 bool invSrc) const {
7250 // For the atomic bitwise operator, we generate
7253 // ld t1 = [bitinstr.addr]
7254 // op t2 = t1, [bitinstr.val]
7256 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7258 // fallthrough -->nextMBB
7259 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7260 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7261 MachineFunction::iterator MBBIter = MBB;
7264 /// First build the CFG
7265 MachineFunction *F = MBB->getParent();
7266 MachineBasicBlock *thisMBB = MBB;
7267 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7268 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7269 F->insert(MBBIter, newMBB);
7270 F->insert(MBBIter, nextMBB);
7272 // Move all successors to thisMBB to nextMBB
7273 nextMBB->transferSuccessors(thisMBB);
7275 // Update thisMBB to fall through to newMBB
7276 thisMBB->addSuccessor(newMBB);
7278 // newMBB jumps to itself and fall through to nextMBB
7279 newMBB->addSuccessor(nextMBB);
7280 newMBB->addSuccessor(newMBB);
7282 // Insert instructions into newMBB based on incoming instruction
7283 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7284 "unexpected number of operands");
7285 DebugLoc dl = bInstr->getDebugLoc();
7286 MachineOperand& destOper = bInstr->getOperand(0);
7287 MachineOperand* argOpers[2 + X86AddrNumOperands];
7288 int numArgs = bInstr->getNumOperands() - 1;
7289 for (int i=0; i < numArgs; ++i)
7290 argOpers[i] = &bInstr->getOperand(i+1);
7292 // x86 address has 4 operands: base, index, scale, and displacement
7293 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7294 int valArgIndx = lastAddrIndx + 1;
7296 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7297 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7298 for (int i=0; i <= lastAddrIndx; ++i)
7299 (*MIB).addOperand(*argOpers[i]);
7301 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7303 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7308 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7309 assert((argOpers[valArgIndx]->isReg() ||
7310 argOpers[valArgIndx]->isImm()) &&
7312 if (argOpers[valArgIndx]->isReg())
7313 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7315 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7317 (*MIB).addOperand(*argOpers[valArgIndx]);
7319 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7322 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7323 for (int i=0; i <= lastAddrIndx; ++i)
7324 (*MIB).addOperand(*argOpers[i]);
7326 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7327 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7329 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7333 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7335 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7339 // private utility function: 64 bit atomics on 32 bit host.
7341 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7342 MachineBasicBlock *MBB,
7347 bool invSrc) const {
7348 // For the atomic bitwise operator, we generate
7349 // thisMBB (instructions are in pairs, except cmpxchg8b)
7350 // ld t1,t2 = [bitinstr.addr]
7352 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7353 // op t5, t6 <- out1, out2, [bitinstr.val]
7354 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7355 // mov ECX, EBX <- t5, t6
7356 // mov EAX, EDX <- t1, t2
7357 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7358 // mov t3, t4 <- EAX, EDX
7360 // result in out1, out2
7361 // fallthrough -->nextMBB
7363 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7364 const unsigned LoadOpc = X86::MOV32rm;
7365 const unsigned copyOpc = X86::MOV32rr;
7366 const unsigned NotOpc = X86::NOT32r;
7367 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7368 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7369 MachineFunction::iterator MBBIter = MBB;
7372 /// First build the CFG
7373 MachineFunction *F = MBB->getParent();
7374 MachineBasicBlock *thisMBB = MBB;
7375 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7376 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7377 F->insert(MBBIter, newMBB);
7378 F->insert(MBBIter, nextMBB);
7380 // Move all successors to thisMBB to nextMBB
7381 nextMBB->transferSuccessors(thisMBB);
7383 // Update thisMBB to fall through to newMBB
7384 thisMBB->addSuccessor(newMBB);
7386 // newMBB jumps to itself and fall through to nextMBB
7387 newMBB->addSuccessor(nextMBB);
7388 newMBB->addSuccessor(newMBB);
7390 DebugLoc dl = bInstr->getDebugLoc();
7391 // Insert instructions into newMBB based on incoming instruction
7392 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7393 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7394 "unexpected number of operands");
7395 MachineOperand& dest1Oper = bInstr->getOperand(0);
7396 MachineOperand& dest2Oper = bInstr->getOperand(1);
7397 MachineOperand* argOpers[2 + X86AddrNumOperands];
7398 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7399 argOpers[i] = &bInstr->getOperand(i+2);
7401 // x86 address has 4 operands: base, index, scale, and displacement
7402 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7404 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7405 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7406 for (int i=0; i <= lastAddrIndx; ++i)
7407 (*MIB).addOperand(*argOpers[i]);
7408 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7409 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7410 // add 4 to displacement.
7411 for (int i=0; i <= lastAddrIndx-2; ++i)
7412 (*MIB).addOperand(*argOpers[i]);
7413 MachineOperand newOp3 = *(argOpers[3]);
7415 newOp3.setImm(newOp3.getImm()+4);
7417 newOp3.setOffset(newOp3.getOffset()+4);
7418 (*MIB).addOperand(newOp3);
7419 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7421 // t3/4 are defined later, at the bottom of the loop
7422 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7423 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7424 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7425 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7426 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7427 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7429 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7430 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7432 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7433 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7439 int valArgIndx = lastAddrIndx + 1;
7440 assert((argOpers[valArgIndx]->isReg() ||
7441 argOpers[valArgIndx]->isImm()) &&
7443 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7444 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7445 if (argOpers[valArgIndx]->isReg())
7446 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7448 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7449 if (regOpcL != X86::MOV32rr)
7451 (*MIB).addOperand(*argOpers[valArgIndx]);
7452 assert(argOpers[valArgIndx + 1]->isReg() ==
7453 argOpers[valArgIndx]->isReg());
7454 assert(argOpers[valArgIndx + 1]->isImm() ==
7455 argOpers[valArgIndx]->isImm());
7456 if (argOpers[valArgIndx + 1]->isReg())
7457 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7459 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7460 if (regOpcH != X86::MOV32rr)
7462 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7464 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7466 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7469 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7471 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7474 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7475 for (int i=0; i <= lastAddrIndx; ++i)
7476 (*MIB).addOperand(*argOpers[i]);
7478 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7479 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7481 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7482 MIB.addReg(X86::EAX);
7483 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7484 MIB.addReg(X86::EDX);
7487 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7489 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7493 // private utility function
7495 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7496 MachineBasicBlock *MBB,
7497 unsigned cmovOpc) const {
7498 // For the atomic min/max operator, we generate
7501 // ld t1 = [min/max.addr]
7502 // mov t2 = [min/max.val]
7504 // cmov[cond] t2 = t1
7506 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7508 // fallthrough -->nextMBB
7510 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7511 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7512 MachineFunction::iterator MBBIter = MBB;
7515 /// First build the CFG
7516 MachineFunction *F = MBB->getParent();
7517 MachineBasicBlock *thisMBB = MBB;
7518 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7519 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7520 F->insert(MBBIter, newMBB);
7521 F->insert(MBBIter, nextMBB);
7523 // Move all successors of thisMBB to nextMBB
7524 nextMBB->transferSuccessors(thisMBB);
7526 // Update thisMBB to fall through to newMBB
7527 thisMBB->addSuccessor(newMBB);
7529 // newMBB jumps to newMBB and fall through to nextMBB
7530 newMBB->addSuccessor(nextMBB);
7531 newMBB->addSuccessor(newMBB);
7533 DebugLoc dl = mInstr->getDebugLoc();
7534 // Insert instructions into newMBB based on incoming instruction
7535 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7536 "unexpected number of operands");
7537 MachineOperand& destOper = mInstr->getOperand(0);
7538 MachineOperand* argOpers[2 + X86AddrNumOperands];
7539 int numArgs = mInstr->getNumOperands() - 1;
7540 for (int i=0; i < numArgs; ++i)
7541 argOpers[i] = &mInstr->getOperand(i+1);
7543 // x86 address has 4 operands: base, index, scale, and displacement
7544 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7545 int valArgIndx = lastAddrIndx + 1;
7547 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7548 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7549 for (int i=0; i <= lastAddrIndx; ++i)
7550 (*MIB).addOperand(*argOpers[i]);
7552 // We only support register and immediate values
7553 assert((argOpers[valArgIndx]->isReg() ||
7554 argOpers[valArgIndx]->isImm()) &&
7557 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7558 if (argOpers[valArgIndx]->isReg())
7559 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7561 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7562 (*MIB).addOperand(*argOpers[valArgIndx]);
7564 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7567 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7572 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7573 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7577 // Cmp and exchange if none has modified the memory location
7578 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7579 for (int i=0; i <= lastAddrIndx; ++i)
7580 (*MIB).addOperand(*argOpers[i]);
7582 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7583 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7585 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7586 MIB.addReg(X86::EAX);
7589 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7591 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7596 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
7598 MachineBasicBlock *MBB) const {
7599 // Emit code to save XMM registers to the stack. The ABI says that the
7600 // number of registers to save is given in %al, so it's theoretically
7601 // possible to do an indirect jump trick to avoid saving all of them,
7602 // however this code takes a simpler approach and just executes all
7603 // of the stores if %al is non-zero. It's less code, and it's probably
7604 // easier on the hardware branch predictor, and stores aren't all that
7605 // expensive anyway.
7607 // Create the new basic blocks. One block contains all the XMM stores,
7608 // and one block is the final destination regardless of whether any
7609 // stores were performed.
7610 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7611 MachineFunction *F = MBB->getParent();
7612 MachineFunction::iterator MBBIter = MBB;
7614 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
7615 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
7616 F->insert(MBBIter, XMMSaveMBB);
7617 F->insert(MBBIter, EndMBB);
7620 // Move any original successors of MBB to the end block.
7621 EndMBB->transferSuccessors(MBB);
7622 // The original block will now fall through to the XMM save block.
7623 MBB->addSuccessor(XMMSaveMBB);
7624 // The XMMSaveMBB will fall through to the end block.
7625 XMMSaveMBB->addSuccessor(EndMBB);
7627 // Now add the instructions.
7628 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7629 DebugLoc DL = MI->getDebugLoc();
7631 unsigned CountReg = MI->getOperand(0).getReg();
7632 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
7633 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
7635 if (!Subtarget->isTargetWin64()) {
7636 // If %al is 0, branch around the XMM save block.
7637 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
7638 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
7639 MBB->addSuccessor(EndMBB);
7642 // In the XMM save block, save all the XMM argument registers.
7643 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
7644 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
7645 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
7646 .addFrameIndex(RegSaveFrameIndex)
7647 .addImm(/*Scale=*/1)
7648 .addReg(/*IndexReg=*/0)
7649 .addImm(/*Disp=*/Offset)
7650 .addReg(/*Segment=*/0)
7651 .addReg(MI->getOperand(i).getReg())
7652 .addMemOperand(MachineMemOperand(
7653 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
7654 MachineMemOperand::MOStore, Offset,
7655 /*Size=*/16, /*Align=*/16));
7658 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7664 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7665 MachineBasicBlock *BB) const {
7666 DebugLoc dl = MI->getDebugLoc();
7667 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7668 switch (MI->getOpcode()) {
7669 default: assert(false && "Unexpected instr type to insert");
7670 case X86::CMOV_V1I64:
7671 case X86::CMOV_FR32:
7672 case X86::CMOV_FR64:
7673 case X86::CMOV_V4F32:
7674 case X86::CMOV_V2F64:
7675 case X86::CMOV_V2I64: {
7676 // To "insert" a SELECT_CC instruction, we actually have to insert the
7677 // diamond control-flow pattern. The incoming instruction knows the
7678 // destination vreg to set, the condition code register to branch on, the
7679 // true/false values to select between, and a branch opcode to use.
7680 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7681 MachineFunction::iterator It = BB;
7687 // cmpTY ccX, r1, r2
7689 // fallthrough --> copy0MBB
7690 MachineBasicBlock *thisMBB = BB;
7691 MachineFunction *F = BB->getParent();
7692 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7693 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7695 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7696 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7697 F->insert(It, copy0MBB);
7698 F->insert(It, sinkMBB);
7699 // Update machine-CFG edges by transferring all successors of the current
7700 // block to the new block which will contain the Phi node for the select.
7701 sinkMBB->transferSuccessors(BB);
7703 // Add the true and fallthrough blocks as its successors.
7704 BB->addSuccessor(copy0MBB);
7705 BB->addSuccessor(sinkMBB);
7708 // %FalseValue = ...
7709 // # fallthrough to sinkMBB
7712 // Update machine-CFG edges
7713 BB->addSuccessor(sinkMBB);
7716 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7719 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7720 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7721 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7723 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7727 case X86::FP32_TO_INT16_IN_MEM:
7728 case X86::FP32_TO_INT32_IN_MEM:
7729 case X86::FP32_TO_INT64_IN_MEM:
7730 case X86::FP64_TO_INT16_IN_MEM:
7731 case X86::FP64_TO_INT32_IN_MEM:
7732 case X86::FP64_TO_INT64_IN_MEM:
7733 case X86::FP80_TO_INT16_IN_MEM:
7734 case X86::FP80_TO_INT32_IN_MEM:
7735 case X86::FP80_TO_INT64_IN_MEM: {
7736 // Change the floating point control register to use "round towards zero"
7737 // mode when truncating to an integer value.
7738 MachineFunction *F = BB->getParent();
7739 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7740 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7742 // Load the old value of the high byte of the control word...
7744 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7745 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7748 // Set the high part to be round to zero...
7749 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7752 // Reload the modified control word now...
7753 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7755 // Restore the memory image of control word to original value
7756 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7759 // Get the X86 opcode to use.
7761 switch (MI->getOpcode()) {
7762 default: llvm_unreachable("illegal opcode!");
7763 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7764 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7765 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7766 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7767 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7768 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7769 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7770 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7771 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7775 MachineOperand &Op = MI->getOperand(0);
7777 AM.BaseType = X86AddressMode::RegBase;
7778 AM.Base.Reg = Op.getReg();
7780 AM.BaseType = X86AddressMode::FrameIndexBase;
7781 AM.Base.FrameIndex = Op.getIndex();
7783 Op = MI->getOperand(1);
7785 AM.Scale = Op.getImm();
7786 Op = MI->getOperand(2);
7788 AM.IndexReg = Op.getImm();
7789 Op = MI->getOperand(3);
7790 if (Op.isGlobal()) {
7791 AM.GV = Op.getGlobal();
7793 AM.Disp = Op.getImm();
7795 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7796 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7798 // Reload the original control word now.
7799 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7801 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7804 case X86::ATOMAND32:
7805 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7806 X86::AND32ri, X86::MOV32rm,
7807 X86::LCMPXCHG32, X86::MOV32rr,
7808 X86::NOT32r, X86::EAX,
7809 X86::GR32RegisterClass);
7811 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7812 X86::OR32ri, X86::MOV32rm,
7813 X86::LCMPXCHG32, X86::MOV32rr,
7814 X86::NOT32r, X86::EAX,
7815 X86::GR32RegisterClass);
7816 case X86::ATOMXOR32:
7817 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7818 X86::XOR32ri, X86::MOV32rm,
7819 X86::LCMPXCHG32, X86::MOV32rr,
7820 X86::NOT32r, X86::EAX,
7821 X86::GR32RegisterClass);
7822 case X86::ATOMNAND32:
7823 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7824 X86::AND32ri, X86::MOV32rm,
7825 X86::LCMPXCHG32, X86::MOV32rr,
7826 X86::NOT32r, X86::EAX,
7827 X86::GR32RegisterClass, true);
7828 case X86::ATOMMIN32:
7829 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7830 case X86::ATOMMAX32:
7831 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7832 case X86::ATOMUMIN32:
7833 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7834 case X86::ATOMUMAX32:
7835 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7837 case X86::ATOMAND16:
7838 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7839 X86::AND16ri, X86::MOV16rm,
7840 X86::LCMPXCHG16, X86::MOV16rr,
7841 X86::NOT16r, X86::AX,
7842 X86::GR16RegisterClass);
7844 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7845 X86::OR16ri, X86::MOV16rm,
7846 X86::LCMPXCHG16, X86::MOV16rr,
7847 X86::NOT16r, X86::AX,
7848 X86::GR16RegisterClass);
7849 case X86::ATOMXOR16:
7850 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7851 X86::XOR16ri, X86::MOV16rm,
7852 X86::LCMPXCHG16, X86::MOV16rr,
7853 X86::NOT16r, X86::AX,
7854 X86::GR16RegisterClass);
7855 case X86::ATOMNAND16:
7856 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7857 X86::AND16ri, X86::MOV16rm,
7858 X86::LCMPXCHG16, X86::MOV16rr,
7859 X86::NOT16r, X86::AX,
7860 X86::GR16RegisterClass, true);
7861 case X86::ATOMMIN16:
7862 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7863 case X86::ATOMMAX16:
7864 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7865 case X86::ATOMUMIN16:
7866 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7867 case X86::ATOMUMAX16:
7868 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7871 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7872 X86::AND8ri, X86::MOV8rm,
7873 X86::LCMPXCHG8, X86::MOV8rr,
7874 X86::NOT8r, X86::AL,
7875 X86::GR8RegisterClass);
7877 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7878 X86::OR8ri, X86::MOV8rm,
7879 X86::LCMPXCHG8, X86::MOV8rr,
7880 X86::NOT8r, X86::AL,
7881 X86::GR8RegisterClass);
7883 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7884 X86::XOR8ri, X86::MOV8rm,
7885 X86::LCMPXCHG8, X86::MOV8rr,
7886 X86::NOT8r, X86::AL,
7887 X86::GR8RegisterClass);
7888 case X86::ATOMNAND8:
7889 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7890 X86::AND8ri, X86::MOV8rm,
7891 X86::LCMPXCHG8, X86::MOV8rr,
7892 X86::NOT8r, X86::AL,
7893 X86::GR8RegisterClass, true);
7894 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7895 // This group is for 64-bit host.
7896 case X86::ATOMAND64:
7897 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7898 X86::AND64ri32, X86::MOV64rm,
7899 X86::LCMPXCHG64, X86::MOV64rr,
7900 X86::NOT64r, X86::RAX,
7901 X86::GR64RegisterClass);
7903 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7904 X86::OR64ri32, X86::MOV64rm,
7905 X86::LCMPXCHG64, X86::MOV64rr,
7906 X86::NOT64r, X86::RAX,
7907 X86::GR64RegisterClass);
7908 case X86::ATOMXOR64:
7909 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7910 X86::XOR64ri32, X86::MOV64rm,
7911 X86::LCMPXCHG64, X86::MOV64rr,
7912 X86::NOT64r, X86::RAX,
7913 X86::GR64RegisterClass);
7914 case X86::ATOMNAND64:
7915 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7916 X86::AND64ri32, X86::MOV64rm,
7917 X86::LCMPXCHG64, X86::MOV64rr,
7918 X86::NOT64r, X86::RAX,
7919 X86::GR64RegisterClass, true);
7920 case X86::ATOMMIN64:
7921 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7922 case X86::ATOMMAX64:
7923 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7924 case X86::ATOMUMIN64:
7925 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7926 case X86::ATOMUMAX64:
7927 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7929 // This group does 64-bit operations on a 32-bit host.
7930 case X86::ATOMAND6432:
7931 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7932 X86::AND32rr, X86::AND32rr,
7933 X86::AND32ri, X86::AND32ri,
7935 case X86::ATOMOR6432:
7936 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7937 X86::OR32rr, X86::OR32rr,
7938 X86::OR32ri, X86::OR32ri,
7940 case X86::ATOMXOR6432:
7941 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7942 X86::XOR32rr, X86::XOR32rr,
7943 X86::XOR32ri, X86::XOR32ri,
7945 case X86::ATOMNAND6432:
7946 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7947 X86::AND32rr, X86::AND32rr,
7948 X86::AND32ri, X86::AND32ri,
7950 case X86::ATOMADD6432:
7951 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7952 X86::ADD32rr, X86::ADC32rr,
7953 X86::ADD32ri, X86::ADC32ri,
7955 case X86::ATOMSUB6432:
7956 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7957 X86::SUB32rr, X86::SBB32rr,
7958 X86::SUB32ri, X86::SBB32ri,
7960 case X86::ATOMSWAP6432:
7961 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7962 X86::MOV32rr, X86::MOV32rr,
7963 X86::MOV32ri, X86::MOV32ri,
7965 case X86::VASTART_SAVE_XMM_REGS:
7966 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
7970 //===----------------------------------------------------------------------===//
7971 // X86 Optimization Hooks
7972 //===----------------------------------------------------------------------===//
7974 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7978 const SelectionDAG &DAG,
7979 unsigned Depth) const {
7980 unsigned Opc = Op.getOpcode();
7981 assert((Opc >= ISD::BUILTIN_OP_END ||
7982 Opc == ISD::INTRINSIC_WO_CHAIN ||
7983 Opc == ISD::INTRINSIC_W_CHAIN ||
7984 Opc == ISD::INTRINSIC_VOID) &&
7985 "Should use MaskedValueIsZero if you don't know whether Op"
7986 " is a target node!");
7988 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7997 // These nodes' second result is a boolean.
7998 if (Op.getResNo() == 0)
8002 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8003 Mask.getBitWidth() - 1);
8008 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8009 /// node is a GlobalAddress + offset.
8010 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8011 GlobalValue* &GA, int64_t &Offset) const{
8012 if (N->getOpcode() == X86ISD::Wrapper) {
8013 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8014 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8015 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8019 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8022 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8023 const TargetLowering &TLI) {
8026 if (TLI.isGAPlusOffset(Base, GV, Offset))
8027 return (GV->getAlignment() >= N && (Offset % N) == 0);
8028 // DAG combine handles the stack object case.
8032 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8033 EVT EVT, LoadSDNode *&LDBase,
8034 unsigned &LastLoadedElt,
8035 SelectionDAG &DAG, MachineFrameInfo *MFI,
8036 const TargetLowering &TLI) {
8038 LastLoadedElt = -1U;
8039 for (unsigned i = 0; i < NumElems; ++i) {
8040 if (N->getMaskElt(i) < 0) {
8046 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8047 if (!Elt.getNode() ||
8048 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8051 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8053 LDBase = cast<LoadSDNode>(Elt.getNode());
8057 if (Elt.getOpcode() == ISD::UNDEF)
8060 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8061 if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
8068 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8069 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8070 /// if the load addresses are consecutive, non-overlapping, and in the right
8071 /// order. In the case of v2i64, it will see if it can rewrite the
8072 /// shuffle to be an appropriate build vector so it can take advantage of
8073 // performBuildVectorCombine.
8074 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8075 const TargetLowering &TLI) {
8076 DebugLoc dl = N->getDebugLoc();
8077 EVT VT = N->getValueType(0);
8078 EVT EVT = VT.getVectorElementType();
8079 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8080 unsigned NumElems = VT.getVectorNumElements();
8082 if (VT.getSizeInBits() != 128)
8085 // Try to combine a vector_shuffle into a 128-bit load.
8086 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8087 LoadSDNode *LD = NULL;
8088 unsigned LastLoadedElt;
8089 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
8093 if (LastLoadedElt == NumElems - 1) {
8094 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
8095 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8096 LD->getSrcValue(), LD->getSrcValueOffset(),
8098 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8099 LD->getSrcValue(), LD->getSrcValueOffset(),
8100 LD->isVolatile(), LD->getAlignment());
8101 } else if (NumElems == 4 && LastLoadedElt == 1) {
8102 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8103 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8104 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8105 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8110 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8111 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8112 const X86Subtarget *Subtarget) {
8113 DebugLoc DL = N->getDebugLoc();
8114 SDValue Cond = N->getOperand(0);
8115 // Get the LHS/RHS of the select.
8116 SDValue LHS = N->getOperand(1);
8117 SDValue RHS = N->getOperand(2);
8119 // If we have SSE[12] support, try to form min/max nodes.
8120 if (Subtarget->hasSSE2() &&
8121 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8122 Cond.getOpcode() == ISD::SETCC) {
8123 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8125 unsigned Opcode = 0;
8126 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8129 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
8132 if (!UnsafeFPMath) break;
8134 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
8136 Opcode = X86ISD::FMIN;
8139 case ISD::SETOGT: // (X > Y) ? X : Y -> max
8142 if (!UnsafeFPMath) break;
8144 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
8146 Opcode = X86ISD::FMAX;
8149 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8152 case ISD::SETOGT: // (X > Y) ? Y : X -> min
8155 if (!UnsafeFPMath) break;
8157 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
8159 Opcode = X86ISD::FMIN;
8162 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
8165 if (!UnsafeFPMath) break;
8167 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
8169 Opcode = X86ISD::FMAX;
8175 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8178 // If this is a select between two integer constants, try to do some
8180 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8181 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8182 // Don't do this for crazy integer types.
8183 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8184 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8185 // so that TrueC (the true value) is larger than FalseC.
8186 bool NeedsCondInvert = false;
8188 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8189 // Efficiently invertible.
8190 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8191 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8192 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8193 NeedsCondInvert = true;
8194 std::swap(TrueC, FalseC);
8197 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8198 if (FalseC->getAPIntValue() == 0 &&
8199 TrueC->getAPIntValue().isPowerOf2()) {
8200 if (NeedsCondInvert) // Invert the condition if needed.
8201 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8202 DAG.getConstant(1, Cond.getValueType()));
8204 // Zero extend the condition if needed.
8205 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8207 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8208 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8209 DAG.getConstant(ShAmt, MVT::i8));
8212 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8213 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8214 if (NeedsCondInvert) // Invert the condition if needed.
8215 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8216 DAG.getConstant(1, Cond.getValueType()));
8218 // Zero extend the condition if needed.
8219 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8220 FalseC->getValueType(0), Cond);
8221 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8222 SDValue(FalseC, 0));
8225 // Optimize cases that will turn into an LEA instruction. This requires
8226 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8227 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8228 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8229 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8231 bool isFastMultiplier = false;
8233 switch ((unsigned char)Diff) {
8235 case 1: // result = add base, cond
8236 case 2: // result = lea base( , cond*2)
8237 case 3: // result = lea base(cond, cond*2)
8238 case 4: // result = lea base( , cond*4)
8239 case 5: // result = lea base(cond, cond*4)
8240 case 8: // result = lea base( , cond*8)
8241 case 9: // result = lea base(cond, cond*8)
8242 isFastMultiplier = true;
8247 if (isFastMultiplier) {
8248 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8249 if (NeedsCondInvert) // Invert the condition if needed.
8250 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8251 DAG.getConstant(1, Cond.getValueType()));
8253 // Zero extend the condition if needed.
8254 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8256 // Scale the condition by the difference.
8258 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8259 DAG.getConstant(Diff, Cond.getValueType()));
8261 // Add the base if non-zero.
8262 if (FalseC->getAPIntValue() != 0)
8263 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8264 SDValue(FalseC, 0));
8274 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8275 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8276 TargetLowering::DAGCombinerInfo &DCI) {
8277 DebugLoc DL = N->getDebugLoc();
8279 // If the flag operand isn't dead, don't touch this CMOV.
8280 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8283 // If this is a select between two integer constants, try to do some
8284 // optimizations. Note that the operands are ordered the opposite of SELECT
8286 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8287 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8288 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8289 // larger than FalseC (the false value).
8290 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8292 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8293 CC = X86::GetOppositeBranchCondition(CC);
8294 std::swap(TrueC, FalseC);
8297 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8298 // This is efficient for any integer data type (including i8/i16) and
8300 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8301 SDValue Cond = N->getOperand(3);
8302 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8303 DAG.getConstant(CC, MVT::i8), Cond);
8305 // Zero extend the condition if needed.
8306 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8308 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8309 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8310 DAG.getConstant(ShAmt, MVT::i8));
8311 if (N->getNumValues() == 2) // Dead flag value?
8312 return DCI.CombineTo(N, Cond, SDValue());
8316 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8317 // for any integer data type, including i8/i16.
8318 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8319 SDValue Cond = N->getOperand(3);
8320 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8321 DAG.getConstant(CC, MVT::i8), Cond);
8323 // Zero extend the condition if needed.
8324 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8325 FalseC->getValueType(0), Cond);
8326 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8327 SDValue(FalseC, 0));
8329 if (N->getNumValues() == 2) // Dead flag value?
8330 return DCI.CombineTo(N, Cond, SDValue());
8334 // Optimize cases that will turn into an LEA instruction. This requires
8335 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8336 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8337 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8338 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8340 bool isFastMultiplier = false;
8342 switch ((unsigned char)Diff) {
8344 case 1: // result = add base, cond
8345 case 2: // result = lea base( , cond*2)
8346 case 3: // result = lea base(cond, cond*2)
8347 case 4: // result = lea base( , cond*4)
8348 case 5: // result = lea base(cond, cond*4)
8349 case 8: // result = lea base( , cond*8)
8350 case 9: // result = lea base(cond, cond*8)
8351 isFastMultiplier = true;
8356 if (isFastMultiplier) {
8357 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8358 SDValue Cond = N->getOperand(3);
8359 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8360 DAG.getConstant(CC, MVT::i8), Cond);
8361 // Zero extend the condition if needed.
8362 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8364 // Scale the condition by the difference.
8366 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8367 DAG.getConstant(Diff, Cond.getValueType()));
8369 // Add the base if non-zero.
8370 if (FalseC->getAPIntValue() != 0)
8371 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8372 SDValue(FalseC, 0));
8373 if (N->getNumValues() == 2) // Dead flag value?
8374 return DCI.CombineTo(N, Cond, SDValue());
8384 /// PerformMulCombine - Optimize a single multiply with constant into two
8385 /// in order to implement it with two cheaper instructions, e.g.
8386 /// LEA + SHL, LEA + LEA.
8387 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8388 TargetLowering::DAGCombinerInfo &DCI) {
8389 if (DAG.getMachineFunction().
8390 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8393 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8396 EVT VT = N->getValueType(0);
8400 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8403 uint64_t MulAmt = C->getZExtValue();
8404 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8407 uint64_t MulAmt1 = 0;
8408 uint64_t MulAmt2 = 0;
8409 if ((MulAmt % 9) == 0) {
8411 MulAmt2 = MulAmt / 9;
8412 } else if ((MulAmt % 5) == 0) {
8414 MulAmt2 = MulAmt / 5;
8415 } else if ((MulAmt % 3) == 0) {
8417 MulAmt2 = MulAmt / 3;
8420 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8421 DebugLoc DL = N->getDebugLoc();
8423 if (isPowerOf2_64(MulAmt2) &&
8424 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8425 // If second multiplifer is pow2, issue it first. We want the multiply by
8426 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8428 std::swap(MulAmt1, MulAmt2);
8431 if (isPowerOf2_64(MulAmt1))
8432 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8433 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8435 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8436 DAG.getConstant(MulAmt1, VT));
8438 if (isPowerOf2_64(MulAmt2))
8439 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8440 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8442 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8443 DAG.getConstant(MulAmt2, VT));
8445 // Do not add new nodes to DAG combiner worklist.
8446 DCI.CombineTo(N, NewMul, false);
8452 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8454 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8455 const X86Subtarget *Subtarget) {
8456 // On X86 with SSE2 support, we can transform this to a vector shift if
8457 // all elements are shifted by the same amount. We can't do this in legalize
8458 // because the a constant vector is typically transformed to a constant pool
8459 // so we have no knowledge of the shift amount.
8460 if (!Subtarget->hasSSE2())
8463 EVT VT = N->getValueType(0);
8464 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8467 SDValue ShAmtOp = N->getOperand(1);
8468 EVT EltVT = VT.getVectorElementType();
8469 DebugLoc DL = N->getDebugLoc();
8471 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8472 unsigned NumElts = VT.getVectorNumElements();
8474 for (; i != NumElts; ++i) {
8475 SDValue Arg = ShAmtOp.getOperand(i);
8476 if (Arg.getOpcode() == ISD::UNDEF) continue;
8480 for (; i != NumElts; ++i) {
8481 SDValue Arg = ShAmtOp.getOperand(i);
8482 if (Arg.getOpcode() == ISD::UNDEF) continue;
8483 if (Arg != BaseShAmt) {
8487 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8488 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8489 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8490 DAG.getIntPtrConstant(0));
8494 if (EltVT.bitsGT(MVT::i32))
8495 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8496 else if (EltVT.bitsLT(MVT::i32))
8497 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8499 // The shift amount is identical so we can do a vector shift.
8500 SDValue ValOp = N->getOperand(0);
8501 switch (N->getOpcode()) {
8503 llvm_unreachable("Unknown shift opcode!");
8506 if (VT == MVT::v2i64)
8507 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8508 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8510 if (VT == MVT::v4i32)
8511 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8512 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8514 if (VT == MVT::v8i16)
8515 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8516 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8520 if (VT == MVT::v4i32)
8521 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8522 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8524 if (VT == MVT::v8i16)
8525 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8526 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8530 if (VT == MVT::v2i64)
8531 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8532 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8534 if (VT == MVT::v4i32)
8535 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8536 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8538 if (VT == MVT::v8i16)
8539 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8540 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8547 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8548 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8549 const X86Subtarget *Subtarget) {
8550 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8551 // the FP state in cases where an emms may be missing.
8552 // A preferable solution to the general problem is to figure out the right
8553 // places to insert EMMS. This qualifies as a quick hack.
8555 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8556 StoreSDNode *St = cast<StoreSDNode>(N);
8557 EVT VT = St->getValue().getValueType();
8558 if (VT.getSizeInBits() != 64)
8561 const Function *F = DAG.getMachineFunction().getFunction();
8562 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8563 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8564 && Subtarget->hasSSE2();
8565 if ((VT.isVector() ||
8566 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8567 isa<LoadSDNode>(St->getValue()) &&
8568 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8569 St->getChain().hasOneUse() && !St->isVolatile()) {
8570 SDNode* LdVal = St->getValue().getNode();
8572 int TokenFactorIndex = -1;
8573 SmallVector<SDValue, 8> Ops;
8574 SDNode* ChainVal = St->getChain().getNode();
8575 // Must be a store of a load. We currently handle two cases: the load
8576 // is a direct child, and it's under an intervening TokenFactor. It is
8577 // possible to dig deeper under nested TokenFactors.
8578 if (ChainVal == LdVal)
8579 Ld = cast<LoadSDNode>(St->getChain());
8580 else if (St->getValue().hasOneUse() &&
8581 ChainVal->getOpcode() == ISD::TokenFactor) {
8582 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8583 if (ChainVal->getOperand(i).getNode() == LdVal) {
8584 TokenFactorIndex = i;
8585 Ld = cast<LoadSDNode>(St->getValue());
8587 Ops.push_back(ChainVal->getOperand(i));
8591 if (!Ld || !ISD::isNormalLoad(Ld))
8594 // If this is not the MMX case, i.e. we are just turning i64 load/store
8595 // into f64 load/store, avoid the transformation if there are multiple
8596 // uses of the loaded value.
8597 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8600 DebugLoc LdDL = Ld->getDebugLoc();
8601 DebugLoc StDL = N->getDebugLoc();
8602 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8603 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8605 if (Subtarget->is64Bit() || F64IsLegal) {
8606 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8607 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8608 Ld->getBasePtr(), Ld->getSrcValue(),
8609 Ld->getSrcValueOffset(), Ld->isVolatile(),
8610 Ld->getAlignment());
8611 SDValue NewChain = NewLd.getValue(1);
8612 if (TokenFactorIndex != -1) {
8613 Ops.push_back(NewChain);
8614 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8617 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8618 St->getSrcValue(), St->getSrcValueOffset(),
8619 St->isVolatile(), St->getAlignment());
8622 // Otherwise, lower to two pairs of 32-bit loads / stores.
8623 SDValue LoAddr = Ld->getBasePtr();
8624 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8625 DAG.getConstant(4, MVT::i32));
8627 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8628 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8629 Ld->isVolatile(), Ld->getAlignment());
8630 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8631 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8633 MinAlign(Ld->getAlignment(), 4));
8635 SDValue NewChain = LoLd.getValue(1);
8636 if (TokenFactorIndex != -1) {
8637 Ops.push_back(LoLd);
8638 Ops.push_back(HiLd);
8639 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8643 LoAddr = St->getBasePtr();
8644 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8645 DAG.getConstant(4, MVT::i32));
8647 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8648 St->getSrcValue(), St->getSrcValueOffset(),
8649 St->isVolatile(), St->getAlignment());
8650 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8652 St->getSrcValueOffset() + 4,
8654 MinAlign(St->getAlignment(), 4));
8655 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8660 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8661 /// X86ISD::FXOR nodes.
8662 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8663 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8664 // F[X]OR(0.0, x) -> x
8665 // F[X]OR(x, 0.0) -> x
8666 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8667 if (C->getValueAPF().isPosZero())
8668 return N->getOperand(1);
8669 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8670 if (C->getValueAPF().isPosZero())
8671 return N->getOperand(0);
8675 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8676 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8677 // FAND(0.0, x) -> 0.0
8678 // FAND(x, 0.0) -> 0.0
8679 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8680 if (C->getValueAPF().isPosZero())
8681 return N->getOperand(0);
8682 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8683 if (C->getValueAPF().isPosZero())
8684 return N->getOperand(1);
8688 static SDValue PerformBTCombine(SDNode *N,
8690 TargetLowering::DAGCombinerInfo &DCI) {
8691 // BT ignores high bits in the bit index operand.
8692 SDValue Op1 = N->getOperand(1);
8693 if (Op1.hasOneUse()) {
8694 unsigned BitWidth = Op1.getValueSizeInBits();
8695 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8696 APInt KnownZero, KnownOne;
8697 TargetLowering::TargetLoweringOpt TLO(DAG);
8698 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8699 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8700 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8701 DCI.CommitTargetLoweringOpt(TLO);
8706 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8707 SDValue Op = N->getOperand(0);
8708 if (Op.getOpcode() == ISD::BIT_CONVERT)
8709 Op = Op.getOperand(0);
8710 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
8711 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8712 VT.getVectorElementType().getSizeInBits() ==
8713 OpVT.getVectorElementType().getSizeInBits()) {
8714 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8719 // On X86 and X86-64, atomic operations are lowered to locked instructions.
8720 // Locked instructions, in turn, have implicit fence semantics (all memory
8721 // operations are flushed before issuing the locked instruction, and the
8722 // are not buffered), so we can fold away the common pattern of
8723 // fence-atomic-fence.
8724 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
8725 SDValue atomic = N->getOperand(0);
8726 switch (atomic.getOpcode()) {
8727 case ISD::ATOMIC_CMP_SWAP:
8728 case ISD::ATOMIC_SWAP:
8729 case ISD::ATOMIC_LOAD_ADD:
8730 case ISD::ATOMIC_LOAD_SUB:
8731 case ISD::ATOMIC_LOAD_AND:
8732 case ISD::ATOMIC_LOAD_OR:
8733 case ISD::ATOMIC_LOAD_XOR:
8734 case ISD::ATOMIC_LOAD_NAND:
8735 case ISD::ATOMIC_LOAD_MIN:
8736 case ISD::ATOMIC_LOAD_MAX:
8737 case ISD::ATOMIC_LOAD_UMIN:
8738 case ISD::ATOMIC_LOAD_UMAX:
8744 SDValue fence = atomic.getOperand(0);
8745 if (fence.getOpcode() != ISD::MEMBARRIER)
8748 switch (atomic.getOpcode()) {
8749 case ISD::ATOMIC_CMP_SWAP:
8750 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8751 atomic.getOperand(1), atomic.getOperand(2),
8752 atomic.getOperand(3));
8753 case ISD::ATOMIC_SWAP:
8754 case ISD::ATOMIC_LOAD_ADD:
8755 case ISD::ATOMIC_LOAD_SUB:
8756 case ISD::ATOMIC_LOAD_AND:
8757 case ISD::ATOMIC_LOAD_OR:
8758 case ISD::ATOMIC_LOAD_XOR:
8759 case ISD::ATOMIC_LOAD_NAND:
8760 case ISD::ATOMIC_LOAD_MIN:
8761 case ISD::ATOMIC_LOAD_MAX:
8762 case ISD::ATOMIC_LOAD_UMIN:
8763 case ISD::ATOMIC_LOAD_UMAX:
8764 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8765 atomic.getOperand(1), atomic.getOperand(2));
8771 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8772 DAGCombinerInfo &DCI) const {
8773 SelectionDAG &DAG = DCI.DAG;
8774 switch (N->getOpcode()) {
8776 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8777 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8778 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8779 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8782 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8783 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8785 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8786 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8787 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8788 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
8789 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
8795 //===----------------------------------------------------------------------===//
8796 // X86 Inline Assembly Support
8797 //===----------------------------------------------------------------------===//
8799 static bool LowerToBSwap(CallInst *CI) {
8800 // FIXME: this should verify that we are targetting a 486 or better. If not,
8801 // we will turn this bswap into something that will be lowered to logical ops
8802 // instead of emitting the bswap asm. For now, we don't support 486 or lower
8803 // so don't worry about this.
8805 // Verify this is a simple bswap.
8806 if (CI->getNumOperands() != 2 ||
8807 CI->getType() != CI->getOperand(1)->getType() ||
8808 !CI->getType()->isInteger())
8811 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8812 if (!Ty || Ty->getBitWidth() % 16 != 0)
8815 // Okay, we can do this xform, do so now.
8816 const Type *Tys[] = { Ty };
8817 Module *M = CI->getParent()->getParent()->getParent();
8818 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
8820 Value *Op = CI->getOperand(1);
8821 Op = CallInst::Create(Int, Op, CI->getName(), CI);
8823 CI->replaceAllUsesWith(Op);
8824 CI->eraseFromParent();
8828 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
8829 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8830 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
8832 std::string AsmStr = IA->getAsmString();
8834 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
8835 std::vector<std::string> AsmPieces;
8836 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
8838 switch (AsmPieces.size()) {
8839 default: return false;
8841 AsmStr = AsmPieces[0];
8843 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
8846 if (AsmPieces.size() == 2 &&
8847 (AsmPieces[0] == "bswap" ||
8848 AsmPieces[0] == "bswapq" ||
8849 AsmPieces[0] == "bswapl") &&
8850 (AsmPieces[1] == "$0" ||
8851 AsmPieces[1] == "${0:q}")) {
8852 // No need to check constraints, nothing other than the equivalent of
8853 // "=r,0" would be valid here.
8854 return LowerToBSwap(CI);
8856 // rorw $$8, ${0:w} --> llvm.bswap.i16
8857 if (CI->getType() == Type::getInt16Ty(CI->getContext()) &&
8858 AsmPieces.size() == 3 &&
8859 AsmPieces[0] == "rorw" &&
8860 AsmPieces[1] == "$$8," &&
8861 AsmPieces[2] == "${0:w}" &&
8862 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
8863 return LowerToBSwap(CI);
8867 if (CI->getType() == Type::getInt64Ty(CI->getContext()) &&
8868 Constraints.size() >= 2 &&
8869 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
8870 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
8871 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
8872 std::vector<std::string> Words;
8873 SplitString(AsmPieces[0], Words, " \t");
8874 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
8876 SplitString(AsmPieces[1], Words, " \t");
8877 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
8879 SplitString(AsmPieces[2], Words, " \t,");
8880 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
8881 Words[2] == "%edx") {
8882 return LowerToBSwap(CI);
8894 /// getConstraintType - Given a constraint letter, return the type of
8895 /// constraint it is for this target.
8896 X86TargetLowering::ConstraintType
8897 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8898 if (Constraint.size() == 1) {
8899 switch (Constraint[0]) {
8911 return C_RegisterClass;
8919 return TargetLowering::getConstraintType(Constraint);
8922 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8923 /// with another that has more specific requirements based on the type of the
8924 /// corresponding operand.
8925 const char *X86TargetLowering::
8926 LowerXConstraint(EVT ConstraintVT) const {
8927 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8928 // 'f' like normal targets.
8929 if (ConstraintVT.isFloatingPoint()) {
8930 if (Subtarget->hasSSE2())
8932 if (Subtarget->hasSSE1())
8936 return TargetLowering::LowerXConstraint(ConstraintVT);
8939 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8940 /// vector. If it is invalid, don't add anything to Ops.
8941 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8944 std::vector<SDValue>&Ops,
8945 SelectionDAG &DAG) const {
8946 SDValue Result(0, 0);
8948 switch (Constraint) {
8951 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8952 if (C->getZExtValue() <= 31) {
8953 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8959 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8960 if (C->getZExtValue() <= 63) {
8961 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8967 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8968 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
8969 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8975 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8976 if (C->getZExtValue() <= 255) {
8977 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8983 // 32-bit signed value
8984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8985 const ConstantInt *CI = C->getConstantIntValue();
8986 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
8987 C->getSExtValue())) {
8988 // Widen to 64 bits here to get it sign extended.
8989 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8992 // FIXME gcc accepts some relocatable values here too, but only in certain
8993 // memory models; it's complicated.
8998 // 32-bit unsigned value
8999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9000 const ConstantInt *CI = C->getConstantIntValue();
9001 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9002 C->getZExtValue())) {
9003 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9007 // FIXME gcc accepts some relocatable values here too, but only in certain
9008 // memory models; it's complicated.
9012 // Literal immediates are always ok.
9013 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9014 // Widen to 64 bits here to get it sign extended.
9015 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9019 // If we are in non-pic codegen mode, we allow the address of a global (with
9020 // an optional displacement) to be used with 'i'.
9021 GlobalAddressSDNode *GA = 0;
9024 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9026 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9027 Offset += GA->getOffset();
9029 } else if (Op.getOpcode() == ISD::ADD) {
9030 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9031 Offset += C->getZExtValue();
9032 Op = Op.getOperand(0);
9035 } else if (Op.getOpcode() == ISD::SUB) {
9036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9037 Offset += -C->getZExtValue();
9038 Op = Op.getOperand(0);
9043 // Otherwise, this isn't something we can handle, reject it.
9047 GlobalValue *GV = GA->getGlobal();
9048 // If we require an extra load to get this address, as in PIC mode, we
9050 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9051 getTargetMachine())))
9055 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9057 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9063 if (Result.getNode()) {
9064 Ops.push_back(Result);
9067 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9071 std::vector<unsigned> X86TargetLowering::
9072 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9074 if (Constraint.size() == 1) {
9075 // FIXME: not handling fp-stack yet!
9076 switch (Constraint[0]) { // GCC X86 Constraint Letters
9077 default: break; // Unknown constraint letter
9078 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9079 if (Subtarget->is64Bit()) {
9081 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9082 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9083 X86::R10D,X86::R11D,X86::R12D,
9084 X86::R13D,X86::R14D,X86::R15D,
9085 X86::EBP, X86::ESP, 0);
9086 else if (VT == MVT::i16)
9087 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9088 X86::SI, X86::DI, X86::R8W,X86::R9W,
9089 X86::R10W,X86::R11W,X86::R12W,
9090 X86::R13W,X86::R14W,X86::R15W,
9091 X86::BP, X86::SP, 0);
9092 else if (VT == MVT::i8)
9093 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9094 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9095 X86::R10B,X86::R11B,X86::R12B,
9096 X86::R13B,X86::R14B,X86::R15B,
9097 X86::BPL, X86::SPL, 0);
9099 else if (VT == MVT::i64)
9100 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9101 X86::RSI, X86::RDI, X86::R8, X86::R9,
9102 X86::R10, X86::R11, X86::R12,
9103 X86::R13, X86::R14, X86::R15,
9104 X86::RBP, X86::RSP, 0);
9108 // 32-bit fallthrough
9111 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9112 else if (VT == MVT::i16)
9113 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9114 else if (VT == MVT::i8)
9115 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9116 else if (VT == MVT::i64)
9117 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9122 return std::vector<unsigned>();
9125 std::pair<unsigned, const TargetRegisterClass*>
9126 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9128 // First, see if this is a constraint that directly corresponds to an LLVM
9130 if (Constraint.size() == 1) {
9131 // GCC Constraint Letters
9132 switch (Constraint[0]) {
9134 case 'r': // GENERAL_REGS
9135 case 'R': // LEGACY_REGS
9136 case 'l': // INDEX_REGS
9138 return std::make_pair(0U, X86::GR8RegisterClass);
9140 return std::make_pair(0U, X86::GR16RegisterClass);
9141 if (VT == MVT::i32 || !Subtarget->is64Bit())
9142 return std::make_pair(0U, X86::GR32RegisterClass);
9143 return std::make_pair(0U, X86::GR64RegisterClass);
9144 case 'f': // FP Stack registers.
9145 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9146 // value to the correct fpstack register class.
9147 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9148 return std::make_pair(0U, X86::RFP32RegisterClass);
9149 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9150 return std::make_pair(0U, X86::RFP64RegisterClass);
9151 return std::make_pair(0U, X86::RFP80RegisterClass);
9152 case 'y': // MMX_REGS if MMX allowed.
9153 if (!Subtarget->hasMMX()) break;
9154 return std::make_pair(0U, X86::VR64RegisterClass);
9155 case 'Y': // SSE_REGS if SSE2 allowed
9156 if (!Subtarget->hasSSE2()) break;
9158 case 'x': // SSE_REGS if SSE1 allowed
9159 if (!Subtarget->hasSSE1()) break;
9161 switch (VT.getSimpleVT().SimpleTy) {
9163 // Scalar SSE types.
9166 return std::make_pair(0U, X86::FR32RegisterClass);
9169 return std::make_pair(0U, X86::FR64RegisterClass);
9177 return std::make_pair(0U, X86::VR128RegisterClass);
9183 // Use the default implementation in TargetLowering to convert the register
9184 // constraint into a member of a register class.
9185 std::pair<unsigned, const TargetRegisterClass*> Res;
9186 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9188 // Not found as a standard register?
9189 if (Res.second == 0) {
9190 // GCC calls "st(0)" just plain "st".
9191 if (StringsEqualNoCase("{st}", Constraint)) {
9192 Res.first = X86::ST0;
9193 Res.second = X86::RFP80RegisterClass;
9195 // 'A' means EAX + EDX.
9196 if (Constraint == "A") {
9197 Res.first = X86::EAX;
9198 Res.second = X86::GR32_ADRegisterClass;
9203 // Otherwise, check to see if this is a register class of the wrong value
9204 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9205 // turn into {ax},{dx}.
9206 if (Res.second->hasType(VT))
9207 return Res; // Correct type already, nothing to do.
9209 // All of the single-register GCC register classes map their values onto
9210 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9211 // really want an 8-bit or 32-bit register, map to the appropriate register
9212 // class and return the appropriate register.
9213 if (Res.second == X86::GR16RegisterClass) {
9214 if (VT == MVT::i8) {
9215 unsigned DestReg = 0;
9216 switch (Res.first) {
9218 case X86::AX: DestReg = X86::AL; break;
9219 case X86::DX: DestReg = X86::DL; break;
9220 case X86::CX: DestReg = X86::CL; break;
9221 case X86::BX: DestReg = X86::BL; break;
9224 Res.first = DestReg;
9225 Res.second = X86::GR8RegisterClass;
9227 } else if (VT == MVT::i32) {
9228 unsigned DestReg = 0;
9229 switch (Res.first) {
9231 case X86::AX: DestReg = X86::EAX; break;
9232 case X86::DX: DestReg = X86::EDX; break;
9233 case X86::CX: DestReg = X86::ECX; break;
9234 case X86::BX: DestReg = X86::EBX; break;
9235 case X86::SI: DestReg = X86::ESI; break;
9236 case X86::DI: DestReg = X86::EDI; break;
9237 case X86::BP: DestReg = X86::EBP; break;
9238 case X86::SP: DestReg = X86::ESP; break;
9241 Res.first = DestReg;
9242 Res.second = X86::GR32RegisterClass;
9244 } else if (VT == MVT::i64) {
9245 unsigned DestReg = 0;
9246 switch (Res.first) {
9248 case X86::AX: DestReg = X86::RAX; break;
9249 case X86::DX: DestReg = X86::RDX; break;
9250 case X86::CX: DestReg = X86::RCX; break;
9251 case X86::BX: DestReg = X86::RBX; break;
9252 case X86::SI: DestReg = X86::RSI; break;
9253 case X86::DI: DestReg = X86::RDI; break;
9254 case X86::BP: DestReg = X86::RBP; break;
9255 case X86::SP: DestReg = X86::RSP; break;
9258 Res.first = DestReg;
9259 Res.second = X86::GR64RegisterClass;
9262 } else if (Res.second == X86::FR32RegisterClass ||
9263 Res.second == X86::FR64RegisterClass ||
9264 Res.second == X86::VR128RegisterClass) {
9265 // Handle references to XMM physical registers that got mapped into the
9266 // wrong class. This can happen with constraints like {xmm0} where the
9267 // target independent register mapper will just pick the first match it can
9268 // find, ignoring the required type.
9270 Res.second = X86::FR32RegisterClass;
9271 else if (VT == MVT::f64)
9272 Res.second = X86::FR64RegisterClass;
9273 else if (X86::VR128RegisterClass->hasType(VT))
9274 Res.second = X86::VR128RegisterClass;
9280 //===----------------------------------------------------------------------===//
9281 // X86 Widen vector type
9282 //===----------------------------------------------------------------------===//
9284 /// getWidenVectorType: given a vector type, returns the type to widen
9285 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9286 /// If there is no vector type that we want to widen to, returns MVT::Other
9287 /// When and where to widen is target dependent based on the cost of
9288 /// scalarizing vs using the wider vector type.
9290 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
9291 assert(VT.isVector());
9292 if (isTypeLegal(VT))
9295 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9296 // type based on element type. This would speed up our search (though
9297 // it may not be worth it since the size of the list is relatively
9299 EVT EltVT = VT.getVectorElementType();
9300 unsigned NElts = VT.getVectorNumElements();
9302 // On X86, it make sense to widen any vector wider than 1
9306 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9307 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9308 EVT SVT = (MVT::SimpleValueType)nVT;
9310 if (isTypeLegal(SVT) &&
9311 SVT.getVectorElementType() == EltVT &&
9312 SVT.getVectorNumElements() > NElts)