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, MVT 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 MVT 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, VT, Custom);
727 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
728 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
731 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
732 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
734 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
735 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
738 if (Subtarget->is64Bit()) {
739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
740 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
743 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
744 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
745 MVT VT = (MVT::SimpleValueType)i;
747 // Do not attempt to promote non-128-bit vectors
748 if (!VT.is128BitVector()) {
751 setOperationAction(ISD::AND, VT, Promote);
752 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
753 setOperationAction(ISD::OR, VT, Promote);
754 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
755 setOperationAction(ISD::XOR, VT, Promote);
756 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
757 setOperationAction(ISD::LOAD, VT, Promote);
758 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
759 setOperationAction(ISD::SELECT, VT, Promote);
760 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
763 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
765 // Custom lower v2i64 and v2f64 selects.
766 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
767 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
768 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
769 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
771 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
772 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
773 if (!DisableMMX && Subtarget->hasMMX()) {
774 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
775 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
779 if (Subtarget->hasSSE41()) {
780 // FIXME: Do we need to handle scalar-to-vector here?
781 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
783 // i8 and i16 vectors are custom , because the source register and source
784 // source memory operand types are not the same width. f32 vectors are
785 // custom since the immediate controlling the insert encodes additional
787 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
788 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
789 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
790 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
792 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
793 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
794 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
797 if (Subtarget->is64Bit()) {
798 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
799 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
803 if (Subtarget->hasSSE42()) {
804 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
807 if (!UseSoftFloat && Subtarget->hasAVX()) {
808 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
809 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
810 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
811 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
813 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
814 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
815 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
816 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
817 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
818 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
819 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
820 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
821 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
822 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
823 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
824 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
825 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
826 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
827 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
829 // Operations to consider commented out -v16i16 v32i8
830 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
831 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
832 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
833 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
834 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
835 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
836 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
837 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
838 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
839 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
840 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
841 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
842 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
843 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
845 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
846 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
847 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
848 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
850 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
851 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
852 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
853 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
854 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
856 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
857 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
858 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
859 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
864 // Not sure we want to do this since there are no 256-bit integer
867 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
868 // This includes 256-bit vectors
869 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
870 MVT VT = (MVT::SimpleValueType)i;
872 // Do not attempt to custom lower non-power-of-2 vectors
873 if (!isPowerOf2_32(VT.getVectorNumElements()))
876 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
877 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
878 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
881 if (Subtarget->is64Bit()) {
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
888 // Not sure we want to do this since there are no 256-bit integer
891 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
892 // Including 256-bit vectors
893 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
894 MVT VT = (MVT::SimpleValueType)i;
896 if (!VT.is256BitVector()) {
899 setOperationAction(ISD::AND, VT, Promote);
900 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
901 setOperationAction(ISD::OR, VT, Promote);
902 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
903 setOperationAction(ISD::XOR, VT, Promote);
904 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
905 setOperationAction(ISD::LOAD, VT, Promote);
906 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
907 setOperationAction(ISD::SELECT, VT, Promote);
908 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
911 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
915 // We want to custom lower some of our intrinsics.
916 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
918 // Add/Sub/Mul with overflow operations are custom lowered.
919 setOperationAction(ISD::SADDO, MVT::i32, Custom);
920 setOperationAction(ISD::SADDO, MVT::i64, Custom);
921 setOperationAction(ISD::UADDO, MVT::i32, Custom);
922 setOperationAction(ISD::UADDO, MVT::i64, Custom);
923 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
924 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
925 setOperationAction(ISD::USUBO, MVT::i32, Custom);
926 setOperationAction(ISD::USUBO, MVT::i64, Custom);
927 setOperationAction(ISD::SMULO, MVT::i32, Custom);
928 setOperationAction(ISD::SMULO, MVT::i64, Custom);
930 if (!Subtarget->is64Bit()) {
931 // These libcalls are not available in 32-bit.
932 setLibcallName(RTLIB::SHL_I128, 0);
933 setLibcallName(RTLIB::SRL_I128, 0);
934 setLibcallName(RTLIB::SRA_I128, 0);
937 // We have target-specific dag combine patterns for the following nodes:
938 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
939 setTargetDAGCombine(ISD::BUILD_VECTOR);
940 setTargetDAGCombine(ISD::SELECT);
941 setTargetDAGCombine(ISD::SHL);
942 setTargetDAGCombine(ISD::SRA);
943 setTargetDAGCombine(ISD::SRL);
944 setTargetDAGCombine(ISD::STORE);
945 setTargetDAGCombine(ISD::MEMBARRIER);
946 if (Subtarget->is64Bit())
947 setTargetDAGCombine(ISD::MUL);
949 computeRegisterProperties();
951 // FIXME: These should be based on subtarget info. Plus, the values should
952 // be smaller when we are in optimizing for size mode.
953 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
954 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
955 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
956 allowUnalignedMemoryAccesses = true; // x86 supports it!
957 setPrefLoopAlignment(16);
958 benefitFromCodePlacementOpt = true;
962 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
967 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
968 /// the desired ByVal argument alignment.
969 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
972 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
973 if (VTy->getBitWidth() == 128)
975 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
976 unsigned EltAlign = 0;
977 getMaxByValAlign(ATy->getElementType(), EltAlign);
978 if (EltAlign > MaxAlign)
980 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
981 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
982 unsigned EltAlign = 0;
983 getMaxByValAlign(STy->getElementType(i), EltAlign);
984 if (EltAlign > MaxAlign)
993 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
994 /// function arguments in the caller parameter area. For X86, aggregates
995 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
996 /// are at 4-byte boundaries.
997 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
998 if (Subtarget->is64Bit()) {
999 // Max of 8 and alignment of type.
1000 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1007 if (Subtarget->hasSSE1())
1008 getMaxByValAlign(Ty, Align);
1012 /// getOptimalMemOpType - Returns the target specific optimal type for load
1013 /// and store operations as a result of memset, memcpy, and memmove
1014 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1017 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1018 bool isSrcConst, bool isSrcStr,
1019 SelectionDAG &DAG) const {
1020 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1021 // linux. This is because the stack realignment code can't handle certain
1022 // cases like PR2962. This should be removed when PR2962 is fixed.
1023 const Function *F = DAG.getMachineFunction().getFunction();
1024 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1025 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1026 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1028 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1031 if (Subtarget->is64Bit() && Size >= 8)
1036 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1038 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1039 SelectionDAG &DAG) const {
1040 if (usesGlobalOffsetTable())
1041 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1042 if (!Subtarget->is64Bit())
1043 // This doesn't have DebugLoc associated with it, but is not really the
1044 // same as a Register.
1045 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1050 /// getFunctionAlignment - Return the Log2 alignment of this function.
1051 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1052 return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 4;
1055 //===----------------------------------------------------------------------===//
1056 // Return Value Calling Convention Implementation
1057 //===----------------------------------------------------------------------===//
1059 #include "X86GenCallingConv.inc"
1062 X86TargetLowering::LowerReturn(SDValue Chain,
1063 unsigned CallConv, bool isVarArg,
1064 const SmallVectorImpl<ISD::OutputArg> &Outs,
1065 DebugLoc dl, SelectionDAG &DAG) {
1067 SmallVector<CCValAssign, 16> RVLocs;
1068 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1069 RVLocs, *DAG.getContext());
1070 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1072 // If this is the first return lowered for this function, add the regs to the
1073 // liveout set for the function.
1074 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1075 for (unsigned i = 0; i != RVLocs.size(); ++i)
1076 if (RVLocs[i].isRegLoc())
1077 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1082 SmallVector<SDValue, 6> RetOps;
1083 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1084 // Operand #1 = Bytes To Pop
1085 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1087 // Copy the result values into the output registers.
1088 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1089 CCValAssign &VA = RVLocs[i];
1090 assert(VA.isRegLoc() && "Can only return in registers!");
1091 SDValue ValToCopy = Outs[i].Val;
1093 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1094 // the RET instruction and handled by the FP Stackifier.
1095 if (VA.getLocReg() == X86::ST0 ||
1096 VA.getLocReg() == X86::ST1) {
1097 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1098 // change the value to the FP stack register class.
1099 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1100 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1101 RetOps.push_back(ValToCopy);
1102 // Don't emit a copytoreg.
1106 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1107 // which is returned in RAX / RDX.
1108 if (Subtarget->is64Bit()) {
1109 MVT ValVT = ValToCopy.getValueType();
1110 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1111 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1112 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1113 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1117 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1118 Flag = Chain.getValue(1);
1121 // The x86-64 ABI for returning structs by value requires that we copy
1122 // the sret argument into %rax for the return. We saved the argument into
1123 // a virtual register in the entry block, so now we copy the value out
1125 if (Subtarget->is64Bit() &&
1126 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1127 MachineFunction &MF = DAG.getMachineFunction();
1128 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1129 unsigned Reg = FuncInfo->getSRetReturnReg();
1131 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1132 FuncInfo->setSRetReturnReg(Reg);
1134 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1136 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1137 Flag = Chain.getValue(1);
1140 RetOps[0] = Chain; // Update chain.
1142 // Add the flag if we have it.
1144 RetOps.push_back(Flag);
1146 return DAG.getNode(X86ISD::RET_FLAG, dl,
1147 MVT::Other, &RetOps[0], RetOps.size());
1150 /// LowerCallResult - Lower the result values of a call into the
1151 /// appropriate copies out of appropriate physical registers.
1154 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1155 unsigned CallConv, bool isVarArg,
1156 const SmallVectorImpl<ISD::InputArg> &Ins,
1157 DebugLoc dl, SelectionDAG &DAG,
1158 SmallVectorImpl<SDValue> &InVals) {
1160 // Assign locations to each value returned by this call.
1161 SmallVector<CCValAssign, 16> RVLocs;
1162 bool Is64Bit = Subtarget->is64Bit();
1163 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1164 RVLocs, *DAG.getContext());
1165 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1167 // Copy all of the result registers out of their specified physreg.
1168 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1169 CCValAssign &VA = RVLocs[i];
1170 MVT CopyVT = VA.getValVT();
1172 // If this is x86-64, and we disabled SSE, we can't return FP values
1173 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1174 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1175 llvm_report_error("SSE register return with SSE disabled");
1178 // If this is a call to a function that returns an fp value on the floating
1179 // point stack, but where we prefer to use the value in xmm registers, copy
1180 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1181 if ((VA.getLocReg() == X86::ST0 ||
1182 VA.getLocReg() == X86::ST1) &&
1183 isScalarFPTypeInSSEReg(VA.getValVT())) {
1188 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1189 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1190 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1191 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1192 MVT::v2i64, InFlag).getValue(1);
1193 Val = Chain.getValue(0);
1194 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1195 Val, DAG.getConstant(0, MVT::i64));
1197 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1198 MVT::i64, InFlag).getValue(1);
1199 Val = Chain.getValue(0);
1201 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1203 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1204 CopyVT, InFlag).getValue(1);
1205 Val = Chain.getValue(0);
1207 InFlag = Chain.getValue(2);
1209 if (CopyVT != VA.getValVT()) {
1210 // Round the F80 the right size, which also moves to the appropriate xmm
1212 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1213 // This truncation won't change the value.
1214 DAG.getIntPtrConstant(1));
1217 InVals.push_back(Val);
1224 //===----------------------------------------------------------------------===//
1225 // C & StdCall & Fast Calling Convention implementation
1226 //===----------------------------------------------------------------------===//
1227 // StdCall calling convention seems to be standard for many Windows' API
1228 // routines and around. It differs from C calling convention just a little:
1229 // callee should clean up the stack, not caller. Symbols should be also
1230 // decorated in some fancy way :) It doesn't support any vector arguments.
1231 // For info on fast calling convention see Fast Calling Convention (tail call)
1232 // implementation LowerX86_32FastCCCallTo.
1234 /// CallIsStructReturn - Determines whether a call uses struct return
1236 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1240 return Outs[0].Flags.isSRet();
1243 /// ArgsAreStructReturn - Determines whether a function uses struct
1244 /// return semantics.
1246 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1250 return Ins[0].Flags.isSRet();
1253 /// IsCalleePop - Determines whether the callee is required to pop its
1254 /// own arguments. Callee pop is necessary to support tail calls.
1255 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1259 switch (CallingConv) {
1262 case CallingConv::X86_StdCall:
1263 return !Subtarget->is64Bit();
1264 case CallingConv::X86_FastCall:
1265 return !Subtarget->is64Bit();
1266 case CallingConv::Fast:
1267 return PerformTailCallOpt;
1271 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1272 /// given CallingConvention value.
1273 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1274 if (Subtarget->is64Bit()) {
1275 if (Subtarget->isTargetWin64())
1276 return CC_X86_Win64_C;
1281 if (CC == CallingConv::X86_FastCall)
1282 return CC_X86_32_FastCall;
1283 else if (CC == CallingConv::Fast)
1284 return CC_X86_32_FastCC;
1289 /// NameDecorationForCallConv - Selects the appropriate decoration to
1290 /// apply to a MachineFunction containing a given calling convention.
1292 X86TargetLowering::NameDecorationForCallConv(unsigned CallConv) {
1293 if (CallConv == CallingConv::X86_FastCall)
1295 else if (CallConv == CallingConv::X86_StdCall)
1301 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1302 /// by "Src" to address "Dst" with size and alignment information specified by
1303 /// the specific parameter attribute. The copy will be passed as a byval
1304 /// function parameter.
1306 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1307 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1309 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1310 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1311 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1315 X86TargetLowering::LowerMemArgument(SDValue Chain,
1317 const SmallVectorImpl<ISD::InputArg> &Ins,
1318 DebugLoc dl, SelectionDAG &DAG,
1319 const CCValAssign &VA,
1320 MachineFrameInfo *MFI,
1323 // Create the nodes corresponding to a load from this parameter slot.
1324 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1325 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1326 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1328 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1329 // changed with more analysis.
1330 // In case of tail call optimization mark all arguments mutable. Since they
1331 // could be overwritten by lowering of arguments in case of a tail call.
1332 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1333 VA.getLocMemOffset(), isImmutable);
1334 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1335 if (Flags.isByVal())
1337 return DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1338 PseudoSourceValue::getFixedStack(FI), 0);
1342 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1345 const SmallVectorImpl<ISD::InputArg> &Ins,
1348 SmallVectorImpl<SDValue> &InVals) {
1350 MachineFunction &MF = DAG.getMachineFunction();
1351 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1353 const Function* Fn = MF.getFunction();
1354 if (Fn->hasExternalLinkage() &&
1355 Subtarget->isTargetCygMing() &&
1356 Fn->getName() == "main")
1357 FuncInfo->setForceFramePointer(true);
1359 // Decorate the function name.
1360 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1362 MachineFrameInfo *MFI = MF.getFrameInfo();
1363 bool Is64Bit = Subtarget->is64Bit();
1364 bool IsWin64 = Subtarget->isTargetWin64();
1366 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1367 "Var args not supported with calling convention fastcc");
1369 // Assign locations to all of the incoming arguments.
1370 SmallVector<CCValAssign, 16> ArgLocs;
1371 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1372 ArgLocs, *DAG.getContext());
1373 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1375 unsigned LastVal = ~0U;
1377 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1378 CCValAssign &VA = ArgLocs[i];
1379 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1381 assert(VA.getValNo() != LastVal &&
1382 "Don't support value assigned to multiple locs yet");
1383 LastVal = VA.getValNo();
1385 if (VA.isRegLoc()) {
1386 MVT RegVT = VA.getLocVT();
1387 TargetRegisterClass *RC = NULL;
1388 if (RegVT == MVT::i32)
1389 RC = X86::GR32RegisterClass;
1390 else if (Is64Bit && RegVT == MVT::i64)
1391 RC = X86::GR64RegisterClass;
1392 else if (RegVT == MVT::f32)
1393 RC = X86::FR32RegisterClass;
1394 else if (RegVT == MVT::f64)
1395 RC = X86::FR64RegisterClass;
1396 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1397 RC = X86::VR128RegisterClass;
1398 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1399 RC = X86::VR64RegisterClass;
1401 llvm_unreachable("Unknown argument type!");
1403 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1404 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1406 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1407 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1409 if (VA.getLocInfo() == CCValAssign::SExt)
1410 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1411 DAG.getValueType(VA.getValVT()));
1412 else if (VA.getLocInfo() == CCValAssign::ZExt)
1413 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1414 DAG.getValueType(VA.getValVT()));
1415 else if (VA.getLocInfo() == CCValAssign::BCvt)
1416 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1418 if (VA.isExtInLoc()) {
1419 // Handle MMX values passed in XMM regs.
1420 if (RegVT.isVector()) {
1421 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1422 ArgValue, DAG.getConstant(0, MVT::i64));
1423 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1425 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1428 assert(VA.isMemLoc());
1429 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1432 // If value is passed via pointer - do a load.
1433 if (VA.getLocInfo() == CCValAssign::Indirect)
1434 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1436 InVals.push_back(ArgValue);
1439 // The x86-64 ABI for returning structs by value requires that we copy
1440 // the sret argument into %rax for the return. Save the argument into
1441 // a virtual register so that we can access it from the return points.
1442 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1443 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1444 unsigned Reg = FuncInfo->getSRetReturnReg();
1446 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1447 FuncInfo->setSRetReturnReg(Reg);
1449 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1450 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1453 unsigned StackSize = CCInfo.getNextStackOffset();
1454 // align stack specially for tail calls
1455 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1456 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1458 // If the function takes variable number of arguments, make a frame index for
1459 // the start of the first vararg value... for expansion of llvm.va_start.
1461 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1462 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1465 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1467 // FIXME: We should really autogenerate these arrays
1468 static const unsigned GPR64ArgRegsWin64[] = {
1469 X86::RCX, X86::RDX, X86::R8, X86::R9
1471 static const unsigned XMMArgRegsWin64[] = {
1472 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1474 static const unsigned GPR64ArgRegs64Bit[] = {
1475 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1477 static const unsigned XMMArgRegs64Bit[] = {
1478 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1479 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1481 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1484 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1485 GPR64ArgRegs = GPR64ArgRegsWin64;
1486 XMMArgRegs = XMMArgRegsWin64;
1488 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1489 GPR64ArgRegs = GPR64ArgRegs64Bit;
1490 XMMArgRegs = XMMArgRegs64Bit;
1492 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1494 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1497 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1498 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1499 "SSE register cannot be used when SSE is disabled!");
1500 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1501 "SSE register cannot be used when SSE is disabled!");
1502 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1503 // Kernel mode asks for SSE to be disabled, so don't push them
1505 TotalNumXMMRegs = 0;
1507 // For X86-64, if there are vararg parameters that are passed via
1508 // registers, then we must store them to their spots on the stack so they
1509 // may be loaded by deferencing the result of va_next.
1510 VarArgsGPOffset = NumIntRegs * 8;
1511 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1512 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1513 TotalNumXMMRegs * 16, 16);
1515 // Store the integer parameter registers.
1516 SmallVector<SDValue, 8> MemOps;
1517 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1518 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1519 DAG.getIntPtrConstant(VarArgsGPOffset));
1520 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1521 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1522 X86::GR64RegisterClass);
1523 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1525 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1526 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1527 MemOps.push_back(Store);
1528 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1529 DAG.getIntPtrConstant(8));
1532 // Now store the XMM (fp + vector) parameter registers.
1533 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1534 DAG.getIntPtrConstant(VarArgsFPOffset));
1535 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1536 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1537 X86::VR128RegisterClass);
1538 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1540 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1541 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1542 MemOps.push_back(Store);
1543 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1544 DAG.getIntPtrConstant(16));
1546 if (!MemOps.empty())
1547 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1548 &MemOps[0], MemOps.size());
1552 // Some CCs need callee pop.
1553 if (IsCalleePop(isVarArg, CallConv)) {
1554 BytesToPopOnReturn = StackSize; // Callee pops everything.
1555 BytesCallerReserves = 0;
1557 BytesToPopOnReturn = 0; // Callee pops nothing.
1558 // If this is an sret function, the return should pop the hidden pointer.
1559 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1560 BytesToPopOnReturn = 4;
1561 BytesCallerReserves = StackSize;
1565 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1566 if (CallConv == CallingConv::X86_FastCall)
1567 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1570 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1576 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1577 SDValue StackPtr, SDValue Arg,
1578 DebugLoc dl, SelectionDAG &DAG,
1579 const CCValAssign &VA,
1580 ISD::ArgFlagsTy Flags) {
1581 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1582 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1583 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1584 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1585 if (Flags.isByVal()) {
1586 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1588 return DAG.getStore(Chain, dl, Arg, PtrOff,
1589 PseudoSourceValue::getStack(), LocMemOffset);
1592 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1593 /// optimization is performed and it is required.
1595 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1596 SDValue &OutRetAddr,
1602 if (!IsTailCall || FPDiff==0) return Chain;
1604 // Adjust the Return address stack slot.
1605 MVT VT = getPointerTy();
1606 OutRetAddr = getReturnAddressFrameIndex(DAG);
1608 // Load the "old" Return address.
1609 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1610 return SDValue(OutRetAddr.getNode(), 1);
1613 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1614 /// optimization is performed and it is required (FPDiff!=0).
1616 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1617 SDValue Chain, SDValue RetAddrFrIdx,
1618 bool Is64Bit, int FPDiff, DebugLoc dl) {
1619 // Store the return address to the appropriate stack slot.
1620 if (!FPDiff) return Chain;
1621 // Calculate the new stack slot for the return address.
1622 int SlotSize = Is64Bit ? 8 : 4;
1623 int NewReturnAddrFI =
1624 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1625 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1626 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1627 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1628 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1633 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1634 unsigned CallConv, bool isVarArg, bool isTailCall,
1635 const SmallVectorImpl<ISD::OutputArg> &Outs,
1636 const SmallVectorImpl<ISD::InputArg> &Ins,
1637 DebugLoc dl, SelectionDAG &DAG,
1638 SmallVectorImpl<SDValue> &InVals) {
1640 MachineFunction &MF = DAG.getMachineFunction();
1641 bool Is64Bit = Subtarget->is64Bit();
1642 bool IsStructRet = CallIsStructReturn(Outs);
1644 assert((!isTailCall ||
1645 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1646 "IsEligibleForTailCallOptimization missed a case!");
1647 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1648 "Var args not supported with calling convention fastcc");
1650 // Analyze operands of the call, assigning locations to each operand.
1651 SmallVector<CCValAssign, 16> ArgLocs;
1652 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1653 ArgLocs, *DAG.getContext());
1654 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1656 // Get a count of how many bytes are to be pushed on the stack.
1657 unsigned NumBytes = CCInfo.getNextStackOffset();
1658 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1659 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1663 // Lower arguments at fp - stackoffset + fpdiff.
1664 unsigned NumBytesCallerPushed =
1665 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1666 FPDiff = NumBytesCallerPushed - NumBytes;
1668 // Set the delta of movement of the returnaddr stackslot.
1669 // But only set if delta is greater than previous delta.
1670 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1671 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1674 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1676 SDValue RetAddrFrIdx;
1677 // Load return adress for tail calls.
1678 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1681 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1682 SmallVector<SDValue, 8> MemOpChains;
1685 // Walk the register/memloc assignments, inserting copies/loads. In the case
1686 // of tail call optimization arguments are handle later.
1687 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1688 CCValAssign &VA = ArgLocs[i];
1689 MVT RegVT = VA.getLocVT();
1690 SDValue Arg = Outs[i].Val;
1691 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1692 bool isByVal = Flags.isByVal();
1694 // Promote the value if needed.
1695 switch (VA.getLocInfo()) {
1696 default: llvm_unreachable("Unknown loc info!");
1697 case CCValAssign::Full: break;
1698 case CCValAssign::SExt:
1699 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1701 case CCValAssign::ZExt:
1702 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1704 case CCValAssign::AExt:
1705 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1706 // Special case: passing MMX values in XMM registers.
1707 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1708 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1709 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1711 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1713 case CCValAssign::BCvt:
1714 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1716 case CCValAssign::Indirect: {
1717 // Store the argument.
1718 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1719 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1720 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1721 PseudoSourceValue::getFixedStack(FI), 0);
1727 if (VA.isRegLoc()) {
1728 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1730 if (!isTailCall || (isTailCall && isByVal)) {
1731 assert(VA.isMemLoc());
1732 if (StackPtr.getNode() == 0)
1733 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1735 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1736 dl, DAG, VA, Flags));
1741 if (!MemOpChains.empty())
1742 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1743 &MemOpChains[0], MemOpChains.size());
1745 // Build a sequence of copy-to-reg nodes chained together with token chain
1746 // and flag operands which copy the outgoing args into registers.
1748 // Tail call byval lowering might overwrite argument registers so in case of
1749 // tail call optimization the copies to registers are lowered later.
1751 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1752 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1753 RegsToPass[i].second, InFlag);
1754 InFlag = Chain.getValue(1);
1758 if (Subtarget->isPICStyleGOT()) {
1759 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1762 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1763 DAG.getNode(X86ISD::GlobalBaseReg,
1764 DebugLoc::getUnknownLoc(),
1767 InFlag = Chain.getValue(1);
1769 // If we are tail calling and generating PIC/GOT style code load the
1770 // address of the callee into ECX. The value in ecx is used as target of
1771 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1772 // for tail calls on PIC/GOT architectures. Normally we would just put the
1773 // address of GOT into ebx and then call target@PLT. But for tail calls
1774 // ebx would be restored (since ebx is callee saved) before jumping to the
1777 // Note: The actual moving to ECX is done further down.
1778 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1779 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1780 !G->getGlobal()->hasProtectedVisibility())
1781 Callee = LowerGlobalAddress(Callee, DAG);
1782 else if (isa<ExternalSymbolSDNode>(Callee))
1783 Callee = LowerExternalSymbol(Callee, DAG);
1787 if (Is64Bit && isVarArg) {
1788 // From AMD64 ABI document:
1789 // For calls that may call functions that use varargs or stdargs
1790 // (prototype-less calls or calls to functions containing ellipsis (...) in
1791 // the declaration) %al is used as hidden argument to specify the number
1792 // of SSE registers used. The contents of %al do not need to match exactly
1793 // the number of registers, but must be an ubound on the number of SSE
1794 // registers used and is in the range 0 - 8 inclusive.
1796 // FIXME: Verify this on Win64
1797 // Count the number of XMM registers allocated.
1798 static const unsigned XMMArgRegs[] = {
1799 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1800 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1802 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1803 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1804 && "SSE registers cannot be used when SSE is disabled");
1806 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1807 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1808 InFlag = Chain.getValue(1);
1812 // For tail calls lower the arguments to the 'real' stack slot.
1814 // Force all the incoming stack arguments to be loaded from the stack
1815 // before any new outgoing arguments are stored to the stack, because the
1816 // outgoing stack slots may alias the incoming argument stack slots, and
1817 // the alias isn't otherwise explicit. This is slightly more conservative
1818 // than necessary, because it means that each store effectively depends
1819 // on every argument instead of just those arguments it would clobber.
1820 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1822 SmallVector<SDValue, 8> MemOpChains2;
1825 // Do not flag preceeding copytoreg stuff together with the following stuff.
1827 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1828 CCValAssign &VA = ArgLocs[i];
1829 if (!VA.isRegLoc()) {
1830 assert(VA.isMemLoc());
1831 SDValue Arg = Outs[i].Val;
1832 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1833 // Create frame index.
1834 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1835 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1836 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1837 FIN = DAG.getFrameIndex(FI, getPointerTy());
1839 if (Flags.isByVal()) {
1840 // Copy relative to framepointer.
1841 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1842 if (StackPtr.getNode() == 0)
1843 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1845 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1847 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1851 // Store relative to framepointer.
1852 MemOpChains2.push_back(
1853 DAG.getStore(ArgChain, dl, Arg, FIN,
1854 PseudoSourceValue::getFixedStack(FI), 0));
1859 if (!MemOpChains2.empty())
1860 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1861 &MemOpChains2[0], MemOpChains2.size());
1863 // Copy arguments to their registers.
1864 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1865 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1866 RegsToPass[i].second, InFlag);
1867 InFlag = Chain.getValue(1);
1871 // Store the return address to the appropriate stack slot.
1872 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1876 // If the callee is a GlobalAddress node (quite common, every direct call is)
1877 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1878 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1879 // We should use extra load for direct calls to dllimported functions in
1881 GlobalValue *GV = G->getGlobal();
1882 if (!GV->hasDLLImportLinkage()) {
1883 unsigned char OpFlags = 0;
1885 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1886 // external symbols most go through the PLT in PIC mode. If the symbol
1887 // has hidden or protected visibility, or if it is static or local, then
1888 // we don't need to use the PLT - we can directly call it.
1889 if (Subtarget->isTargetELF() &&
1890 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1891 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1892 OpFlags = X86II::MO_PLT;
1893 } else if (Subtarget->isPICStyleStubAny() &&
1894 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1895 Subtarget->getDarwinVers() < 9) {
1896 // PC-relative references to external symbols should go through $stub,
1897 // unless we're building with the leopard linker or later, which
1898 // automatically synthesizes these stubs.
1899 OpFlags = X86II::MO_DARWIN_STUB;
1902 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1903 G->getOffset(), OpFlags);
1905 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1906 unsigned char OpFlags = 0;
1908 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1909 // symbols should go through the PLT.
1910 if (Subtarget->isTargetELF() &&
1911 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1912 OpFlags = X86II::MO_PLT;
1913 } else if (Subtarget->isPICStyleStubAny() &&
1914 Subtarget->getDarwinVers() < 9) {
1915 // PC-relative references to external symbols should go through $stub,
1916 // unless we're building with the leopard linker or later, which
1917 // automatically synthesizes these stubs.
1918 OpFlags = X86II::MO_DARWIN_STUB;
1921 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
1923 } else if (isTailCall) {
1924 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1926 Chain = DAG.getCopyToReg(Chain, dl,
1927 DAG.getRegister(Opc, getPointerTy()),
1929 Callee = DAG.getRegister(Opc, getPointerTy());
1930 // Add register as live out.
1931 MF.getRegInfo().addLiveOut(Opc);
1934 // Returns a chain & a flag for retval copy to use.
1935 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1936 SmallVector<SDValue, 8> Ops;
1939 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1940 DAG.getIntPtrConstant(0, true), InFlag);
1941 InFlag = Chain.getValue(1);
1944 Ops.push_back(Chain);
1945 Ops.push_back(Callee);
1948 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1950 // Add argument registers to the end of the list so that they are known live
1952 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1953 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1954 RegsToPass[i].second.getValueType()));
1956 // Add an implicit use GOT pointer in EBX.
1957 if (!isTailCall && Subtarget->isPICStyleGOT())
1958 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1960 // Add an implicit use of AL for x86 vararg functions.
1961 if (Is64Bit && isVarArg)
1962 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1964 if (InFlag.getNode())
1965 Ops.push_back(InFlag);
1968 // If this is the first return lowered for this function, add the regs
1969 // to the liveout set for the function.
1970 if (MF.getRegInfo().liveout_empty()) {
1971 SmallVector<CCValAssign, 16> RVLocs;
1972 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1974 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1975 for (unsigned i = 0; i != RVLocs.size(); ++i)
1976 if (RVLocs[i].isRegLoc())
1977 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1980 assert(((Callee.getOpcode() == ISD::Register &&
1981 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
1982 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
1983 Callee.getOpcode() == ISD::TargetExternalSymbol ||
1984 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
1985 "Expecting an global address, external symbol, or register");
1987 return DAG.getNode(X86ISD::TC_RETURN, dl,
1988 NodeTys, &Ops[0], Ops.size());
1991 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1992 InFlag = Chain.getValue(1);
1994 // Create the CALLSEQ_END node.
1995 unsigned NumBytesForCalleeToPush;
1996 if (IsCalleePop(isVarArg, CallConv))
1997 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1998 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
1999 // If this is is a call to a struct-return function, the callee
2000 // pops the hidden struct pointer, so we have to push it back.
2001 // This is common for Darwin/X86, Linux & Mingw32 targets.
2002 NumBytesForCalleeToPush = 4;
2004 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2006 // Returns a flag for retval copy to use.
2007 Chain = DAG.getCALLSEQ_END(Chain,
2008 DAG.getIntPtrConstant(NumBytes, true),
2009 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2012 InFlag = Chain.getValue(1);
2014 // Handle result values, copying them out of physregs into vregs that we
2016 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2017 Ins, dl, DAG, InVals);
2021 //===----------------------------------------------------------------------===//
2022 // Fast Calling Convention (tail call) implementation
2023 //===----------------------------------------------------------------------===//
2025 // Like std call, callee cleans arguments, convention except that ECX is
2026 // reserved for storing the tail called function address. Only 2 registers are
2027 // free for argument passing (inreg). Tail call optimization is performed
2029 // * tailcallopt is enabled
2030 // * caller/callee are fastcc
2031 // On X86_64 architecture with GOT-style position independent code only local
2032 // (within module) calls are supported at the moment.
2033 // To keep the stack aligned according to platform abi the function
2034 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2035 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2036 // If a tail called function callee has more arguments than the caller the
2037 // caller needs to make sure that there is room to move the RETADDR to. This is
2038 // achieved by reserving an area the size of the argument delta right after the
2039 // original REtADDR, but before the saved framepointer or the spilled registers
2040 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2052 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2053 /// for a 16 byte align requirement.
2054 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2055 SelectionDAG& DAG) {
2056 MachineFunction &MF = DAG.getMachineFunction();
2057 const TargetMachine &TM = MF.getTarget();
2058 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2059 unsigned StackAlignment = TFI.getStackAlignment();
2060 uint64_t AlignMask = StackAlignment - 1;
2061 int64_t Offset = StackSize;
2062 uint64_t SlotSize = TD->getPointerSize();
2063 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2064 // Number smaller than 12 so just add the difference.
2065 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2067 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2068 Offset = ((~AlignMask) & Offset) + StackAlignment +
2069 (StackAlignment-SlotSize);
2074 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2075 /// for tail call optimization. Targets which want to do tail call
2076 /// optimization should implement this function.
2078 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2081 const SmallVectorImpl<ISD::InputArg> &Ins,
2082 SelectionDAG& DAG) const {
2083 MachineFunction &MF = DAG.getMachineFunction();
2084 unsigned CallerCC = MF.getFunction()->getCallingConv();
2085 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2089 X86TargetLowering::createFastISel(MachineFunction &mf,
2090 MachineModuleInfo *mmo,
2092 DenseMap<const Value *, unsigned> &vm,
2093 DenseMap<const BasicBlock *,
2094 MachineBasicBlock *> &bm,
2095 DenseMap<const AllocaInst *, int> &am
2097 , SmallSet<Instruction*, 8> &cil
2100 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2108 //===----------------------------------------------------------------------===//
2109 // Other Lowering Hooks
2110 //===----------------------------------------------------------------------===//
2113 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2114 MachineFunction &MF = DAG.getMachineFunction();
2115 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2116 int ReturnAddrIndex = FuncInfo->getRAIndex();
2118 if (ReturnAddrIndex == 0) {
2119 // Set up a frame object for the return address.
2120 uint64_t SlotSize = TD->getPointerSize();
2121 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2122 FuncInfo->setRAIndex(ReturnAddrIndex);
2125 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2129 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2130 /// specific condition code, returning the condition code and the LHS/RHS of the
2131 /// comparison to make.
2132 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2133 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2135 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2136 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2137 // X > -1 -> X == 0, jump !sign.
2138 RHS = DAG.getConstant(0, RHS.getValueType());
2139 return X86::COND_NS;
2140 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2141 // X < 0 -> X == 0, jump on sign.
2143 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2145 RHS = DAG.getConstant(0, RHS.getValueType());
2146 return X86::COND_LE;
2150 switch (SetCCOpcode) {
2151 default: llvm_unreachable("Invalid integer condition!");
2152 case ISD::SETEQ: return X86::COND_E;
2153 case ISD::SETGT: return X86::COND_G;
2154 case ISD::SETGE: return X86::COND_GE;
2155 case ISD::SETLT: return X86::COND_L;
2156 case ISD::SETLE: return X86::COND_LE;
2157 case ISD::SETNE: return X86::COND_NE;
2158 case ISD::SETULT: return X86::COND_B;
2159 case ISD::SETUGT: return X86::COND_A;
2160 case ISD::SETULE: return X86::COND_BE;
2161 case ISD::SETUGE: return X86::COND_AE;
2165 // First determine if it is required or is profitable to flip the operands.
2167 // If LHS is a foldable load, but RHS is not, flip the condition.
2168 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2169 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2170 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2171 std::swap(LHS, RHS);
2174 switch (SetCCOpcode) {
2180 std::swap(LHS, RHS);
2184 // On a floating point condition, the flags are set as follows:
2186 // 0 | 0 | 0 | X > Y
2187 // 0 | 0 | 1 | X < Y
2188 // 1 | 0 | 0 | X == Y
2189 // 1 | 1 | 1 | unordered
2190 switch (SetCCOpcode) {
2191 default: llvm_unreachable("Condcode should be pre-legalized away");
2193 case ISD::SETEQ: return X86::COND_E;
2194 case ISD::SETOLT: // flipped
2196 case ISD::SETGT: return X86::COND_A;
2197 case ISD::SETOLE: // flipped
2199 case ISD::SETGE: return X86::COND_AE;
2200 case ISD::SETUGT: // flipped
2202 case ISD::SETLT: return X86::COND_B;
2203 case ISD::SETUGE: // flipped
2205 case ISD::SETLE: return X86::COND_BE;
2207 case ISD::SETNE: return X86::COND_NE;
2208 case ISD::SETUO: return X86::COND_P;
2209 case ISD::SETO: return X86::COND_NP;
2213 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2214 /// code. Current x86 isa includes the following FP cmov instructions:
2215 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2216 static bool hasFPCMov(unsigned X86CC) {
2232 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2233 /// the specified range (L, H].
2234 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2235 return (Val < 0) || (Val >= Low && Val < Hi);
2238 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2239 /// specified value.
2240 static bool isUndefOrEqual(int Val, int CmpVal) {
2241 if (Val < 0 || Val == CmpVal)
2246 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2247 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2248 /// the second operand.
2249 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2250 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2251 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2252 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2253 return (Mask[0] < 2 && Mask[1] < 2);
2257 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2258 SmallVector<int, 8> M;
2260 return ::isPSHUFDMask(M, N->getValueType(0));
2263 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2264 /// is suitable for input to PSHUFHW.
2265 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2266 if (VT != MVT::v8i16)
2269 // Lower quadword copied in order or undef.
2270 for (int i = 0; i != 4; ++i)
2271 if (Mask[i] >= 0 && Mask[i] != i)
2274 // Upper quadword shuffled.
2275 for (int i = 4; i != 8; ++i)
2276 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2282 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2283 SmallVector<int, 8> M;
2285 return ::isPSHUFHWMask(M, N->getValueType(0));
2288 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2289 /// is suitable for input to PSHUFLW.
2290 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2291 if (VT != MVT::v8i16)
2294 // Upper quadword copied in order.
2295 for (int i = 4; i != 8; ++i)
2296 if (Mask[i] >= 0 && Mask[i] != i)
2299 // Lower quadword shuffled.
2300 for (int i = 0; i != 4; ++i)
2307 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2308 SmallVector<int, 8> M;
2310 return ::isPSHUFLWMask(M, N->getValueType(0));
2313 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2314 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2315 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2316 int NumElems = VT.getVectorNumElements();
2317 if (NumElems != 2 && NumElems != 4)
2320 int Half = NumElems / 2;
2321 for (int i = 0; i < Half; ++i)
2322 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2324 for (int i = Half; i < NumElems; ++i)
2325 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2331 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2332 SmallVector<int, 8> M;
2334 return ::isSHUFPMask(M, N->getValueType(0));
2337 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2338 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2339 /// half elements to come from vector 1 (which would equal the dest.) and
2340 /// the upper half to come from vector 2.
2341 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2342 int NumElems = VT.getVectorNumElements();
2344 if (NumElems != 2 && NumElems != 4)
2347 int Half = NumElems / 2;
2348 for (int i = 0; i < Half; ++i)
2349 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2351 for (int i = Half; i < NumElems; ++i)
2352 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2357 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2358 SmallVector<int, 8> M;
2360 return isCommutedSHUFPMask(M, N->getValueType(0));
2363 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2364 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2365 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2366 if (N->getValueType(0).getVectorNumElements() != 4)
2369 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2370 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2371 isUndefOrEqual(N->getMaskElt(1), 7) &&
2372 isUndefOrEqual(N->getMaskElt(2), 2) &&
2373 isUndefOrEqual(N->getMaskElt(3), 3);
2376 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2377 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2378 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2379 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2381 if (NumElems != 2 && NumElems != 4)
2384 for (unsigned i = 0; i < NumElems/2; ++i)
2385 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2388 for (unsigned i = NumElems/2; i < NumElems; ++i)
2389 if (!isUndefOrEqual(N->getMaskElt(i), i))
2395 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2396 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2398 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2399 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2401 if (NumElems != 2 && NumElems != 4)
2404 for (unsigned i = 0; i < NumElems/2; ++i)
2405 if (!isUndefOrEqual(N->getMaskElt(i), i))
2408 for (unsigned i = 0; i < NumElems/2; ++i)
2409 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2415 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2416 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2418 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2419 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2424 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2425 isUndefOrEqual(N->getMaskElt(1), 3) &&
2426 isUndefOrEqual(N->getMaskElt(2), 2) &&
2427 isUndefOrEqual(N->getMaskElt(3), 3);
2430 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2431 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2432 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2433 bool V2IsSplat = false) {
2434 int NumElts = VT.getVectorNumElements();
2435 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2438 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2440 int BitI1 = Mask[i+1];
2441 if (!isUndefOrEqual(BitI, j))
2444 if (!isUndefOrEqual(BitI1, NumElts))
2447 if (!isUndefOrEqual(BitI1, j + NumElts))
2454 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2455 SmallVector<int, 8> M;
2457 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2460 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2461 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2462 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2463 bool V2IsSplat = false) {
2464 int NumElts = VT.getVectorNumElements();
2465 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2468 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2470 int BitI1 = Mask[i+1];
2471 if (!isUndefOrEqual(BitI, j + NumElts/2))
2474 if (isUndefOrEqual(BitI1, NumElts))
2477 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2484 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2485 SmallVector<int, 8> M;
2487 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2490 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2491 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2493 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2494 int NumElems = VT.getVectorNumElements();
2495 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2498 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2500 int BitI1 = Mask[i+1];
2501 if (!isUndefOrEqual(BitI, j))
2503 if (!isUndefOrEqual(BitI1, j))
2509 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2510 SmallVector<int, 8> M;
2512 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2515 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2516 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2518 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2519 int NumElems = VT.getVectorNumElements();
2520 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2523 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2525 int BitI1 = Mask[i+1];
2526 if (!isUndefOrEqual(BitI, j))
2528 if (!isUndefOrEqual(BitI1, j))
2534 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2535 SmallVector<int, 8> M;
2537 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2540 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2541 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2542 /// MOVSD, and MOVD, i.e. setting the lowest element.
2543 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2544 if (VT.getVectorElementType().getSizeInBits() < 32)
2547 int NumElts = VT.getVectorNumElements();
2549 if (!isUndefOrEqual(Mask[0], NumElts))
2552 for (int i = 1; i < NumElts; ++i)
2553 if (!isUndefOrEqual(Mask[i], i))
2559 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2560 SmallVector<int, 8> M;
2562 return ::isMOVLMask(M, N->getValueType(0));
2565 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2566 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2567 /// element of vector 2 and the other elements to come from vector 1 in order.
2568 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2569 bool V2IsSplat = false, bool V2IsUndef = false) {
2570 int NumOps = VT.getVectorNumElements();
2571 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2574 if (!isUndefOrEqual(Mask[0], 0))
2577 for (int i = 1; i < NumOps; ++i)
2578 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2579 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2580 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2586 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2587 bool V2IsUndef = false) {
2588 SmallVector<int, 8> M;
2590 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2593 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2594 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2595 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2596 if (N->getValueType(0).getVectorNumElements() != 4)
2599 // Expect 1, 1, 3, 3
2600 for (unsigned i = 0; i < 2; ++i) {
2601 int Elt = N->getMaskElt(i);
2602 if (Elt >= 0 && Elt != 1)
2607 for (unsigned i = 2; i < 4; ++i) {
2608 int Elt = N->getMaskElt(i);
2609 if (Elt >= 0 && Elt != 3)
2614 // Don't use movshdup if it can be done with a shufps.
2615 // FIXME: verify that matching u, u, 3, 3 is what we want.
2619 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2620 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2621 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2622 if (N->getValueType(0).getVectorNumElements() != 4)
2625 // Expect 0, 0, 2, 2
2626 for (unsigned i = 0; i < 2; ++i)
2627 if (N->getMaskElt(i) > 0)
2631 for (unsigned i = 2; i < 4; ++i) {
2632 int Elt = N->getMaskElt(i);
2633 if (Elt >= 0 && Elt != 2)
2638 // Don't use movsldup if it can be done with a shufps.
2642 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2643 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2644 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2645 int e = N->getValueType(0).getVectorNumElements() / 2;
2647 for (int i = 0; i < e; ++i)
2648 if (!isUndefOrEqual(N->getMaskElt(i), i))
2650 for (int i = 0; i < e; ++i)
2651 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2656 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2657 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2659 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2660 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2661 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2663 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2665 for (int i = 0; i < NumOperands; ++i) {
2666 int Val = SVOp->getMaskElt(NumOperands-i-1);
2667 if (Val < 0) Val = 0;
2668 if (Val >= NumOperands) Val -= NumOperands;
2670 if (i != NumOperands - 1)
2676 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2677 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2679 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2682 // 8 nodes, but we only care about the last 4.
2683 for (unsigned i = 7; i >= 4; --i) {
2684 int Val = SVOp->getMaskElt(i);
2693 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2694 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2696 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2697 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2699 // 8 nodes, but we only care about the first 4.
2700 for (int i = 3; i >= 0; --i) {
2701 int Val = SVOp->getMaskElt(i);
2710 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2712 bool X86::isZeroNode(SDValue Elt) {
2713 return ((isa<ConstantSDNode>(Elt) &&
2714 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2715 (isa<ConstantFPSDNode>(Elt) &&
2716 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2719 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2720 /// their permute mask.
2721 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2722 SelectionDAG &DAG) {
2723 MVT VT = SVOp->getValueType(0);
2724 unsigned NumElems = VT.getVectorNumElements();
2725 SmallVector<int, 8> MaskVec;
2727 for (unsigned i = 0; i != NumElems; ++i) {
2728 int idx = SVOp->getMaskElt(i);
2730 MaskVec.push_back(idx);
2731 else if (idx < (int)NumElems)
2732 MaskVec.push_back(idx + NumElems);
2734 MaskVec.push_back(idx - NumElems);
2736 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2737 SVOp->getOperand(0), &MaskVec[0]);
2740 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2741 /// the two vector operands have swapped position.
2742 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2743 unsigned NumElems = VT.getVectorNumElements();
2744 for (unsigned i = 0; i != NumElems; ++i) {
2748 else if (idx < (int)NumElems)
2749 Mask[i] = idx + NumElems;
2751 Mask[i] = idx - NumElems;
2755 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2756 /// match movhlps. The lower half elements should come from upper half of
2757 /// V1 (and in order), and the upper half elements should come from the upper
2758 /// half of V2 (and in order).
2759 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2760 if (Op->getValueType(0).getVectorNumElements() != 4)
2762 for (unsigned i = 0, e = 2; i != e; ++i)
2763 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2765 for (unsigned i = 2; i != 4; ++i)
2766 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2771 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2772 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2774 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2775 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2777 N = N->getOperand(0).getNode();
2778 if (!ISD::isNON_EXTLoad(N))
2781 *LD = cast<LoadSDNode>(N);
2785 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2786 /// match movlp{s|d}. The lower half elements should come from lower half of
2787 /// V1 (and in order), and the upper half elements should come from the upper
2788 /// half of V2 (and in order). And since V1 will become the source of the
2789 /// MOVLP, it must be either a vector load or a scalar load to vector.
2790 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2791 ShuffleVectorSDNode *Op) {
2792 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2794 // Is V2 is a vector load, don't do this transformation. We will try to use
2795 // load folding shufps op.
2796 if (ISD::isNON_EXTLoad(V2))
2799 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2801 if (NumElems != 2 && NumElems != 4)
2803 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2804 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2806 for (unsigned i = NumElems/2; i != NumElems; ++i)
2807 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2812 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2814 static bool isSplatVector(SDNode *N) {
2815 if (N->getOpcode() != ISD::BUILD_VECTOR)
2818 SDValue SplatValue = N->getOperand(0);
2819 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2820 if (N->getOperand(i) != SplatValue)
2825 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2826 /// to an zero vector.
2827 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2828 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2829 SDValue V1 = N->getOperand(0);
2830 SDValue V2 = N->getOperand(1);
2831 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2832 for (unsigned i = 0; i != NumElems; ++i) {
2833 int Idx = N->getMaskElt(i);
2834 if (Idx >= (int)NumElems) {
2835 unsigned Opc = V2.getOpcode();
2836 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2838 if (Opc != ISD::BUILD_VECTOR ||
2839 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
2841 } else if (Idx >= 0) {
2842 unsigned Opc = V1.getOpcode();
2843 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2845 if (Opc != ISD::BUILD_VECTOR ||
2846 !X86::isZeroNode(V1.getOperand(Idx)))
2853 /// getZeroVector - Returns a vector of specified type with all zero elements.
2855 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2857 assert(VT.isVector() && "Expected a vector type");
2859 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2860 // type. This ensures they get CSE'd.
2862 if (VT.getSizeInBits() == 64) { // MMX
2863 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2864 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2865 } else if (HasSSE2) { // SSE2
2866 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2867 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2869 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2870 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2872 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2875 /// getOnesVector - Returns a vector of specified type with all bits set.
2877 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2878 assert(VT.isVector() && "Expected a vector type");
2880 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2881 // type. This ensures they get CSE'd.
2882 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2884 if (VT.getSizeInBits() == 64) // MMX
2885 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2887 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2888 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2892 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2893 /// that point to V2 points to its first element.
2894 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2895 MVT VT = SVOp->getValueType(0);
2896 unsigned NumElems = VT.getVectorNumElements();
2898 bool Changed = false;
2899 SmallVector<int, 8> MaskVec;
2900 SVOp->getMask(MaskVec);
2902 for (unsigned i = 0; i != NumElems; ++i) {
2903 if (MaskVec[i] > (int)NumElems) {
2904 MaskVec[i] = NumElems;
2909 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2910 SVOp->getOperand(1), &MaskVec[0]);
2911 return SDValue(SVOp, 0);
2914 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2915 /// operation of specified width.
2916 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2918 unsigned NumElems = VT.getVectorNumElements();
2919 SmallVector<int, 8> Mask;
2920 Mask.push_back(NumElems);
2921 for (unsigned i = 1; i != NumElems; ++i)
2923 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2926 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2927 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2929 unsigned NumElems = VT.getVectorNumElements();
2930 SmallVector<int, 8> Mask;
2931 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2933 Mask.push_back(i + NumElems);
2935 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2938 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2939 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2941 unsigned NumElems = VT.getVectorNumElements();
2942 unsigned Half = NumElems/2;
2943 SmallVector<int, 8> Mask;
2944 for (unsigned i = 0; i != Half; ++i) {
2945 Mask.push_back(i + Half);
2946 Mask.push_back(i + NumElems + Half);
2948 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2951 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2952 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2954 if (SV->getValueType(0).getVectorNumElements() <= 4)
2955 return SDValue(SV, 0);
2957 MVT PVT = MVT::v4f32;
2958 MVT VT = SV->getValueType(0);
2959 DebugLoc dl = SV->getDebugLoc();
2960 SDValue V1 = SV->getOperand(0);
2961 int NumElems = VT.getVectorNumElements();
2962 int EltNo = SV->getSplatIndex();
2964 // unpack elements to the correct location
2965 while (NumElems > 4) {
2966 if (EltNo < NumElems/2) {
2967 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2969 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2970 EltNo -= NumElems/2;
2975 // Perform the splat.
2976 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2977 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2978 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2979 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2982 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2983 /// vector of zero or undef vector. This produces a shuffle where the low
2984 /// element of V2 is swizzled into the zero/undef vector, landing at element
2985 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2986 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2987 bool isZero, bool HasSSE2,
2988 SelectionDAG &DAG) {
2989 MVT VT = V2.getValueType();
2991 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2992 unsigned NumElems = VT.getVectorNumElements();
2993 SmallVector<int, 16> MaskVec;
2994 for (unsigned i = 0; i != NumElems; ++i)
2995 // If this is the insertion idx, put the low elt of V2 here.
2996 MaskVec.push_back(i == Idx ? NumElems : i);
2997 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3000 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3001 /// a shuffle that is zero.
3003 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3004 bool Low, SelectionDAG &DAG) {
3005 unsigned NumZeros = 0;
3006 for (int i = 0; i < NumElems; ++i) {
3007 unsigned Index = Low ? i : NumElems-i-1;
3008 int Idx = SVOp->getMaskElt(Index);
3013 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3014 if (Elt.getNode() && X86::isZeroNode(Elt))
3022 /// isVectorShift - Returns true if the shuffle can be implemented as a
3023 /// logical left or right shift of a vector.
3024 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3025 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3026 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3027 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3030 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3033 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3037 bool SeenV1 = false;
3038 bool SeenV2 = false;
3039 for (int i = NumZeros; i < NumElems; ++i) {
3040 int Val = isLeft ? (i - NumZeros) : i;
3041 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3053 if (SeenV1 && SeenV2)
3056 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3062 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3064 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3065 unsigned NumNonZero, unsigned NumZero,
3066 SelectionDAG &DAG, TargetLowering &TLI) {
3070 DebugLoc dl = Op.getDebugLoc();
3073 for (unsigned i = 0; i < 16; ++i) {
3074 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3075 if (ThisIsNonZero && First) {
3077 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3079 V = DAG.getUNDEF(MVT::v8i16);
3084 SDValue ThisElt(0, 0), LastElt(0, 0);
3085 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3086 if (LastIsNonZero) {
3087 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3088 MVT::i16, Op.getOperand(i-1));
3090 if (ThisIsNonZero) {
3091 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3092 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3093 ThisElt, DAG.getConstant(8, MVT::i8));
3095 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3099 if (ThisElt.getNode())
3100 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3101 DAG.getIntPtrConstant(i/2));
3105 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3108 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3110 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3111 unsigned NumNonZero, unsigned NumZero,
3112 SelectionDAG &DAG, TargetLowering &TLI) {
3116 DebugLoc dl = Op.getDebugLoc();
3119 for (unsigned i = 0; i < 8; ++i) {
3120 bool isNonZero = (NonZeros & (1 << i)) != 0;
3124 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3126 V = DAG.getUNDEF(MVT::v8i16);
3129 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3130 MVT::v8i16, V, Op.getOperand(i),
3131 DAG.getIntPtrConstant(i));
3138 /// getVShift - Return a vector logical shift node.
3140 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3141 unsigned NumBits, SelectionDAG &DAG,
3142 const TargetLowering &TLI, DebugLoc dl) {
3143 bool isMMX = VT.getSizeInBits() == 64;
3144 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3145 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3146 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3147 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3148 DAG.getNode(Opc, dl, ShVT, SrcOp,
3149 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3153 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3154 DebugLoc dl = Op.getDebugLoc();
3155 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3156 if (ISD::isBuildVectorAllZeros(Op.getNode())
3157 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3158 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3159 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3160 // eliminated on x86-32 hosts.
3161 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3164 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3165 return getOnesVector(Op.getValueType(), DAG, dl);
3166 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3169 MVT VT = Op.getValueType();
3170 MVT EVT = VT.getVectorElementType();
3171 unsigned EVTBits = EVT.getSizeInBits();
3173 unsigned NumElems = Op.getNumOperands();
3174 unsigned NumZero = 0;
3175 unsigned NumNonZero = 0;
3176 unsigned NonZeros = 0;
3177 bool IsAllConstants = true;
3178 SmallSet<SDValue, 8> Values;
3179 for (unsigned i = 0; i < NumElems; ++i) {
3180 SDValue Elt = Op.getOperand(i);
3181 if (Elt.getOpcode() == ISD::UNDEF)
3184 if (Elt.getOpcode() != ISD::Constant &&
3185 Elt.getOpcode() != ISD::ConstantFP)
3186 IsAllConstants = false;
3187 if (X86::isZeroNode(Elt))
3190 NonZeros |= (1 << i);
3195 if (NumNonZero == 0) {
3196 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3197 return DAG.getUNDEF(VT);
3200 // Special case for single non-zero, non-undef, element.
3201 if (NumNonZero == 1) {
3202 unsigned Idx = CountTrailingZeros_32(NonZeros);
3203 SDValue Item = Op.getOperand(Idx);
3205 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3206 // the value are obviously zero, truncate the value to i32 and do the
3207 // insertion that way. Only do this if the value is non-constant or if the
3208 // value is a constant being inserted into element 0. It is cheaper to do
3209 // a constant pool load than it is to do a movd + shuffle.
3210 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3211 (!IsAllConstants || Idx == 0)) {
3212 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3213 // Handle MMX and SSE both.
3214 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3215 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3217 // Truncate the value (which may itself be a constant) to i32, and
3218 // convert it to a vector with movd (S2V+shuffle to zero extend).
3219 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3220 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3221 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3222 Subtarget->hasSSE2(), DAG);
3224 // Now we have our 32-bit value zero extended in the low element of
3225 // a vector. If Idx != 0, swizzle it into place.
3227 SmallVector<int, 4> Mask;
3228 Mask.push_back(Idx);
3229 for (unsigned i = 1; i != VecElts; ++i)
3231 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3232 DAG.getUNDEF(Item.getValueType()),
3235 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3239 // If we have a constant or non-constant insertion into the low element of
3240 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3241 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3242 // depending on what the source datatype is.
3245 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3246 } else if (EVT == MVT::i32 || EVT == MVT::f32 || EVT == MVT::f64 ||
3247 (EVT == MVT::i64 && Subtarget->is64Bit())) {
3248 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3249 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3250 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3252 } else if (EVT == MVT::i16 || EVT == MVT::i8) {
3253 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3254 MVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3255 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3256 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3257 Subtarget->hasSSE2(), DAG);
3258 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3262 // Is it a vector logical left shift?
3263 if (NumElems == 2 && Idx == 1 &&
3264 X86::isZeroNode(Op.getOperand(0)) &&
3265 !X86::isZeroNode(Op.getOperand(1))) {
3266 unsigned NumBits = VT.getSizeInBits();
3267 return getVShift(true, VT,
3268 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3269 VT, Op.getOperand(1)),
3270 NumBits/2, DAG, *this, dl);
3273 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3276 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3277 // is a non-constant being inserted into an element other than the low one,
3278 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3279 // movd/movss) to move this into the low element, then shuffle it into
3281 if (EVTBits == 32) {
3282 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3284 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3285 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3286 Subtarget->hasSSE2(), DAG);
3287 SmallVector<int, 8> MaskVec;
3288 for (unsigned i = 0; i < NumElems; i++)
3289 MaskVec.push_back(i == Idx ? 0 : 1);
3290 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3294 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3295 if (Values.size() == 1)
3298 // A vector full of immediates; various special cases are already
3299 // handled, so this is best done with a single constant-pool load.
3303 // Let legalizer expand 2-wide build_vectors.
3304 if (EVTBits == 64) {
3305 if (NumNonZero == 1) {
3306 // One half is zero or undef.
3307 unsigned Idx = CountTrailingZeros_32(NonZeros);
3308 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3309 Op.getOperand(Idx));
3310 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3311 Subtarget->hasSSE2(), DAG);
3316 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3317 if (EVTBits == 8 && NumElems == 16) {
3318 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3320 if (V.getNode()) return V;
3323 if (EVTBits == 16 && NumElems == 8) {
3324 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3326 if (V.getNode()) return V;
3329 // If element VT is == 32 bits, turn it into a number of shuffles.
3330 SmallVector<SDValue, 8> V;
3332 if (NumElems == 4 && NumZero > 0) {
3333 for (unsigned i = 0; i < 4; ++i) {
3334 bool isZero = !(NonZeros & (1 << i));
3336 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3338 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3341 for (unsigned i = 0; i < 2; ++i) {
3342 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3345 V[i] = V[i*2]; // Must be a zero vector.
3348 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3351 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3354 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3359 SmallVector<int, 8> MaskVec;
3360 bool Reverse = (NonZeros & 0x3) == 2;
3361 for (unsigned i = 0; i < 2; ++i)
3362 MaskVec.push_back(Reverse ? 1-i : i);
3363 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3364 for (unsigned i = 0; i < 2; ++i)
3365 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3366 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3369 if (Values.size() > 2) {
3370 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3371 // values to be inserted is equal to the number of elements, in which case
3372 // use the unpack code below in the hopes of matching the consecutive elts
3373 // load merge pattern for shuffles.
3374 // FIXME: We could probably just check that here directly.
3375 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3376 getSubtarget()->hasSSE41()) {
3377 V[0] = DAG.getUNDEF(VT);
3378 for (unsigned i = 0; i < NumElems; ++i)
3379 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3380 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3381 Op.getOperand(i), DAG.getIntPtrConstant(i));
3384 // Expand into a number of unpckl*.
3386 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3387 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3388 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3389 for (unsigned i = 0; i < NumElems; ++i)
3390 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3392 while (NumElems != 0) {
3393 for (unsigned i = 0; i < NumElems; ++i)
3394 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3403 // v8i16 shuffles - Prefer shuffles in the following order:
3404 // 1. [all] pshuflw, pshufhw, optional move
3405 // 2. [ssse3] 1 x pshufb
3406 // 3. [ssse3] 2 x pshufb + 1 x por
3407 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3409 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3410 SelectionDAG &DAG, X86TargetLowering &TLI) {
3411 SDValue V1 = SVOp->getOperand(0);
3412 SDValue V2 = SVOp->getOperand(1);
3413 DebugLoc dl = SVOp->getDebugLoc();
3414 SmallVector<int, 8> MaskVals;
3416 // Determine if more than 1 of the words in each of the low and high quadwords
3417 // of the result come from the same quadword of one of the two inputs. Undef
3418 // mask values count as coming from any quadword, for better codegen.
3419 SmallVector<unsigned, 4> LoQuad(4);
3420 SmallVector<unsigned, 4> HiQuad(4);
3421 BitVector InputQuads(4);
3422 for (unsigned i = 0; i < 8; ++i) {
3423 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3424 int EltIdx = SVOp->getMaskElt(i);
3425 MaskVals.push_back(EltIdx);
3434 InputQuads.set(EltIdx / 4);
3437 int BestLoQuad = -1;
3438 unsigned MaxQuad = 1;
3439 for (unsigned i = 0; i < 4; ++i) {
3440 if (LoQuad[i] > MaxQuad) {
3442 MaxQuad = LoQuad[i];
3446 int BestHiQuad = -1;
3448 for (unsigned i = 0; i < 4; ++i) {
3449 if (HiQuad[i] > MaxQuad) {
3451 MaxQuad = HiQuad[i];
3455 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3456 // of the two input vectors, shuffle them into one input vector so only a
3457 // single pshufb instruction is necessary. If There are more than 2 input
3458 // quads, disable the next transformation since it does not help SSSE3.
3459 bool V1Used = InputQuads[0] || InputQuads[1];
3460 bool V2Used = InputQuads[2] || InputQuads[3];
3461 if (TLI.getSubtarget()->hasSSSE3()) {
3462 if (InputQuads.count() == 2 && V1Used && V2Used) {
3463 BestLoQuad = InputQuads.find_first();
3464 BestHiQuad = InputQuads.find_next(BestLoQuad);
3466 if (InputQuads.count() > 2) {
3472 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3473 // the shuffle mask. If a quad is scored as -1, that means that it contains
3474 // words from all 4 input quadwords.
3476 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3477 SmallVector<int, 8> MaskV;
3478 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3479 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3480 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3481 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3482 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3483 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3485 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3486 // source words for the shuffle, to aid later transformations.
3487 bool AllWordsInNewV = true;
3488 bool InOrder[2] = { true, true };
3489 for (unsigned i = 0; i != 8; ++i) {
3490 int idx = MaskVals[i];
3492 InOrder[i/4] = false;
3493 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3495 AllWordsInNewV = false;
3499 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3500 if (AllWordsInNewV) {
3501 for (int i = 0; i != 8; ++i) {
3502 int idx = MaskVals[i];
3505 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3506 if ((idx != i) && idx < 4)
3508 if ((idx != i) && idx > 3)
3517 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3518 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3519 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3520 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3521 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3525 // If we have SSSE3, and all words of the result are from 1 input vector,
3526 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3527 // is present, fall back to case 4.
3528 if (TLI.getSubtarget()->hasSSSE3()) {
3529 SmallVector<SDValue,16> pshufbMask;
3531 // If we have elements from both input vectors, set the high bit of the
3532 // shuffle mask element to zero out elements that come from V2 in the V1
3533 // mask, and elements that come from V1 in the V2 mask, so that the two
3534 // results can be OR'd together.
3535 bool TwoInputs = V1Used && V2Used;
3536 for (unsigned i = 0; i != 8; ++i) {
3537 int EltIdx = MaskVals[i] * 2;
3538 if (TwoInputs && (EltIdx >= 16)) {
3539 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3540 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3543 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3544 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3546 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3547 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3548 DAG.getNode(ISD::BUILD_VECTOR, dl,
3549 MVT::v16i8, &pshufbMask[0], 16));
3551 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3553 // Calculate the shuffle mask for the second input, shuffle it, and
3554 // OR it with the first shuffled input.
3556 for (unsigned i = 0; i != 8; ++i) {
3557 int EltIdx = MaskVals[i] * 2;
3559 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3560 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3563 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3564 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3566 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3567 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3568 DAG.getNode(ISD::BUILD_VECTOR, dl,
3569 MVT::v16i8, &pshufbMask[0], 16));
3570 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3571 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3574 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3575 // and update MaskVals with new element order.
3576 BitVector InOrder(8);
3577 if (BestLoQuad >= 0) {
3578 SmallVector<int, 8> MaskV;
3579 for (int i = 0; i != 4; ++i) {
3580 int idx = MaskVals[i];
3582 MaskV.push_back(-1);
3584 } else if ((idx / 4) == BestLoQuad) {
3585 MaskV.push_back(idx & 3);
3588 MaskV.push_back(-1);
3591 for (unsigned i = 4; i != 8; ++i)
3593 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3597 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3598 // and update MaskVals with the new element order.
3599 if (BestHiQuad >= 0) {
3600 SmallVector<int, 8> MaskV;
3601 for (unsigned i = 0; i != 4; ++i)
3603 for (unsigned i = 4; i != 8; ++i) {
3604 int idx = MaskVals[i];
3606 MaskV.push_back(-1);
3608 } else if ((idx / 4) == BestHiQuad) {
3609 MaskV.push_back((idx & 3) + 4);
3612 MaskV.push_back(-1);
3615 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3619 // In case BestHi & BestLo were both -1, which means each quadword has a word
3620 // from each of the four input quadwords, calculate the InOrder bitvector now
3621 // before falling through to the insert/extract cleanup.
3622 if (BestLoQuad == -1 && BestHiQuad == -1) {
3624 for (int i = 0; i != 8; ++i)
3625 if (MaskVals[i] < 0 || MaskVals[i] == i)
3629 // The other elements are put in the right place using pextrw and pinsrw.
3630 for (unsigned i = 0; i != 8; ++i) {
3633 int EltIdx = MaskVals[i];
3636 SDValue ExtOp = (EltIdx < 8)
3637 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3638 DAG.getIntPtrConstant(EltIdx))
3639 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3640 DAG.getIntPtrConstant(EltIdx - 8));
3641 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3642 DAG.getIntPtrConstant(i));
3647 // v16i8 shuffles - Prefer shuffles in the following order:
3648 // 1. [ssse3] 1 x pshufb
3649 // 2. [ssse3] 2 x pshufb + 1 x por
3650 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3652 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3653 SelectionDAG &DAG, X86TargetLowering &TLI) {
3654 SDValue V1 = SVOp->getOperand(0);
3655 SDValue V2 = SVOp->getOperand(1);
3656 DebugLoc dl = SVOp->getDebugLoc();
3657 SmallVector<int, 16> MaskVals;
3658 SVOp->getMask(MaskVals);
3660 // If we have SSSE3, case 1 is generated when all result bytes come from
3661 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3662 // present, fall back to case 3.
3663 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3666 for (unsigned i = 0; i < 16; ++i) {
3667 int EltIdx = MaskVals[i];
3676 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3677 if (TLI.getSubtarget()->hasSSSE3()) {
3678 SmallVector<SDValue,16> pshufbMask;
3680 // If all result elements are from one input vector, then only translate
3681 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3683 // Otherwise, we have elements from both input vectors, and must zero out
3684 // elements that come from V2 in the first mask, and V1 in the second mask
3685 // so that we can OR them together.
3686 bool TwoInputs = !(V1Only || V2Only);
3687 for (unsigned i = 0; i != 16; ++i) {
3688 int EltIdx = MaskVals[i];
3689 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3690 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3693 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3695 // If all the elements are from V2, assign it to V1 and return after
3696 // building the first pshufb.
3699 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3700 DAG.getNode(ISD::BUILD_VECTOR, dl,
3701 MVT::v16i8, &pshufbMask[0], 16));
3705 // Calculate the shuffle mask for the second input, shuffle it, and
3706 // OR it with the first shuffled input.
3708 for (unsigned i = 0; i != 16; ++i) {
3709 int EltIdx = MaskVals[i];
3711 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3714 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3716 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3717 DAG.getNode(ISD::BUILD_VECTOR, dl,
3718 MVT::v16i8, &pshufbMask[0], 16));
3719 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3722 // No SSSE3 - Calculate in place words and then fix all out of place words
3723 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3724 // the 16 different words that comprise the two doublequadword input vectors.
3725 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3726 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3727 SDValue NewV = V2Only ? V2 : V1;
3728 for (int i = 0; i != 8; ++i) {
3729 int Elt0 = MaskVals[i*2];
3730 int Elt1 = MaskVals[i*2+1];
3732 // This word of the result is all undef, skip it.
3733 if (Elt0 < 0 && Elt1 < 0)
3736 // This word of the result is already in the correct place, skip it.
3737 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3739 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3742 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3743 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3746 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3747 // using a single extract together, load it and store it.
3748 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3749 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3750 DAG.getIntPtrConstant(Elt1 / 2));
3751 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3752 DAG.getIntPtrConstant(i));
3756 // If Elt1 is defined, extract it from the appropriate source. If the
3757 // source byte is not also odd, shift the extracted word left 8 bits
3758 // otherwise clear the bottom 8 bits if we need to do an or.
3760 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3761 DAG.getIntPtrConstant(Elt1 / 2));
3762 if ((Elt1 & 1) == 0)
3763 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3764 DAG.getConstant(8, TLI.getShiftAmountTy()));
3766 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3767 DAG.getConstant(0xFF00, MVT::i16));
3769 // If Elt0 is defined, extract it from the appropriate source. If the
3770 // source byte is not also even, shift the extracted word right 8 bits. If
3771 // Elt1 was also defined, OR the extracted values together before
3772 // inserting them in the result.
3774 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3775 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3776 if ((Elt0 & 1) != 0)
3777 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3778 DAG.getConstant(8, TLI.getShiftAmountTy()));
3780 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3781 DAG.getConstant(0x00FF, MVT::i16));
3782 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3785 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3786 DAG.getIntPtrConstant(i));
3788 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3791 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3792 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3793 /// done when every pair / quad of shuffle mask elements point to elements in
3794 /// the right sequence. e.g.
3795 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3797 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3799 TargetLowering &TLI, DebugLoc dl) {
3800 MVT VT = SVOp->getValueType(0);
3801 SDValue V1 = SVOp->getOperand(0);
3802 SDValue V2 = SVOp->getOperand(1);
3803 unsigned NumElems = VT.getVectorNumElements();
3804 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3805 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3806 MVT MaskEltVT = MaskVT.getVectorElementType();
3808 switch (VT.getSimpleVT()) {
3809 default: assert(false && "Unexpected!");
3810 case MVT::v4f32: NewVT = MVT::v2f64; break;
3811 case MVT::v4i32: NewVT = MVT::v2i64; break;
3812 case MVT::v8i16: NewVT = MVT::v4i32; break;
3813 case MVT::v16i8: NewVT = MVT::v4i32; break;
3816 if (NewWidth == 2) {
3822 int Scale = NumElems / NewWidth;
3823 SmallVector<int, 8> MaskVec;
3824 for (unsigned i = 0; i < NumElems; i += Scale) {
3826 for (int j = 0; j < Scale; ++j) {
3827 int EltIdx = SVOp->getMaskElt(i+j);
3831 StartIdx = EltIdx - (EltIdx % Scale);
3832 if (EltIdx != StartIdx + j)
3836 MaskVec.push_back(-1);
3838 MaskVec.push_back(StartIdx / Scale);
3841 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3842 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3843 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3846 /// getVZextMovL - Return a zero-extending vector move low node.
3848 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3849 SDValue SrcOp, SelectionDAG &DAG,
3850 const X86Subtarget *Subtarget, DebugLoc dl) {
3851 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3852 LoadSDNode *LD = NULL;
3853 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3854 LD = dyn_cast<LoadSDNode>(SrcOp);
3856 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3858 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3859 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3860 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3861 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3862 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3864 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3865 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3866 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3867 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3875 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3876 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3877 DAG.getNode(ISD::BIT_CONVERT, dl,
3881 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3884 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3885 SDValue V1 = SVOp->getOperand(0);
3886 SDValue V2 = SVOp->getOperand(1);
3887 DebugLoc dl = SVOp->getDebugLoc();
3888 MVT VT = SVOp->getValueType(0);
3890 SmallVector<std::pair<int, int>, 8> Locs;
3892 SmallVector<int, 8> Mask1(4U, -1);
3893 SmallVector<int, 8> PermMask;
3894 SVOp->getMask(PermMask);
3898 for (unsigned i = 0; i != 4; ++i) {
3899 int Idx = PermMask[i];
3901 Locs[i] = std::make_pair(-1, -1);
3903 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3905 Locs[i] = std::make_pair(0, NumLo);
3909 Locs[i] = std::make_pair(1, NumHi);
3911 Mask1[2+NumHi] = Idx;
3917 if (NumLo <= 2 && NumHi <= 2) {
3918 // If no more than two elements come from either vector. This can be
3919 // implemented with two shuffles. First shuffle gather the elements.
3920 // The second shuffle, which takes the first shuffle as both of its
3921 // vector operands, put the elements into the right order.
3922 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3924 SmallVector<int, 8> Mask2(4U, -1);
3926 for (unsigned i = 0; i != 4; ++i) {
3927 if (Locs[i].first == -1)
3930 unsigned Idx = (i < 2) ? 0 : 4;
3931 Idx += Locs[i].first * 2 + Locs[i].second;
3936 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3937 } else if (NumLo == 3 || NumHi == 3) {
3938 // Otherwise, we must have three elements from one vector, call it X, and
3939 // one element from the other, call it Y. First, use a shufps to build an
3940 // intermediate vector with the one element from Y and the element from X
3941 // that will be in the same half in the final destination (the indexes don't
3942 // matter). Then, use a shufps to build the final vector, taking the half
3943 // containing the element from Y from the intermediate, and the other half
3946 // Normalize it so the 3 elements come from V1.
3947 CommuteVectorShuffleMask(PermMask, VT);
3951 // Find the element from V2.
3953 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3954 int Val = PermMask[HiIndex];
3961 Mask1[0] = PermMask[HiIndex];
3963 Mask1[2] = PermMask[HiIndex^1];
3965 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3968 Mask1[0] = PermMask[0];
3969 Mask1[1] = PermMask[1];
3970 Mask1[2] = HiIndex & 1 ? 6 : 4;
3971 Mask1[3] = HiIndex & 1 ? 4 : 6;
3972 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3974 Mask1[0] = HiIndex & 1 ? 2 : 0;
3975 Mask1[1] = HiIndex & 1 ? 0 : 2;
3976 Mask1[2] = PermMask[2];
3977 Mask1[3] = PermMask[3];
3982 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3986 // Break it into (shuffle shuffle_hi, shuffle_lo).
3988 SmallVector<int,8> LoMask(4U, -1);
3989 SmallVector<int,8> HiMask(4U, -1);
3991 SmallVector<int,8> *MaskPtr = &LoMask;
3992 unsigned MaskIdx = 0;
3995 for (unsigned i = 0; i != 4; ++i) {
4002 int Idx = PermMask[i];
4004 Locs[i] = std::make_pair(-1, -1);
4005 } else if (Idx < 4) {
4006 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4007 (*MaskPtr)[LoIdx] = Idx;
4010 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4011 (*MaskPtr)[HiIdx] = Idx;
4016 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4017 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4018 SmallVector<int, 8> MaskOps;
4019 for (unsigned i = 0; i != 4; ++i) {
4020 if (Locs[i].first == -1) {
4021 MaskOps.push_back(-1);
4023 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4024 MaskOps.push_back(Idx);
4027 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4031 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4032 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4033 SDValue V1 = Op.getOperand(0);
4034 SDValue V2 = Op.getOperand(1);
4035 MVT VT = Op.getValueType();
4036 DebugLoc dl = Op.getDebugLoc();
4037 unsigned NumElems = VT.getVectorNumElements();
4038 bool isMMX = VT.getSizeInBits() == 64;
4039 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4040 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4041 bool V1IsSplat = false;
4042 bool V2IsSplat = false;
4044 if (isZeroShuffle(SVOp))
4045 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4047 // Promote splats to v4f32.
4048 if (SVOp->isSplat()) {
4049 if (isMMX || NumElems < 4)
4051 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4054 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4056 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4057 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4058 if (NewOp.getNode())
4059 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4060 LowerVECTOR_SHUFFLE(NewOp, DAG));
4061 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4062 // FIXME: Figure out a cleaner way to do this.
4063 // Try to make use of movq to zero out the top part.
4064 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4065 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4066 if (NewOp.getNode()) {
4067 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4068 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4069 DAG, Subtarget, dl);
4071 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4072 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4073 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4074 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4075 DAG, Subtarget, dl);
4079 if (X86::isPSHUFDMask(SVOp))
4082 // Check if this can be converted into a logical shift.
4083 bool isLeft = false;
4086 bool isShift = getSubtarget()->hasSSE2() &&
4087 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4088 if (isShift && ShVal.hasOneUse()) {
4089 // If the shifted value has multiple uses, it may be cheaper to use
4090 // v_set0 + movlhps or movhlps, etc.
4091 MVT EVT = VT.getVectorElementType();
4092 ShAmt *= EVT.getSizeInBits();
4093 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4096 if (X86::isMOVLMask(SVOp)) {
4099 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4100 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4105 // FIXME: fold these into legal mask.
4106 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4107 X86::isMOVSLDUPMask(SVOp) ||
4108 X86::isMOVHLPSMask(SVOp) ||
4109 X86::isMOVHPMask(SVOp) ||
4110 X86::isMOVLPMask(SVOp)))
4113 if (ShouldXformToMOVHLPS(SVOp) ||
4114 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4115 return CommuteVectorShuffle(SVOp, DAG);
4118 // No better options. Use a vshl / vsrl.
4119 MVT EVT = VT.getVectorElementType();
4120 ShAmt *= EVT.getSizeInBits();
4121 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4124 bool Commuted = false;
4125 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4126 // 1,1,1,1 -> v8i16 though.
4127 V1IsSplat = isSplatVector(V1.getNode());
4128 V2IsSplat = isSplatVector(V2.getNode());
4130 // Canonicalize the splat or undef, if present, to be on the RHS.
4131 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4132 Op = CommuteVectorShuffle(SVOp, DAG);
4133 SVOp = cast<ShuffleVectorSDNode>(Op);
4134 V1 = SVOp->getOperand(0);
4135 V2 = SVOp->getOperand(1);
4136 std::swap(V1IsSplat, V2IsSplat);
4137 std::swap(V1IsUndef, V2IsUndef);
4141 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4142 // Shuffling low element of v1 into undef, just return v1.
4145 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4146 // the instruction selector will not match, so get a canonical MOVL with
4147 // swapped operands to undo the commute.
4148 return getMOVL(DAG, dl, VT, V2, V1);
4151 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4152 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4153 X86::isUNPCKLMask(SVOp) ||
4154 X86::isUNPCKHMask(SVOp))
4158 // Normalize mask so all entries that point to V2 points to its first
4159 // element then try to match unpck{h|l} again. If match, return a
4160 // new vector_shuffle with the corrected mask.
4161 SDValue NewMask = NormalizeMask(SVOp, DAG);
4162 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4163 if (NSVOp != SVOp) {
4164 if (X86::isUNPCKLMask(NSVOp, true)) {
4166 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4173 // Commute is back and try unpck* again.
4174 // FIXME: this seems wrong.
4175 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4176 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4177 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4178 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4179 X86::isUNPCKLMask(NewSVOp) ||
4180 X86::isUNPCKHMask(NewSVOp))
4184 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4186 // Normalize the node to match x86 shuffle ops if needed
4187 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4188 return CommuteVectorShuffle(SVOp, DAG);
4190 // Check for legal shuffle and return?
4191 SmallVector<int, 16> PermMask;
4192 SVOp->getMask(PermMask);
4193 if (isShuffleMaskLegal(PermMask, VT))
4196 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4197 if (VT == MVT::v8i16) {
4198 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4199 if (NewOp.getNode())
4203 if (VT == MVT::v16i8) {
4204 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4205 if (NewOp.getNode())
4209 // Handle all 4 wide cases with a number of shuffles except for MMX.
4210 if (NumElems == 4 && !isMMX)
4211 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4217 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4218 SelectionDAG &DAG) {
4219 MVT VT = Op.getValueType();
4220 DebugLoc dl = Op.getDebugLoc();
4221 if (VT.getSizeInBits() == 8) {
4222 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4223 Op.getOperand(0), Op.getOperand(1));
4224 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4225 DAG.getValueType(VT));
4226 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4227 } else if (VT.getSizeInBits() == 16) {
4228 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4229 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4231 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4232 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4233 DAG.getNode(ISD::BIT_CONVERT, dl,
4237 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4238 Op.getOperand(0), Op.getOperand(1));
4239 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4240 DAG.getValueType(VT));
4241 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4242 } else if (VT == MVT::f32) {
4243 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4244 // the result back to FR32 register. It's only worth matching if the
4245 // result has a single use which is a store or a bitcast to i32. And in
4246 // the case of a store, it's not worth it if the index is a constant 0,
4247 // because a MOVSSmr can be used instead, which is smaller and faster.
4248 if (!Op.hasOneUse())
4250 SDNode *User = *Op.getNode()->use_begin();
4251 if ((User->getOpcode() != ISD::STORE ||
4252 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4253 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4254 (User->getOpcode() != ISD::BIT_CONVERT ||
4255 User->getValueType(0) != MVT::i32))
4257 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4258 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4261 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4262 } else if (VT == MVT::i32) {
4263 // ExtractPS works with constant index.
4264 if (isa<ConstantSDNode>(Op.getOperand(1)))
4272 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4273 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4276 if (Subtarget->hasSSE41()) {
4277 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4282 MVT VT = Op.getValueType();
4283 DebugLoc dl = Op.getDebugLoc();
4284 // TODO: handle v16i8.
4285 if (VT.getSizeInBits() == 16) {
4286 SDValue Vec = Op.getOperand(0);
4287 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4289 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4290 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4291 DAG.getNode(ISD::BIT_CONVERT, dl,
4294 // Transform it so it match pextrw which produces a 32-bit result.
4295 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4296 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4297 Op.getOperand(0), Op.getOperand(1));
4298 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4299 DAG.getValueType(VT));
4300 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4301 } else if (VT.getSizeInBits() == 32) {
4302 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4306 // SHUFPS the element to the lowest double word, then movss.
4307 int Mask[4] = { Idx, -1, -1, -1 };
4308 MVT VVT = Op.getOperand(0).getValueType();
4309 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4310 DAG.getUNDEF(VVT), Mask);
4311 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4312 DAG.getIntPtrConstant(0));
4313 } else if (VT.getSizeInBits() == 64) {
4314 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4315 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4316 // to match extract_elt for f64.
4317 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4321 // UNPCKHPD the element to the lowest double word, then movsd.
4322 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4323 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4324 int Mask[2] = { 1, -1 };
4325 MVT VVT = Op.getOperand(0).getValueType();
4326 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4327 DAG.getUNDEF(VVT), Mask);
4328 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4329 DAG.getIntPtrConstant(0));
4336 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4337 MVT VT = Op.getValueType();
4338 MVT EVT = VT.getVectorElementType();
4339 DebugLoc dl = Op.getDebugLoc();
4341 SDValue N0 = Op.getOperand(0);
4342 SDValue N1 = Op.getOperand(1);
4343 SDValue N2 = Op.getOperand(2);
4345 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4346 isa<ConstantSDNode>(N2)) {
4347 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4349 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4351 if (N1.getValueType() != MVT::i32)
4352 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4353 if (N2.getValueType() != MVT::i32)
4354 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4355 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4356 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4357 // Bits [7:6] of the constant are the source select. This will always be
4358 // zero here. The DAG Combiner may combine an extract_elt index into these
4359 // bits. For example (insert (extract, 3), 2) could be matched by putting
4360 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4361 // Bits [5:4] of the constant are the destination select. This is the
4362 // value of the incoming immediate.
4363 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4364 // combine either bitwise AND or insert of float 0.0 to set these bits.
4365 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4366 // Create this as a scalar to vector..
4367 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4368 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4369 } else if (EVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4370 // PINSR* works with constant index.
4377 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4378 MVT VT = Op.getValueType();
4379 MVT EVT = VT.getVectorElementType();
4381 if (Subtarget->hasSSE41())
4382 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4387 DebugLoc dl = Op.getDebugLoc();
4388 SDValue N0 = Op.getOperand(0);
4389 SDValue N1 = Op.getOperand(1);
4390 SDValue N2 = Op.getOperand(2);
4392 if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4393 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4394 // as its second argument.
4395 if (N1.getValueType() != MVT::i32)
4396 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4397 if (N2.getValueType() != MVT::i32)
4398 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4399 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4405 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4406 DebugLoc dl = Op.getDebugLoc();
4407 if (Op.getValueType() == MVT::v2f32)
4408 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4409 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4410 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4411 Op.getOperand(0))));
4413 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4414 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4416 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4417 MVT VT = MVT::v2i32;
4418 switch (Op.getValueType().getSimpleVT()) {
4425 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4426 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4429 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4430 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4431 // one of the above mentioned nodes. It has to be wrapped because otherwise
4432 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4433 // be used to form addressing mode. These wrapped nodes will be selected
4436 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4437 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4439 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4441 unsigned char OpFlag = 0;
4442 unsigned WrapperKind = X86ISD::Wrapper;
4444 if (Subtarget->isPICStyleRIPRel() &&
4445 getTargetMachine().getCodeModel() == CodeModel::Small)
4446 WrapperKind = X86ISD::WrapperRIP;
4447 else if (Subtarget->isPICStyleGOT())
4448 OpFlag = X86II::MO_GOTOFF;
4449 else if (Subtarget->isPICStyleStubPIC())
4450 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4452 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4454 CP->getOffset(), OpFlag);
4455 DebugLoc DL = CP->getDebugLoc();
4456 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4457 // With PIC, the address is actually $g + Offset.
4459 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4460 DAG.getNode(X86ISD::GlobalBaseReg,
4461 DebugLoc::getUnknownLoc(), getPointerTy()),
4468 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4469 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4471 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4473 unsigned char OpFlag = 0;
4474 unsigned WrapperKind = X86ISD::Wrapper;
4476 if (Subtarget->isPICStyleRIPRel() &&
4477 getTargetMachine().getCodeModel() == CodeModel::Small)
4478 WrapperKind = X86ISD::WrapperRIP;
4479 else if (Subtarget->isPICStyleGOT())
4480 OpFlag = X86II::MO_GOTOFF;
4481 else if (Subtarget->isPICStyleStubPIC())
4482 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4484 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4486 DebugLoc DL = JT->getDebugLoc();
4487 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4489 // With PIC, the address is actually $g + Offset.
4491 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4492 DAG.getNode(X86ISD::GlobalBaseReg,
4493 DebugLoc::getUnknownLoc(), getPointerTy()),
4501 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4502 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4504 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4506 unsigned char OpFlag = 0;
4507 unsigned WrapperKind = X86ISD::Wrapper;
4508 if (Subtarget->isPICStyleRIPRel() &&
4509 getTargetMachine().getCodeModel() == CodeModel::Small)
4510 WrapperKind = X86ISD::WrapperRIP;
4511 else if (Subtarget->isPICStyleGOT())
4512 OpFlag = X86II::MO_GOTOFF;
4513 else if (Subtarget->isPICStyleStubPIC())
4514 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4516 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4518 DebugLoc DL = Op.getDebugLoc();
4519 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4522 // With PIC, the address is actually $g + Offset.
4523 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4524 !Subtarget->is64Bit()) {
4525 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4526 DAG.getNode(X86ISD::GlobalBaseReg,
4527 DebugLoc::getUnknownLoc(),
4536 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4538 SelectionDAG &DAG) const {
4539 // Create the TargetGlobalAddress node, folding in the constant
4540 // offset if it is legal.
4541 unsigned char OpFlags =
4542 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4544 if (OpFlags == X86II::MO_NO_FLAG && isInt32(Offset)) {
4545 // A direct static reference to a global.
4546 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4549 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4552 if (Subtarget->isPICStyleRIPRel() &&
4553 getTargetMachine().getCodeModel() == CodeModel::Small)
4554 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4556 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4558 // With PIC, the address is actually $g + Offset.
4559 if (isGlobalRelativeToPICBase(OpFlags)) {
4560 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4561 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4565 // For globals that require a load from a stub to get the address, emit the
4567 if (isGlobalStubReference(OpFlags))
4568 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4569 PseudoSourceValue::getGOT(), 0);
4571 // If there was a non-zero offset that we didn't fold, create an explicit
4574 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4575 DAG.getConstant(Offset, getPointerTy()));
4581 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4582 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4583 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4584 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4588 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4589 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg,
4590 unsigned char OperandFlags) {
4591 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4592 DebugLoc dl = GA->getDebugLoc();
4593 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4594 GA->getValueType(0),
4598 SDValue Ops[] = { Chain, TGA, *InFlag };
4599 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4601 SDValue Ops[] = { Chain, TGA };
4602 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4604 SDValue Flag = Chain.getValue(1);
4605 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4608 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4610 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4613 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4614 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4615 DAG.getNode(X86ISD::GlobalBaseReg,
4616 DebugLoc::getUnknownLoc(),
4618 InFlag = Chain.getValue(1);
4620 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4623 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4625 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4627 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4628 X86::RAX, X86II::MO_TLSGD);
4631 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4632 // "local exec" model.
4633 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4634 const MVT PtrVT, TLSModel::Model model,
4636 DebugLoc dl = GA->getDebugLoc();
4637 // Get the Thread Pointer
4638 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4639 DebugLoc::getUnknownLoc(), PtrVT,
4640 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4643 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4646 unsigned char OperandFlags = 0;
4647 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4649 unsigned WrapperKind = X86ISD::Wrapper;
4650 if (model == TLSModel::LocalExec) {
4651 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4652 } else if (is64Bit) {
4653 assert(model == TLSModel::InitialExec);
4654 OperandFlags = X86II::MO_GOTTPOFF;
4655 WrapperKind = X86ISD::WrapperRIP;
4657 assert(model == TLSModel::InitialExec);
4658 OperandFlags = X86II::MO_INDNTPOFF;
4661 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4663 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4664 GA->getOffset(), OperandFlags);
4665 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4667 if (model == TLSModel::InitialExec)
4668 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4669 PseudoSourceValue::getGOT(), 0);
4671 // The address of the thread local variable is the add of the thread
4672 // pointer with the offset of the variable.
4673 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4677 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4678 // TODO: implement the "local dynamic" model
4679 // TODO: implement the "initial exec"model for pic executables
4680 assert(Subtarget->isTargetELF() &&
4681 "TLS not implemented for non-ELF targets");
4682 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4683 const GlobalValue *GV = GA->getGlobal();
4685 // If GV is an alias then use the aliasee for determining
4686 // thread-localness.
4687 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4688 GV = GA->resolveAliasedGlobal(false);
4690 TLSModel::Model model = getTLSModel(GV,
4691 getTargetMachine().getRelocationModel());
4694 case TLSModel::GeneralDynamic:
4695 case TLSModel::LocalDynamic: // not implemented
4696 if (Subtarget->is64Bit())
4697 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4698 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4700 case TLSModel::InitialExec:
4701 case TLSModel::LocalExec:
4702 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4703 Subtarget->is64Bit());
4706 llvm_unreachable("Unreachable");
4711 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4712 /// take a 2 x i32 value to shift plus a shift amount.
4713 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4714 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4715 MVT VT = Op.getValueType();
4716 unsigned VTBits = VT.getSizeInBits();
4717 DebugLoc dl = Op.getDebugLoc();
4718 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4719 SDValue ShOpLo = Op.getOperand(0);
4720 SDValue ShOpHi = Op.getOperand(1);
4721 SDValue ShAmt = Op.getOperand(2);
4722 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4723 DAG.getConstant(VTBits - 1, MVT::i8))
4724 : DAG.getConstant(0, VT);
4727 if (Op.getOpcode() == ISD::SHL_PARTS) {
4728 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4729 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4731 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4732 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4735 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4736 DAG.getConstant(VTBits, MVT::i8));
4737 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4738 AndNode, DAG.getConstant(0, MVT::i8));
4741 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4742 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4743 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4745 if (Op.getOpcode() == ISD::SHL_PARTS) {
4746 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4747 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4749 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4750 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4753 SDValue Ops[2] = { Lo, Hi };
4754 return DAG.getMergeValues(Ops, 2, dl);
4757 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4758 MVT SrcVT = Op.getOperand(0).getValueType();
4760 if (SrcVT.isVector()) {
4761 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4767 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4768 "Unknown SINT_TO_FP to lower!");
4770 // These are really Legal; return the operand so the caller accepts it as
4772 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4774 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4775 Subtarget->is64Bit()) {
4779 DebugLoc dl = Op.getDebugLoc();
4780 unsigned Size = SrcVT.getSizeInBits()/8;
4781 MachineFunction &MF = DAG.getMachineFunction();
4782 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4783 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4784 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4786 PseudoSourceValue::getFixedStack(SSFI), 0);
4787 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4790 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4792 SelectionDAG &DAG) {
4794 DebugLoc dl = Op.getDebugLoc();
4796 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4798 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4800 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4801 SmallVector<SDValue, 8> Ops;
4802 Ops.push_back(Chain);
4803 Ops.push_back(StackSlot);
4804 Ops.push_back(DAG.getValueType(SrcVT));
4805 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4806 Tys, &Ops[0], Ops.size());
4809 Chain = Result.getValue(1);
4810 SDValue InFlag = Result.getValue(2);
4812 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4813 // shouldn't be necessary except that RFP cannot be live across
4814 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4815 MachineFunction &MF = DAG.getMachineFunction();
4816 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4817 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4818 Tys = DAG.getVTList(MVT::Other);
4819 SmallVector<SDValue, 8> Ops;
4820 Ops.push_back(Chain);
4821 Ops.push_back(Result);
4822 Ops.push_back(StackSlot);
4823 Ops.push_back(DAG.getValueType(Op.getValueType()));
4824 Ops.push_back(InFlag);
4825 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4826 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4827 PseudoSourceValue::getFixedStack(SSFI), 0);
4833 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4834 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4835 // This algorithm is not obvious. Here it is in C code, more or less:
4837 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4838 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4839 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4841 // Copy ints to xmm registers.
4842 __m128i xh = _mm_cvtsi32_si128( hi );
4843 __m128i xl = _mm_cvtsi32_si128( lo );
4845 // Combine into low half of a single xmm register.
4846 __m128i x = _mm_unpacklo_epi32( xh, xl );
4850 // Merge in appropriate exponents to give the integer bits the right
4852 x = _mm_unpacklo_epi32( x, exp );
4854 // Subtract away the biases to deal with the IEEE-754 double precision
4856 d = _mm_sub_pd( (__m128d) x, bias );
4858 // All conversions up to here are exact. The correctly rounded result is
4859 // calculated using the current rounding mode using the following
4861 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4862 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4863 // store doesn't really need to be here (except
4864 // maybe to zero the other double)
4869 DebugLoc dl = Op.getDebugLoc();
4870 LLVMContext *Context = DAG.getContext();
4872 // Build some magic constants.
4873 std::vector<Constant*> CV0;
4874 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
4875 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
4876 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4877 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4878 Constant *C0 = ConstantVector::get(CV0);
4879 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4881 std::vector<Constant*> CV1;
4883 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
4885 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
4886 Constant *C1 = ConstantVector::get(CV1);
4887 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4889 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4890 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4892 DAG.getIntPtrConstant(1)));
4893 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4894 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4896 DAG.getIntPtrConstant(0)));
4897 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4898 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4899 PseudoSourceValue::getConstantPool(), 0,
4901 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4902 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4903 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4904 PseudoSourceValue::getConstantPool(), 0,
4906 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4908 // Add the halves; easiest way is to swap them into another reg first.
4909 int ShufMask[2] = { 1, -1 };
4910 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4911 DAG.getUNDEF(MVT::v2f64), ShufMask);
4912 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4913 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4914 DAG.getIntPtrConstant(0));
4917 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4918 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4919 DebugLoc dl = Op.getDebugLoc();
4920 // FP constant to bias correct the final result.
4921 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4924 // Load the 32-bit value into an XMM register.
4925 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4926 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4928 DAG.getIntPtrConstant(0)));
4930 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4931 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4932 DAG.getIntPtrConstant(0));
4934 // Or the load with the bias.
4935 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4936 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4937 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4939 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4940 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4941 MVT::v2f64, Bias)));
4942 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4943 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4944 DAG.getIntPtrConstant(0));
4946 // Subtract the bias.
4947 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4949 // Handle final rounding.
4950 MVT DestVT = Op.getValueType();
4952 if (DestVT.bitsLT(MVT::f64)) {
4953 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4954 DAG.getIntPtrConstant(0));
4955 } else if (DestVT.bitsGT(MVT::f64)) {
4956 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4959 // Handle final rounding.
4963 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4964 SDValue N0 = Op.getOperand(0);
4965 DebugLoc dl = Op.getDebugLoc();
4967 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4968 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4969 // the optimization here.
4970 if (DAG.SignBitIsZero(N0))
4971 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4973 MVT SrcVT = N0.getValueType();
4974 if (SrcVT == MVT::i64) {
4975 // We only handle SSE2 f64 target here; caller can expand the rest.
4976 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4979 return LowerUINT_TO_FP_i64(Op, DAG);
4980 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4981 return LowerUINT_TO_FP_i32(Op, DAG);
4984 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4986 // Make a 64-bit buffer, and use it to build an FILD.
4987 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4988 SDValue WordOff = DAG.getConstant(4, getPointerTy());
4989 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4990 getPointerTy(), StackSlot, WordOff);
4991 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4992 StackSlot, NULL, 0);
4993 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4994 OffsetSlot, NULL, 0);
4995 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4998 std::pair<SDValue,SDValue> X86TargetLowering::
4999 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5000 DebugLoc dl = Op.getDebugLoc();
5002 MVT DstTy = Op.getValueType();
5005 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5009 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5010 DstTy.getSimpleVT() >= MVT::i16 &&
5011 "Unknown FP_TO_SINT to lower!");
5013 // These are really Legal.
5014 if (DstTy == MVT::i32 &&
5015 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5016 return std::make_pair(SDValue(), SDValue());
5017 if (Subtarget->is64Bit() &&
5018 DstTy == MVT::i64 &&
5019 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5020 return std::make_pair(SDValue(), SDValue());
5022 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5024 MachineFunction &MF = DAG.getMachineFunction();
5025 unsigned MemSize = DstTy.getSizeInBits()/8;
5026 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5027 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5030 switch (DstTy.getSimpleVT()) {
5031 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5032 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5033 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5034 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5037 SDValue Chain = DAG.getEntryNode();
5038 SDValue Value = Op.getOperand(0);
5039 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5040 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5041 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5042 PseudoSourceValue::getFixedStack(SSFI), 0);
5043 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5045 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5047 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5048 Chain = Value.getValue(1);
5049 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5050 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5053 // Build the FP_TO_INT*_IN_MEM
5054 SDValue Ops[] = { Chain, Value, StackSlot };
5055 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5057 return std::make_pair(FIST, StackSlot);
5060 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5061 if (Op.getValueType().isVector()) {
5062 if (Op.getValueType() == MVT::v2i32 &&
5063 Op.getOperand(0).getValueType() == MVT::v2f64) {
5069 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5070 SDValue FIST = Vals.first, StackSlot = Vals.second;
5071 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5072 if (FIST.getNode() == 0) return Op;
5075 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5076 FIST, StackSlot, NULL, 0);
5079 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5080 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5081 SDValue FIST = Vals.first, StackSlot = Vals.second;
5082 assert(FIST.getNode() && "Unexpected failure");
5085 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5086 FIST, StackSlot, NULL, 0);
5089 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5090 LLVMContext *Context = DAG.getContext();
5091 DebugLoc dl = Op.getDebugLoc();
5092 MVT VT = Op.getValueType();
5095 EltVT = VT.getVectorElementType();
5096 std::vector<Constant*> CV;
5097 if (EltVT == MVT::f64) {
5098 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5102 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5108 Constant *C = ConstantVector::get(CV);
5109 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5110 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5111 PseudoSourceValue::getConstantPool(), 0,
5113 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5116 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5117 LLVMContext *Context = DAG.getContext();
5118 DebugLoc dl = Op.getDebugLoc();
5119 MVT VT = Op.getValueType();
5121 unsigned EltNum = 1;
5122 if (VT.isVector()) {
5123 EltVT = VT.getVectorElementType();
5124 EltNum = VT.getVectorNumElements();
5126 std::vector<Constant*> CV;
5127 if (EltVT == MVT::f64) {
5128 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5132 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5138 Constant *C = ConstantVector::get(CV);
5139 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5140 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5141 PseudoSourceValue::getConstantPool(), 0,
5143 if (VT.isVector()) {
5144 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5145 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5146 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5148 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5150 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5154 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5155 LLVMContext *Context = DAG.getContext();
5156 SDValue Op0 = Op.getOperand(0);
5157 SDValue Op1 = Op.getOperand(1);
5158 DebugLoc dl = Op.getDebugLoc();
5159 MVT VT = Op.getValueType();
5160 MVT SrcVT = Op1.getValueType();
5162 // If second operand is smaller, extend it first.
5163 if (SrcVT.bitsLT(VT)) {
5164 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5167 // And if it is bigger, shrink it first.
5168 if (SrcVT.bitsGT(VT)) {
5169 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5173 // At this point the operands and the result should have the same
5174 // type, and that won't be f80 since that is not custom lowered.
5176 // First get the sign bit of second operand.
5177 std::vector<Constant*> CV;
5178 if (SrcVT == MVT::f64) {
5179 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5180 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5182 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5183 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5184 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5185 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5187 Constant *C = ConstantVector::get(CV);
5188 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5189 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5190 PseudoSourceValue::getConstantPool(), 0,
5192 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5194 // Shift sign bit right or left if the two operands have different types.
5195 if (SrcVT.bitsGT(VT)) {
5196 // Op0 is MVT::f32, Op1 is MVT::f64.
5197 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5198 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5199 DAG.getConstant(32, MVT::i32));
5200 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5201 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5202 DAG.getIntPtrConstant(0));
5205 // Clear first operand sign bit.
5207 if (VT == MVT::f64) {
5208 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5209 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5211 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5212 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5213 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5214 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5216 C = ConstantVector::get(CV);
5217 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5218 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5219 PseudoSourceValue::getConstantPool(), 0,
5221 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5223 // Or the value with the sign bit.
5224 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5227 /// Emit nodes that will be selected as "test Op0,Op0", or something
5229 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5230 SelectionDAG &DAG) {
5231 DebugLoc dl = Op.getDebugLoc();
5233 // CF and OF aren't always set the way we want. Determine which
5234 // of these we need.
5235 bool NeedCF = false;
5236 bool NeedOF = false;
5238 case X86::COND_A: case X86::COND_AE:
5239 case X86::COND_B: case X86::COND_BE:
5242 case X86::COND_G: case X86::COND_GE:
5243 case X86::COND_L: case X86::COND_LE:
5244 case X86::COND_O: case X86::COND_NO:
5250 // See if we can use the EFLAGS value from the operand instead of
5251 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5252 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5253 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5254 unsigned Opcode = 0;
5255 unsigned NumOperands = 0;
5256 switch (Op.getNode()->getOpcode()) {
5258 // Due to an isel shortcoming, be conservative if this add is likely to
5259 // be selected as part of a load-modify-store instruction. When the root
5260 // node in a match is a store, isel doesn't know how to remap non-chain
5261 // non-flag uses of other nodes in the match, such as the ADD in this
5262 // case. This leads to the ADD being left around and reselected, with
5263 // the result being two adds in the output.
5264 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5265 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5266 if (UI->getOpcode() == ISD::STORE)
5268 if (ConstantSDNode *C =
5269 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5270 // An add of one will be selected as an INC.
5271 if (C->getAPIntValue() == 1) {
5272 Opcode = X86ISD::INC;
5276 // An add of negative one (subtract of one) will be selected as a DEC.
5277 if (C->getAPIntValue().isAllOnesValue()) {
5278 Opcode = X86ISD::DEC;
5283 // Otherwise use a regular EFLAGS-setting add.
5284 Opcode = X86ISD::ADD;
5288 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5289 // likely to be selected as part of a load-modify-store instruction.
5290 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5291 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5292 if (UI->getOpcode() == ISD::STORE)
5294 // Otherwise use a regular EFLAGS-setting sub.
5295 Opcode = X86ISD::SUB;
5302 return SDValue(Op.getNode(), 1);
5308 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5309 SmallVector<SDValue, 4> Ops;
5310 for (unsigned i = 0; i != NumOperands; ++i)
5311 Ops.push_back(Op.getOperand(i));
5312 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5313 DAG.ReplaceAllUsesWith(Op, New);
5314 return SDValue(New.getNode(), 1);
5318 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5319 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5320 DAG.getConstant(0, Op.getValueType()));
5323 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5325 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5326 SelectionDAG &DAG) {
5327 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5328 if (C->getAPIntValue() == 0)
5329 return EmitTest(Op0, X86CC, DAG);
5331 DebugLoc dl = Op0.getDebugLoc();
5332 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5335 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5336 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5337 SDValue Op0 = Op.getOperand(0);
5338 SDValue Op1 = Op.getOperand(1);
5339 DebugLoc dl = Op.getDebugLoc();
5340 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5342 // Lower (X & (1 << N)) == 0 to BT(X, N).
5343 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5344 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5345 if (Op0.getOpcode() == ISD::AND &&
5347 Op1.getOpcode() == ISD::Constant &&
5348 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5349 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5351 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5352 if (ConstantSDNode *Op010C =
5353 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5354 if (Op010C->getZExtValue() == 1) {
5355 LHS = Op0.getOperand(0);
5356 RHS = Op0.getOperand(1).getOperand(1);
5358 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5359 if (ConstantSDNode *Op000C =
5360 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5361 if (Op000C->getZExtValue() == 1) {
5362 LHS = Op0.getOperand(1);
5363 RHS = Op0.getOperand(0).getOperand(1);
5365 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5366 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5367 SDValue AndLHS = Op0.getOperand(0);
5368 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5369 LHS = AndLHS.getOperand(0);
5370 RHS = AndLHS.getOperand(1);
5374 if (LHS.getNode()) {
5375 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5376 // instruction. Since the shift amount is in-range-or-undefined, we know
5377 // that doing a bittest on the i16 value is ok. We extend to i32 because
5378 // the encoding for the i16 version is larger than the i32 version.
5379 if (LHS.getValueType() == MVT::i8)
5380 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5382 // If the operand types disagree, extend the shift amount to match. Since
5383 // BT ignores high bits (like shifts) we can use anyextend.
5384 if (LHS.getValueType() != RHS.getValueType())
5385 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5387 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5388 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5389 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5390 DAG.getConstant(Cond, MVT::i8), BT);
5394 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5395 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5397 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5398 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5399 DAG.getConstant(X86CC, MVT::i8), Cond);
5402 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5404 SDValue Op0 = Op.getOperand(0);
5405 SDValue Op1 = Op.getOperand(1);
5406 SDValue CC = Op.getOperand(2);
5407 MVT VT = Op.getValueType();
5408 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5409 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5410 DebugLoc dl = Op.getDebugLoc();
5414 MVT VT0 = Op0.getValueType();
5415 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5416 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5419 switch (SetCCOpcode) {
5422 case ISD::SETEQ: SSECC = 0; break;
5424 case ISD::SETGT: Swap = true; // Fallthrough
5426 case ISD::SETOLT: SSECC = 1; break;
5428 case ISD::SETGE: Swap = true; // Fallthrough
5430 case ISD::SETOLE: SSECC = 2; break;
5431 case ISD::SETUO: SSECC = 3; break;
5433 case ISD::SETNE: SSECC = 4; break;
5434 case ISD::SETULE: Swap = true;
5435 case ISD::SETUGE: SSECC = 5; break;
5436 case ISD::SETULT: Swap = true;
5437 case ISD::SETUGT: SSECC = 6; break;
5438 case ISD::SETO: SSECC = 7; break;
5441 std::swap(Op0, Op1);
5443 // In the two special cases we can't handle, emit two comparisons.
5445 if (SetCCOpcode == ISD::SETUEQ) {
5447 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5448 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5449 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5451 else if (SetCCOpcode == ISD::SETONE) {
5453 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5454 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5455 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5457 llvm_unreachable("Illegal FP comparison");
5459 // Handle all other FP comparisons here.
5460 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5463 // We are handling one of the integer comparisons here. Since SSE only has
5464 // GT and EQ comparisons for integer, swapping operands and multiple
5465 // operations may be required for some comparisons.
5466 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5467 bool Swap = false, Invert = false, FlipSigns = false;
5469 switch (VT.getSimpleVT()) {
5472 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5474 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5476 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5477 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5480 switch (SetCCOpcode) {
5482 case ISD::SETNE: Invert = true;
5483 case ISD::SETEQ: Opc = EQOpc; break;
5484 case ISD::SETLT: Swap = true;
5485 case ISD::SETGT: Opc = GTOpc; break;
5486 case ISD::SETGE: Swap = true;
5487 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5488 case ISD::SETULT: Swap = true;
5489 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5490 case ISD::SETUGE: Swap = true;
5491 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5494 std::swap(Op0, Op1);
5496 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5497 // bits of the inputs before performing those operations.
5499 MVT EltVT = VT.getVectorElementType();
5500 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5502 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5503 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5505 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5506 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5509 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5511 // If the logical-not of the result is required, perform that now.
5513 Result = DAG.getNOT(dl, Result, VT);
5518 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5519 static bool isX86LogicalCmp(SDValue Op) {
5520 unsigned Opc = Op.getNode()->getOpcode();
5521 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5523 if (Op.getResNo() == 1 &&
5524 (Opc == X86ISD::ADD ||
5525 Opc == X86ISD::SUB ||
5526 Opc == X86ISD::SMUL ||
5527 Opc == X86ISD::UMUL ||
5528 Opc == X86ISD::INC ||
5529 Opc == X86ISD::DEC))
5535 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5536 bool addTest = true;
5537 SDValue Cond = Op.getOperand(0);
5538 DebugLoc dl = Op.getDebugLoc();
5541 if (Cond.getOpcode() == ISD::SETCC)
5542 Cond = LowerSETCC(Cond, DAG);
5544 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5545 // setting operand in place of the X86ISD::SETCC.
5546 if (Cond.getOpcode() == X86ISD::SETCC) {
5547 CC = Cond.getOperand(0);
5549 SDValue Cmp = Cond.getOperand(1);
5550 unsigned Opc = Cmp.getOpcode();
5551 MVT VT = Op.getValueType();
5553 bool IllegalFPCMov = false;
5554 if (VT.isFloatingPoint() && !VT.isVector() &&
5555 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5556 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5558 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5559 Opc == X86ISD::BT) { // FIXME
5566 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5567 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5570 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5571 SmallVector<SDValue, 4> Ops;
5572 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5573 // condition is true.
5574 Ops.push_back(Op.getOperand(2));
5575 Ops.push_back(Op.getOperand(1));
5577 Ops.push_back(Cond);
5578 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5581 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5582 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5583 // from the AND / OR.
5584 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5585 Opc = Op.getOpcode();
5586 if (Opc != ISD::OR && Opc != ISD::AND)
5588 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5589 Op.getOperand(0).hasOneUse() &&
5590 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5591 Op.getOperand(1).hasOneUse());
5594 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5595 // 1 and that the SETCC node has a single use.
5596 static bool isXor1OfSetCC(SDValue Op) {
5597 if (Op.getOpcode() != ISD::XOR)
5599 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5600 if (N1C && N1C->getAPIntValue() == 1) {
5601 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5602 Op.getOperand(0).hasOneUse();
5607 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5608 bool addTest = true;
5609 SDValue Chain = Op.getOperand(0);
5610 SDValue Cond = Op.getOperand(1);
5611 SDValue Dest = Op.getOperand(2);
5612 DebugLoc dl = Op.getDebugLoc();
5615 if (Cond.getOpcode() == ISD::SETCC)
5616 Cond = LowerSETCC(Cond, DAG);
5618 // FIXME: LowerXALUO doesn't handle these!!
5619 else if (Cond.getOpcode() == X86ISD::ADD ||
5620 Cond.getOpcode() == X86ISD::SUB ||
5621 Cond.getOpcode() == X86ISD::SMUL ||
5622 Cond.getOpcode() == X86ISD::UMUL)
5623 Cond = LowerXALUO(Cond, DAG);
5626 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5627 // setting operand in place of the X86ISD::SETCC.
5628 if (Cond.getOpcode() == X86ISD::SETCC) {
5629 CC = Cond.getOperand(0);
5631 SDValue Cmp = Cond.getOperand(1);
5632 unsigned Opc = Cmp.getOpcode();
5633 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5634 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5638 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5642 // These can only come from an arithmetic instruction with overflow,
5643 // e.g. SADDO, UADDO.
5644 Cond = Cond.getNode()->getOperand(1);
5651 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5652 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5653 if (CondOpc == ISD::OR) {
5654 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5655 // two branches instead of an explicit OR instruction with a
5657 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5658 isX86LogicalCmp(Cmp)) {
5659 CC = Cond.getOperand(0).getOperand(0);
5660 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5661 Chain, Dest, CC, Cmp);
5662 CC = Cond.getOperand(1).getOperand(0);
5666 } else { // ISD::AND
5667 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5668 // two branches instead of an explicit AND instruction with a
5669 // separate test. However, we only do this if this block doesn't
5670 // have a fall-through edge, because this requires an explicit
5671 // jmp when the condition is false.
5672 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5673 isX86LogicalCmp(Cmp) &&
5674 Op.getNode()->hasOneUse()) {
5675 X86::CondCode CCode =
5676 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5677 CCode = X86::GetOppositeBranchCondition(CCode);
5678 CC = DAG.getConstant(CCode, MVT::i8);
5679 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5680 // Look for an unconditional branch following this conditional branch.
5681 // We need this because we need to reverse the successors in order
5682 // to implement FCMP_OEQ.
5683 if (User.getOpcode() == ISD::BR) {
5684 SDValue FalseBB = User.getOperand(1);
5686 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5687 assert(NewBR == User);
5690 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5691 Chain, Dest, CC, Cmp);
5692 X86::CondCode CCode =
5693 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5694 CCode = X86::GetOppositeBranchCondition(CCode);
5695 CC = DAG.getConstant(CCode, MVT::i8);
5701 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5702 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5703 // It should be transformed during dag combiner except when the condition
5704 // is set by a arithmetics with overflow node.
5705 X86::CondCode CCode =
5706 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5707 CCode = X86::GetOppositeBranchCondition(CCode);
5708 CC = DAG.getConstant(CCode, MVT::i8);
5709 Cond = Cond.getOperand(0).getOperand(1);
5715 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5716 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5718 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5719 Chain, Dest, CC, Cond);
5723 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5724 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5725 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5726 // that the guard pages used by the OS virtual memory manager are allocated in
5727 // correct sequence.
5729 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5730 SelectionDAG &DAG) {
5731 assert(Subtarget->isTargetCygMing() &&
5732 "This should be used only on Cygwin/Mingw targets");
5733 DebugLoc dl = Op.getDebugLoc();
5736 SDValue Chain = Op.getOperand(0);
5737 SDValue Size = Op.getOperand(1);
5738 // FIXME: Ensure alignment here
5742 MVT IntPtr = getPointerTy();
5743 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5745 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5747 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5748 Flag = Chain.getValue(1);
5750 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5751 SDValue Ops[] = { Chain,
5752 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5753 DAG.getRegister(X86::EAX, IntPtr),
5754 DAG.getRegister(X86StackPtr, SPTy),
5756 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5757 Flag = Chain.getValue(1);
5759 Chain = DAG.getCALLSEQ_END(Chain,
5760 DAG.getIntPtrConstant(0, true),
5761 DAG.getIntPtrConstant(0, true),
5764 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5766 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5767 return DAG.getMergeValues(Ops1, 2, dl);
5771 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5773 SDValue Dst, SDValue Src,
5774 SDValue Size, unsigned Align,
5776 uint64_t DstSVOff) {
5777 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5779 // If not DWORD aligned or size is more than the threshold, call the library.
5780 // The libc version is likely to be faster for these cases. It can use the
5781 // address value and run time information about the CPU.
5782 if ((Align & 3) != 0 ||
5784 ConstantSize->getZExtValue() >
5785 getSubtarget()->getMaxInlineSizeThreshold()) {
5786 SDValue InFlag(0, 0);
5788 // Check to see if there is a specialized entry-point for memory zeroing.
5789 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5791 if (const char *bzeroEntry = V &&
5792 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5793 MVT IntPtr = getPointerTy();
5794 const Type *IntPtrTy = TD->getIntPtrType();
5795 TargetLowering::ArgListTy Args;
5796 TargetLowering::ArgListEntry Entry;
5798 Entry.Ty = IntPtrTy;
5799 Args.push_back(Entry);
5801 Args.push_back(Entry);
5802 std::pair<SDValue,SDValue> CallResult =
5803 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5804 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
5805 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5806 return CallResult.second;
5809 // Otherwise have the target-independent code call memset.
5813 uint64_t SizeVal = ConstantSize->getZExtValue();
5814 SDValue InFlag(0, 0);
5817 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5818 unsigned BytesLeft = 0;
5819 bool TwoRepStos = false;
5822 uint64_t Val = ValC->getZExtValue() & 255;
5824 // If the value is a constant, then we can potentially use larger sets.
5825 switch (Align & 3) {
5826 case 2: // WORD aligned
5829 Val = (Val << 8) | Val;
5831 case 0: // DWORD aligned
5834 Val = (Val << 8) | Val;
5835 Val = (Val << 16) | Val;
5836 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5839 Val = (Val << 32) | Val;
5842 default: // Byte aligned
5845 Count = DAG.getIntPtrConstant(SizeVal);
5849 if (AVT.bitsGT(MVT::i8)) {
5850 unsigned UBytes = AVT.getSizeInBits() / 8;
5851 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5852 BytesLeft = SizeVal % UBytes;
5855 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5857 InFlag = Chain.getValue(1);
5860 Count = DAG.getIntPtrConstant(SizeVal);
5861 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5862 InFlag = Chain.getValue(1);
5865 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5868 InFlag = Chain.getValue(1);
5869 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5872 InFlag = Chain.getValue(1);
5874 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5875 SmallVector<SDValue, 8> Ops;
5876 Ops.push_back(Chain);
5877 Ops.push_back(DAG.getValueType(AVT));
5878 Ops.push_back(InFlag);
5879 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5882 InFlag = Chain.getValue(1);
5884 MVT CVT = Count.getValueType();
5885 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5886 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5887 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5890 InFlag = Chain.getValue(1);
5891 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5893 Ops.push_back(Chain);
5894 Ops.push_back(DAG.getValueType(MVT::i8));
5895 Ops.push_back(InFlag);
5896 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5897 } else if (BytesLeft) {
5898 // Handle the last 1 - 7 bytes.
5899 unsigned Offset = SizeVal - BytesLeft;
5900 MVT AddrVT = Dst.getValueType();
5901 MVT SizeVT = Size.getValueType();
5903 Chain = DAG.getMemset(Chain, dl,
5904 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5905 DAG.getConstant(Offset, AddrVT)),
5907 DAG.getConstant(BytesLeft, SizeVT),
5908 Align, DstSV, DstSVOff + Offset);
5911 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5916 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5917 SDValue Chain, SDValue Dst, SDValue Src,
5918 SDValue Size, unsigned Align,
5920 const Value *DstSV, uint64_t DstSVOff,
5921 const Value *SrcSV, uint64_t SrcSVOff) {
5922 // This requires the copy size to be a constant, preferrably
5923 // within a subtarget-specific limit.
5924 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5927 uint64_t SizeVal = ConstantSize->getZExtValue();
5928 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5931 /// If not DWORD aligned, call the library.
5932 if ((Align & 3) != 0)
5937 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5940 unsigned UBytes = AVT.getSizeInBits() / 8;
5941 unsigned CountVal = SizeVal / UBytes;
5942 SDValue Count = DAG.getIntPtrConstant(CountVal);
5943 unsigned BytesLeft = SizeVal % UBytes;
5945 SDValue InFlag(0, 0);
5946 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5949 InFlag = Chain.getValue(1);
5950 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5953 InFlag = Chain.getValue(1);
5954 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5957 InFlag = Chain.getValue(1);
5959 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5960 SmallVector<SDValue, 8> Ops;
5961 Ops.push_back(Chain);
5962 Ops.push_back(DAG.getValueType(AVT));
5963 Ops.push_back(InFlag);
5964 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5966 SmallVector<SDValue, 4> Results;
5967 Results.push_back(RepMovs);
5969 // Handle the last 1 - 7 bytes.
5970 unsigned Offset = SizeVal - BytesLeft;
5971 MVT DstVT = Dst.getValueType();
5972 MVT SrcVT = Src.getValueType();
5973 MVT SizeVT = Size.getValueType();
5974 Results.push_back(DAG.getMemcpy(Chain, dl,
5975 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5976 DAG.getConstant(Offset, DstVT)),
5977 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5978 DAG.getConstant(Offset, SrcVT)),
5979 DAG.getConstant(BytesLeft, SizeVT),
5980 Align, AlwaysInline,
5981 DstSV, DstSVOff + Offset,
5982 SrcSV, SrcSVOff + Offset));
5985 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5986 &Results[0], Results.size());
5989 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5990 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5991 DebugLoc dl = Op.getDebugLoc();
5993 if (!Subtarget->is64Bit()) {
5994 // vastart just stores the address of the VarArgsFrameIndex slot into the
5995 // memory location argument.
5996 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5997 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6001 // gp_offset (0 - 6 * 8)
6002 // fp_offset (48 - 48 + 8 * 16)
6003 // overflow_arg_area (point to parameters coming in memory).
6005 SmallVector<SDValue, 8> MemOps;
6006 SDValue FIN = Op.getOperand(1);
6008 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6009 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6011 MemOps.push_back(Store);
6014 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6015 FIN, DAG.getIntPtrConstant(4));
6016 Store = DAG.getStore(Op.getOperand(0), dl,
6017 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6019 MemOps.push_back(Store);
6021 // Store ptr to overflow_arg_area
6022 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6023 FIN, DAG.getIntPtrConstant(4));
6024 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6025 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6026 MemOps.push_back(Store);
6028 // Store ptr to reg_save_area.
6029 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6030 FIN, DAG.getIntPtrConstant(8));
6031 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6032 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6033 MemOps.push_back(Store);
6034 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6035 &MemOps[0], MemOps.size());
6038 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6039 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6040 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6041 SDValue Chain = Op.getOperand(0);
6042 SDValue SrcPtr = Op.getOperand(1);
6043 SDValue SrcSV = Op.getOperand(2);
6045 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6049 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6050 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6051 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6052 SDValue Chain = Op.getOperand(0);
6053 SDValue DstPtr = Op.getOperand(1);
6054 SDValue SrcPtr = Op.getOperand(2);
6055 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6056 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6057 DebugLoc dl = Op.getDebugLoc();
6059 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6060 DAG.getIntPtrConstant(24), 8, false,
6061 DstSV, 0, SrcSV, 0);
6065 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6066 DebugLoc dl = Op.getDebugLoc();
6067 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6069 default: return SDValue(); // Don't custom lower most intrinsics.
6070 // Comparison intrinsics.
6071 case Intrinsic::x86_sse_comieq_ss:
6072 case Intrinsic::x86_sse_comilt_ss:
6073 case Intrinsic::x86_sse_comile_ss:
6074 case Intrinsic::x86_sse_comigt_ss:
6075 case Intrinsic::x86_sse_comige_ss:
6076 case Intrinsic::x86_sse_comineq_ss:
6077 case Intrinsic::x86_sse_ucomieq_ss:
6078 case Intrinsic::x86_sse_ucomilt_ss:
6079 case Intrinsic::x86_sse_ucomile_ss:
6080 case Intrinsic::x86_sse_ucomigt_ss:
6081 case Intrinsic::x86_sse_ucomige_ss:
6082 case Intrinsic::x86_sse_ucomineq_ss:
6083 case Intrinsic::x86_sse2_comieq_sd:
6084 case Intrinsic::x86_sse2_comilt_sd:
6085 case Intrinsic::x86_sse2_comile_sd:
6086 case Intrinsic::x86_sse2_comigt_sd:
6087 case Intrinsic::x86_sse2_comige_sd:
6088 case Intrinsic::x86_sse2_comineq_sd:
6089 case Intrinsic::x86_sse2_ucomieq_sd:
6090 case Intrinsic::x86_sse2_ucomilt_sd:
6091 case Intrinsic::x86_sse2_ucomile_sd:
6092 case Intrinsic::x86_sse2_ucomigt_sd:
6093 case Intrinsic::x86_sse2_ucomige_sd:
6094 case Intrinsic::x86_sse2_ucomineq_sd: {
6096 ISD::CondCode CC = ISD::SETCC_INVALID;
6099 case Intrinsic::x86_sse_comieq_ss:
6100 case Intrinsic::x86_sse2_comieq_sd:
6104 case Intrinsic::x86_sse_comilt_ss:
6105 case Intrinsic::x86_sse2_comilt_sd:
6109 case Intrinsic::x86_sse_comile_ss:
6110 case Intrinsic::x86_sse2_comile_sd:
6114 case Intrinsic::x86_sse_comigt_ss:
6115 case Intrinsic::x86_sse2_comigt_sd:
6119 case Intrinsic::x86_sse_comige_ss:
6120 case Intrinsic::x86_sse2_comige_sd:
6124 case Intrinsic::x86_sse_comineq_ss:
6125 case Intrinsic::x86_sse2_comineq_sd:
6129 case Intrinsic::x86_sse_ucomieq_ss:
6130 case Intrinsic::x86_sse2_ucomieq_sd:
6131 Opc = X86ISD::UCOMI;
6134 case Intrinsic::x86_sse_ucomilt_ss:
6135 case Intrinsic::x86_sse2_ucomilt_sd:
6136 Opc = X86ISD::UCOMI;
6139 case Intrinsic::x86_sse_ucomile_ss:
6140 case Intrinsic::x86_sse2_ucomile_sd:
6141 Opc = X86ISD::UCOMI;
6144 case Intrinsic::x86_sse_ucomigt_ss:
6145 case Intrinsic::x86_sse2_ucomigt_sd:
6146 Opc = X86ISD::UCOMI;
6149 case Intrinsic::x86_sse_ucomige_ss:
6150 case Intrinsic::x86_sse2_ucomige_sd:
6151 Opc = X86ISD::UCOMI;
6154 case Intrinsic::x86_sse_ucomineq_ss:
6155 case Intrinsic::x86_sse2_ucomineq_sd:
6156 Opc = X86ISD::UCOMI;
6161 SDValue LHS = Op.getOperand(1);
6162 SDValue RHS = Op.getOperand(2);
6163 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6164 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6165 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6166 DAG.getConstant(X86CC, MVT::i8), Cond);
6167 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6169 // ptest intrinsics. The intrinsic these come from are designed to return
6170 // an integer value, not just an instruction so lower it to the ptest
6171 // pattern and a setcc for the result.
6172 case Intrinsic::x86_sse41_ptestz:
6173 case Intrinsic::x86_sse41_ptestc:
6174 case Intrinsic::x86_sse41_ptestnzc:{
6177 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6178 case Intrinsic::x86_sse41_ptestz:
6180 X86CC = X86::COND_E;
6182 case Intrinsic::x86_sse41_ptestc:
6184 X86CC = X86::COND_B;
6186 case Intrinsic::x86_sse41_ptestnzc:
6188 X86CC = X86::COND_A;
6192 SDValue LHS = Op.getOperand(1);
6193 SDValue RHS = Op.getOperand(2);
6194 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6195 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6196 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6197 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6200 // Fix vector shift instructions where the last operand is a non-immediate
6202 case Intrinsic::x86_sse2_pslli_w:
6203 case Intrinsic::x86_sse2_pslli_d:
6204 case Intrinsic::x86_sse2_pslli_q:
6205 case Intrinsic::x86_sse2_psrli_w:
6206 case Intrinsic::x86_sse2_psrli_d:
6207 case Intrinsic::x86_sse2_psrli_q:
6208 case Intrinsic::x86_sse2_psrai_w:
6209 case Intrinsic::x86_sse2_psrai_d:
6210 case Intrinsic::x86_mmx_pslli_w:
6211 case Intrinsic::x86_mmx_pslli_d:
6212 case Intrinsic::x86_mmx_pslli_q:
6213 case Intrinsic::x86_mmx_psrli_w:
6214 case Intrinsic::x86_mmx_psrli_d:
6215 case Intrinsic::x86_mmx_psrli_q:
6216 case Intrinsic::x86_mmx_psrai_w:
6217 case Intrinsic::x86_mmx_psrai_d: {
6218 SDValue ShAmt = Op.getOperand(2);
6219 if (isa<ConstantSDNode>(ShAmt))
6222 unsigned NewIntNo = 0;
6223 MVT ShAmtVT = MVT::v4i32;
6225 case Intrinsic::x86_sse2_pslli_w:
6226 NewIntNo = Intrinsic::x86_sse2_psll_w;
6228 case Intrinsic::x86_sse2_pslli_d:
6229 NewIntNo = Intrinsic::x86_sse2_psll_d;
6231 case Intrinsic::x86_sse2_pslli_q:
6232 NewIntNo = Intrinsic::x86_sse2_psll_q;
6234 case Intrinsic::x86_sse2_psrli_w:
6235 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6237 case Intrinsic::x86_sse2_psrli_d:
6238 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6240 case Intrinsic::x86_sse2_psrli_q:
6241 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6243 case Intrinsic::x86_sse2_psrai_w:
6244 NewIntNo = Intrinsic::x86_sse2_psra_w;
6246 case Intrinsic::x86_sse2_psrai_d:
6247 NewIntNo = Intrinsic::x86_sse2_psra_d;
6250 ShAmtVT = MVT::v2i32;
6252 case Intrinsic::x86_mmx_pslli_w:
6253 NewIntNo = Intrinsic::x86_mmx_psll_w;
6255 case Intrinsic::x86_mmx_pslli_d:
6256 NewIntNo = Intrinsic::x86_mmx_psll_d;
6258 case Intrinsic::x86_mmx_pslli_q:
6259 NewIntNo = Intrinsic::x86_mmx_psll_q;
6261 case Intrinsic::x86_mmx_psrli_w:
6262 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6264 case Intrinsic::x86_mmx_psrli_d:
6265 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6267 case Intrinsic::x86_mmx_psrli_q:
6268 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6270 case Intrinsic::x86_mmx_psrai_w:
6271 NewIntNo = Intrinsic::x86_mmx_psra_w;
6273 case Intrinsic::x86_mmx_psrai_d:
6274 NewIntNo = Intrinsic::x86_mmx_psra_d;
6276 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6281 MVT VT = Op.getValueType();
6282 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6283 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6284 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6285 DAG.getConstant(NewIntNo, MVT::i32),
6286 Op.getOperand(1), ShAmt);
6291 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6292 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6293 DebugLoc dl = Op.getDebugLoc();
6296 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6298 DAG.getConstant(TD->getPointerSize(),
6299 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6300 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6301 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6306 // Just load the return address.
6307 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6308 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6309 RetAddrFI, NULL, 0);
6312 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6313 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6314 MFI->setFrameAddressIsTaken(true);
6315 MVT VT = Op.getValueType();
6316 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6317 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6318 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6319 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6321 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6325 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6326 SelectionDAG &DAG) {
6327 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6330 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6332 MachineFunction &MF = DAG.getMachineFunction();
6333 SDValue Chain = Op.getOperand(0);
6334 SDValue Offset = Op.getOperand(1);
6335 SDValue Handler = Op.getOperand(2);
6336 DebugLoc dl = Op.getDebugLoc();
6338 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6340 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6342 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6343 DAG.getIntPtrConstant(-TD->getPointerSize()));
6344 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6345 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6346 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6347 MF.getRegInfo().addLiveOut(StoreAddrReg);
6349 return DAG.getNode(X86ISD::EH_RETURN, dl,
6351 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6354 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6355 SelectionDAG &DAG) {
6356 SDValue Root = Op.getOperand(0);
6357 SDValue Trmp = Op.getOperand(1); // trampoline
6358 SDValue FPtr = Op.getOperand(2); // nested function
6359 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6360 DebugLoc dl = Op.getDebugLoc();
6362 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6364 const X86InstrInfo *TII =
6365 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6367 if (Subtarget->is64Bit()) {
6368 SDValue OutChains[6];
6370 // Large code-model.
6372 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6373 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6375 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6376 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6378 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6380 // Load the pointer to the nested function into R11.
6381 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6382 SDValue Addr = Trmp;
6383 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6386 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6387 DAG.getConstant(2, MVT::i64));
6388 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6390 // Load the 'nest' parameter value into R10.
6391 // R10 is specified in X86CallingConv.td
6392 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6393 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6394 DAG.getConstant(10, MVT::i64));
6395 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6396 Addr, TrmpAddr, 10);
6398 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6399 DAG.getConstant(12, MVT::i64));
6400 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6402 // Jump to the nested function.
6403 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6404 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6405 DAG.getConstant(20, MVT::i64));
6406 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6407 Addr, TrmpAddr, 20);
6409 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6410 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6411 DAG.getConstant(22, MVT::i64));
6412 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6416 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6417 return DAG.getMergeValues(Ops, 2, dl);
6419 const Function *Func =
6420 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6421 unsigned CC = Func->getCallingConv();
6426 llvm_unreachable("Unsupported calling convention");
6427 case CallingConv::C:
6428 case CallingConv::X86_StdCall: {
6429 // Pass 'nest' parameter in ECX.
6430 // Must be kept in sync with X86CallingConv.td
6433 // Check that ECX wasn't needed by an 'inreg' parameter.
6434 const FunctionType *FTy = Func->getFunctionType();
6435 const AttrListPtr &Attrs = Func->getAttributes();
6437 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6438 unsigned InRegCount = 0;
6441 for (FunctionType::param_iterator I = FTy->param_begin(),
6442 E = FTy->param_end(); I != E; ++I, ++Idx)
6443 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6444 // FIXME: should only count parameters that are lowered to integers.
6445 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6447 if (InRegCount > 2) {
6448 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6453 case CallingConv::X86_FastCall:
6454 case CallingConv::Fast:
6455 // Pass 'nest' parameter in EAX.
6456 // Must be kept in sync with X86CallingConv.td
6461 SDValue OutChains[4];
6464 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6465 DAG.getConstant(10, MVT::i32));
6466 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6468 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6469 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6470 OutChains[0] = DAG.getStore(Root, dl,
6471 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6474 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6475 DAG.getConstant(1, MVT::i32));
6476 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6478 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6479 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6480 DAG.getConstant(5, MVT::i32));
6481 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6482 TrmpAddr, 5, false, 1);
6484 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6485 DAG.getConstant(6, MVT::i32));
6486 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6489 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6490 return DAG.getMergeValues(Ops, 2, dl);
6494 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6496 The rounding mode is in bits 11:10 of FPSR, and has the following
6503 FLT_ROUNDS, on the other hand, expects the following:
6510 To perform the conversion, we do:
6511 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6514 MachineFunction &MF = DAG.getMachineFunction();
6515 const TargetMachine &TM = MF.getTarget();
6516 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6517 unsigned StackAlignment = TFI.getStackAlignment();
6518 MVT VT = Op.getValueType();
6519 DebugLoc dl = Op.getDebugLoc();
6521 // Save FP Control Word to stack slot
6522 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6523 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6525 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6526 DAG.getEntryNode(), StackSlot);
6528 // Load FP Control Word from stack slot
6529 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6531 // Transform as necessary
6533 DAG.getNode(ISD::SRL, dl, MVT::i16,
6534 DAG.getNode(ISD::AND, dl, MVT::i16,
6535 CWD, DAG.getConstant(0x800, MVT::i16)),
6536 DAG.getConstant(11, MVT::i8));
6538 DAG.getNode(ISD::SRL, dl, MVT::i16,
6539 DAG.getNode(ISD::AND, dl, MVT::i16,
6540 CWD, DAG.getConstant(0x400, MVT::i16)),
6541 DAG.getConstant(9, MVT::i8));
6544 DAG.getNode(ISD::AND, dl, MVT::i16,
6545 DAG.getNode(ISD::ADD, dl, MVT::i16,
6546 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6547 DAG.getConstant(1, MVT::i16)),
6548 DAG.getConstant(3, MVT::i16));
6551 return DAG.getNode((VT.getSizeInBits() < 16 ?
6552 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6555 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6556 MVT VT = Op.getValueType();
6558 unsigned NumBits = VT.getSizeInBits();
6559 DebugLoc dl = Op.getDebugLoc();
6561 Op = Op.getOperand(0);
6562 if (VT == MVT::i8) {
6563 // Zero extend to i32 since there is not an i8 bsr.
6565 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6568 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6569 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6570 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6572 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6573 SmallVector<SDValue, 4> Ops;
6575 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6576 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6577 Ops.push_back(Op.getValue(1));
6578 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6580 // Finally xor with NumBits-1.
6581 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6584 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6588 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6589 MVT VT = Op.getValueType();
6591 unsigned NumBits = VT.getSizeInBits();
6592 DebugLoc dl = Op.getDebugLoc();
6594 Op = Op.getOperand(0);
6595 if (VT == MVT::i8) {
6597 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6600 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6601 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6602 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6604 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6605 SmallVector<SDValue, 4> Ops;
6607 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6608 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6609 Ops.push_back(Op.getValue(1));
6610 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6613 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6617 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6618 MVT VT = Op.getValueType();
6619 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6620 DebugLoc dl = Op.getDebugLoc();
6622 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6623 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6624 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6625 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6626 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6628 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6629 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6630 // return AloBlo + AloBhi + AhiBlo;
6632 SDValue A = Op.getOperand(0);
6633 SDValue B = Op.getOperand(1);
6635 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6636 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6637 A, DAG.getConstant(32, MVT::i32));
6638 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6639 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6640 B, DAG.getConstant(32, MVT::i32));
6641 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6642 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6644 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6645 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6647 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6648 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6650 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6651 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6652 AloBhi, DAG.getConstant(32, MVT::i32));
6653 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6654 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6655 AhiBlo, DAG.getConstant(32, MVT::i32));
6656 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6657 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6662 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6663 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6664 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6665 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6666 // has only one use.
6667 SDNode *N = Op.getNode();
6668 SDValue LHS = N->getOperand(0);
6669 SDValue RHS = N->getOperand(1);
6670 unsigned BaseOp = 0;
6672 DebugLoc dl = Op.getDebugLoc();
6674 switch (Op.getOpcode()) {
6675 default: llvm_unreachable("Unknown ovf instruction!");
6677 // A subtract of one will be selected as a INC. Note that INC doesn't
6678 // set CF, so we can't do this for UADDO.
6679 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6680 if (C->getAPIntValue() == 1) {
6681 BaseOp = X86ISD::INC;
6685 BaseOp = X86ISD::ADD;
6689 BaseOp = X86ISD::ADD;
6693 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6694 // set CF, so we can't do this for USUBO.
6695 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6696 if (C->getAPIntValue() == 1) {
6697 BaseOp = X86ISD::DEC;
6701 BaseOp = X86ISD::SUB;
6705 BaseOp = X86ISD::SUB;
6709 BaseOp = X86ISD::SMUL;
6713 BaseOp = X86ISD::UMUL;
6718 // Also sets EFLAGS.
6719 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6720 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6723 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6724 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6726 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6730 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6731 MVT T = Op.getValueType();
6732 DebugLoc dl = Op.getDebugLoc();
6735 switch(T.getSimpleVT()) {
6737 assert(false && "Invalid value type!");
6738 case MVT::i8: Reg = X86::AL; size = 1; break;
6739 case MVT::i16: Reg = X86::AX; size = 2; break;
6740 case MVT::i32: Reg = X86::EAX; size = 4; break;
6742 assert(Subtarget->is64Bit() && "Node not type legal!");
6743 Reg = X86::RAX; size = 8;
6746 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6747 Op.getOperand(2), SDValue());
6748 SDValue Ops[] = { cpIn.getValue(0),
6751 DAG.getTargetConstant(size, MVT::i8),
6753 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6754 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6756 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6760 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6761 SelectionDAG &DAG) {
6762 assert(Subtarget->is64Bit() && "Result not type legalized?");
6763 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6764 SDValue TheChain = Op.getOperand(0);
6765 DebugLoc dl = Op.getDebugLoc();
6766 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6767 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6768 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6770 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6771 DAG.getConstant(32, MVT::i8));
6773 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6776 return DAG.getMergeValues(Ops, 2, dl);
6779 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6780 SDNode *Node = Op.getNode();
6781 DebugLoc dl = Node->getDebugLoc();
6782 MVT T = Node->getValueType(0);
6783 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6784 DAG.getConstant(0, T), Node->getOperand(2));
6785 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6786 cast<AtomicSDNode>(Node)->getMemoryVT(),
6787 Node->getOperand(0),
6788 Node->getOperand(1), negOp,
6789 cast<AtomicSDNode>(Node)->getSrcValue(),
6790 cast<AtomicSDNode>(Node)->getAlignment());
6793 /// LowerOperation - Provide custom lowering hooks for some operations.
6795 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6796 switch (Op.getOpcode()) {
6797 default: llvm_unreachable("Should not custom lower this!");
6798 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6799 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6800 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6801 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6802 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6803 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6804 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6805 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6806 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6807 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6808 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6809 case ISD::SHL_PARTS:
6810 case ISD::SRA_PARTS:
6811 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6812 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6813 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6814 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6815 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6816 case ISD::FABS: return LowerFABS(Op, DAG);
6817 case ISD::FNEG: return LowerFNEG(Op, DAG);
6818 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6819 case ISD::SETCC: return LowerSETCC(Op, DAG);
6820 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6821 case ISD::SELECT: return LowerSELECT(Op, DAG);
6822 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6823 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6824 case ISD::VASTART: return LowerVASTART(Op, DAG);
6825 case ISD::VAARG: return LowerVAARG(Op, DAG);
6826 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6827 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6828 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6829 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6830 case ISD::FRAME_TO_ARGS_OFFSET:
6831 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6832 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6833 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6834 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6835 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6836 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6837 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6838 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6844 case ISD::UMULO: return LowerXALUO(Op, DAG);
6845 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6849 void X86TargetLowering::
6850 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6851 SelectionDAG &DAG, unsigned NewOp) {
6852 MVT T = Node->getValueType(0);
6853 DebugLoc dl = Node->getDebugLoc();
6854 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6856 SDValue Chain = Node->getOperand(0);
6857 SDValue In1 = Node->getOperand(1);
6858 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6859 Node->getOperand(2), DAG.getIntPtrConstant(0));
6860 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6861 Node->getOperand(2), DAG.getIntPtrConstant(1));
6862 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6863 // have a MemOperand. Pass the info through as a normal operand.
6864 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6865 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6866 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6867 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6868 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6869 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6870 Results.push_back(Result.getValue(2));
6873 /// ReplaceNodeResults - Replace a node with an illegal result type
6874 /// with a new node built out of custom code.
6875 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6876 SmallVectorImpl<SDValue>&Results,
6877 SelectionDAG &DAG) {
6878 DebugLoc dl = N->getDebugLoc();
6879 switch (N->getOpcode()) {
6881 assert(false && "Do not know how to custom type legalize this operation!");
6883 case ISD::FP_TO_SINT: {
6884 std::pair<SDValue,SDValue> Vals =
6885 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6886 SDValue FIST = Vals.first, StackSlot = Vals.second;
6887 if (FIST.getNode() != 0) {
6888 MVT VT = N->getValueType(0);
6889 // Return a load from the stack slot.
6890 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6894 case ISD::READCYCLECOUNTER: {
6895 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6896 SDValue TheChain = N->getOperand(0);
6897 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6898 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6900 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6902 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6903 SDValue Ops[] = { eax, edx };
6904 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6905 Results.push_back(edx.getValue(1));
6908 case ISD::ATOMIC_CMP_SWAP: {
6909 MVT T = N->getValueType(0);
6910 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6911 SDValue cpInL, cpInH;
6912 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6913 DAG.getConstant(0, MVT::i32));
6914 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6915 DAG.getConstant(1, MVT::i32));
6916 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6917 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6919 SDValue swapInL, swapInH;
6920 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6921 DAG.getConstant(0, MVT::i32));
6922 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6923 DAG.getConstant(1, MVT::i32));
6924 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6926 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6927 swapInL.getValue(1));
6928 SDValue Ops[] = { swapInH.getValue(0),
6930 swapInH.getValue(1) };
6931 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6932 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6933 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6934 MVT::i32, Result.getValue(1));
6935 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6936 MVT::i32, cpOutL.getValue(2));
6937 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6938 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6939 Results.push_back(cpOutH.getValue(1));
6942 case ISD::ATOMIC_LOAD_ADD:
6943 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6945 case ISD::ATOMIC_LOAD_AND:
6946 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6948 case ISD::ATOMIC_LOAD_NAND:
6949 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6951 case ISD::ATOMIC_LOAD_OR:
6952 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6954 case ISD::ATOMIC_LOAD_SUB:
6955 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6957 case ISD::ATOMIC_LOAD_XOR:
6958 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6960 case ISD::ATOMIC_SWAP:
6961 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6966 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6968 default: return NULL;
6969 case X86ISD::BSF: return "X86ISD::BSF";
6970 case X86ISD::BSR: return "X86ISD::BSR";
6971 case X86ISD::SHLD: return "X86ISD::SHLD";
6972 case X86ISD::SHRD: return "X86ISD::SHRD";
6973 case X86ISD::FAND: return "X86ISD::FAND";
6974 case X86ISD::FOR: return "X86ISD::FOR";
6975 case X86ISD::FXOR: return "X86ISD::FXOR";
6976 case X86ISD::FSRL: return "X86ISD::FSRL";
6977 case X86ISD::FILD: return "X86ISD::FILD";
6978 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6979 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6980 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6981 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6982 case X86ISD::FLD: return "X86ISD::FLD";
6983 case X86ISD::FST: return "X86ISD::FST";
6984 case X86ISD::CALL: return "X86ISD::CALL";
6985 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6986 case X86ISD::BT: return "X86ISD::BT";
6987 case X86ISD::CMP: return "X86ISD::CMP";
6988 case X86ISD::COMI: return "X86ISD::COMI";
6989 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6990 case X86ISD::SETCC: return "X86ISD::SETCC";
6991 case X86ISD::CMOV: return "X86ISD::CMOV";
6992 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6993 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6994 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6995 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6996 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6997 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6998 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
6999 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7000 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7001 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7002 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7003 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7004 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7005 case X86ISD::FMAX: return "X86ISD::FMAX";
7006 case X86ISD::FMIN: return "X86ISD::FMIN";
7007 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7008 case X86ISD::FRCP: return "X86ISD::FRCP";
7009 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7010 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7011 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7012 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7013 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7014 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7015 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7016 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7017 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7018 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7019 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7020 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7021 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7022 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7023 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7024 case X86ISD::VSHL: return "X86ISD::VSHL";
7025 case X86ISD::VSRL: return "X86ISD::VSRL";
7026 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7027 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7028 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7029 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7030 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7031 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7032 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7033 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7034 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7035 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7036 case X86ISD::ADD: return "X86ISD::ADD";
7037 case X86ISD::SUB: return "X86ISD::SUB";
7038 case X86ISD::SMUL: return "X86ISD::SMUL";
7039 case X86ISD::UMUL: return "X86ISD::UMUL";
7040 case X86ISD::INC: return "X86ISD::INC";
7041 case X86ISD::DEC: return "X86ISD::DEC";
7042 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7043 case X86ISD::PTEST: return "X86ISD::PTEST";
7047 // isLegalAddressingMode - Return true if the addressing mode represented
7048 // by AM is legal for this target, for a load/store of the specified type.
7049 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7050 const Type *Ty) const {
7051 // X86 supports extremely general addressing modes.
7053 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7054 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
7059 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7061 // If a reference to this global requires an extra load, we can't fold it.
7062 if (isGlobalStubReference(GVFlags))
7065 // If BaseGV requires a register for the PIC base, we cannot also have a
7066 // BaseReg specified.
7067 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7070 // X86-64 only supports addr of globals in small code model.
7071 if (Subtarget->is64Bit()) {
7072 if (getTargetMachine().getCodeModel() != CodeModel::Small)
7074 // If lower 4G is not available, then we must use rip-relative addressing.
7075 if (AM.BaseOffs || AM.Scale > 1)
7086 // These scales always work.
7091 // These scales are formed with basereg+scalereg. Only accept if there is
7096 default: // Other stuff never works.
7104 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7105 if (!Ty1->isInteger() || !Ty2->isInteger())
7107 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7108 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7109 if (NumBits1 <= NumBits2)
7111 return Subtarget->is64Bit() || NumBits1 < 64;
7114 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7115 if (!VT1.isInteger() || !VT2.isInteger())
7117 unsigned NumBits1 = VT1.getSizeInBits();
7118 unsigned NumBits2 = VT2.getSizeInBits();
7119 if (NumBits1 <= NumBits2)
7121 return Subtarget->is64Bit() || NumBits1 < 64;
7124 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7125 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7126 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
7129 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
7130 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7131 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7134 bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
7135 // i16 instructions are longer (0x66 prefix) and potentially slower.
7136 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7139 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7140 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7141 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7142 /// are assumed to be legal.
7144 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7146 // Only do shuffles on 128-bit vector types for now.
7147 if (VT.getSizeInBits() == 64)
7150 // FIXME: pshufb, blends, palignr, shifts.
7151 return (VT.getVectorNumElements() == 2 ||
7152 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7153 isMOVLMask(M, VT) ||
7154 isSHUFPMask(M, VT) ||
7155 isPSHUFDMask(M, VT) ||
7156 isPSHUFHWMask(M, VT) ||
7157 isPSHUFLWMask(M, VT) ||
7158 isUNPCKLMask(M, VT) ||
7159 isUNPCKHMask(M, VT) ||
7160 isUNPCKL_v_undef_Mask(M, VT) ||
7161 isUNPCKH_v_undef_Mask(M, VT));
7165 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7167 unsigned NumElts = VT.getVectorNumElements();
7168 // FIXME: This collection of masks seems suspect.
7171 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7172 return (isMOVLMask(Mask, VT) ||
7173 isCommutedMOVLMask(Mask, VT, true) ||
7174 isSHUFPMask(Mask, VT) ||
7175 isCommutedSHUFPMask(Mask, VT));
7180 //===----------------------------------------------------------------------===//
7181 // X86 Scheduler Hooks
7182 //===----------------------------------------------------------------------===//
7184 // private utility function
7186 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7187 MachineBasicBlock *MBB,
7195 TargetRegisterClass *RC,
7196 bool invSrc) const {
7197 // For the atomic bitwise operator, we generate
7200 // ld t1 = [bitinstr.addr]
7201 // op t2 = t1, [bitinstr.val]
7203 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7205 // fallthrough -->nextMBB
7206 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7207 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7208 MachineFunction::iterator MBBIter = MBB;
7211 /// First build the CFG
7212 MachineFunction *F = MBB->getParent();
7213 MachineBasicBlock *thisMBB = MBB;
7214 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7215 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7216 F->insert(MBBIter, newMBB);
7217 F->insert(MBBIter, nextMBB);
7219 // Move all successors to thisMBB to nextMBB
7220 nextMBB->transferSuccessors(thisMBB);
7222 // Update thisMBB to fall through to newMBB
7223 thisMBB->addSuccessor(newMBB);
7225 // newMBB jumps to itself and fall through to nextMBB
7226 newMBB->addSuccessor(nextMBB);
7227 newMBB->addSuccessor(newMBB);
7229 // Insert instructions into newMBB based on incoming instruction
7230 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7231 "unexpected number of operands");
7232 DebugLoc dl = bInstr->getDebugLoc();
7233 MachineOperand& destOper = bInstr->getOperand(0);
7234 MachineOperand* argOpers[2 + X86AddrNumOperands];
7235 int numArgs = bInstr->getNumOperands() - 1;
7236 for (int i=0; i < numArgs; ++i)
7237 argOpers[i] = &bInstr->getOperand(i+1);
7239 // x86 address has 4 operands: base, index, scale, and displacement
7240 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7241 int valArgIndx = lastAddrIndx + 1;
7243 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7244 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7245 for (int i=0; i <= lastAddrIndx; ++i)
7246 (*MIB).addOperand(*argOpers[i]);
7248 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7250 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7255 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7256 assert((argOpers[valArgIndx]->isReg() ||
7257 argOpers[valArgIndx]->isImm()) &&
7259 if (argOpers[valArgIndx]->isReg())
7260 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7262 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7264 (*MIB).addOperand(*argOpers[valArgIndx]);
7266 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7269 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7270 for (int i=0; i <= lastAddrIndx; ++i)
7271 (*MIB).addOperand(*argOpers[i]);
7273 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7274 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7276 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7280 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7282 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7286 // private utility function: 64 bit atomics on 32 bit host.
7288 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7289 MachineBasicBlock *MBB,
7294 bool invSrc) const {
7295 // For the atomic bitwise operator, we generate
7296 // thisMBB (instructions are in pairs, except cmpxchg8b)
7297 // ld t1,t2 = [bitinstr.addr]
7299 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7300 // op t5, t6 <- out1, out2, [bitinstr.val]
7301 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7302 // mov ECX, EBX <- t5, t6
7303 // mov EAX, EDX <- t1, t2
7304 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7305 // mov t3, t4 <- EAX, EDX
7307 // result in out1, out2
7308 // fallthrough -->nextMBB
7310 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7311 const unsigned LoadOpc = X86::MOV32rm;
7312 const unsigned copyOpc = X86::MOV32rr;
7313 const unsigned NotOpc = X86::NOT32r;
7314 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7315 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7316 MachineFunction::iterator MBBIter = MBB;
7319 /// First build the CFG
7320 MachineFunction *F = MBB->getParent();
7321 MachineBasicBlock *thisMBB = MBB;
7322 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7323 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7324 F->insert(MBBIter, newMBB);
7325 F->insert(MBBIter, nextMBB);
7327 // Move all successors to thisMBB to nextMBB
7328 nextMBB->transferSuccessors(thisMBB);
7330 // Update thisMBB to fall through to newMBB
7331 thisMBB->addSuccessor(newMBB);
7333 // newMBB jumps to itself and fall through to nextMBB
7334 newMBB->addSuccessor(nextMBB);
7335 newMBB->addSuccessor(newMBB);
7337 DebugLoc dl = bInstr->getDebugLoc();
7338 // Insert instructions into newMBB based on incoming instruction
7339 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7340 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7341 "unexpected number of operands");
7342 MachineOperand& dest1Oper = bInstr->getOperand(0);
7343 MachineOperand& dest2Oper = bInstr->getOperand(1);
7344 MachineOperand* argOpers[2 + X86AddrNumOperands];
7345 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7346 argOpers[i] = &bInstr->getOperand(i+2);
7348 // x86 address has 4 operands: base, index, scale, and displacement
7349 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7351 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7352 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7353 for (int i=0; i <= lastAddrIndx; ++i)
7354 (*MIB).addOperand(*argOpers[i]);
7355 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7356 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7357 // add 4 to displacement.
7358 for (int i=0; i <= lastAddrIndx-2; ++i)
7359 (*MIB).addOperand(*argOpers[i]);
7360 MachineOperand newOp3 = *(argOpers[3]);
7362 newOp3.setImm(newOp3.getImm()+4);
7364 newOp3.setOffset(newOp3.getOffset()+4);
7365 (*MIB).addOperand(newOp3);
7366 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7368 // t3/4 are defined later, at the bottom of the loop
7369 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7370 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7371 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7372 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7373 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7374 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7376 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7377 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7379 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7380 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7386 int valArgIndx = lastAddrIndx + 1;
7387 assert((argOpers[valArgIndx]->isReg() ||
7388 argOpers[valArgIndx]->isImm()) &&
7390 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7391 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7392 if (argOpers[valArgIndx]->isReg())
7393 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7395 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7396 if (regOpcL != X86::MOV32rr)
7398 (*MIB).addOperand(*argOpers[valArgIndx]);
7399 assert(argOpers[valArgIndx + 1]->isReg() ==
7400 argOpers[valArgIndx]->isReg());
7401 assert(argOpers[valArgIndx + 1]->isImm() ==
7402 argOpers[valArgIndx]->isImm());
7403 if (argOpers[valArgIndx + 1]->isReg())
7404 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7406 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7407 if (regOpcH != X86::MOV32rr)
7409 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7411 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7413 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7416 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7418 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7421 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7422 for (int i=0; i <= lastAddrIndx; ++i)
7423 (*MIB).addOperand(*argOpers[i]);
7425 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7426 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7428 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7429 MIB.addReg(X86::EAX);
7430 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7431 MIB.addReg(X86::EDX);
7434 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7436 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7440 // private utility function
7442 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7443 MachineBasicBlock *MBB,
7444 unsigned cmovOpc) const {
7445 // For the atomic min/max operator, we generate
7448 // ld t1 = [min/max.addr]
7449 // mov t2 = [min/max.val]
7451 // cmov[cond] t2 = t1
7453 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7455 // fallthrough -->nextMBB
7457 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7458 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7459 MachineFunction::iterator MBBIter = MBB;
7462 /// First build the CFG
7463 MachineFunction *F = MBB->getParent();
7464 MachineBasicBlock *thisMBB = MBB;
7465 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7466 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7467 F->insert(MBBIter, newMBB);
7468 F->insert(MBBIter, nextMBB);
7470 // Move all successors to thisMBB to nextMBB
7471 nextMBB->transferSuccessors(thisMBB);
7473 // Update thisMBB to fall through to newMBB
7474 thisMBB->addSuccessor(newMBB);
7476 // newMBB jumps to newMBB and fall through to nextMBB
7477 newMBB->addSuccessor(nextMBB);
7478 newMBB->addSuccessor(newMBB);
7480 DebugLoc dl = mInstr->getDebugLoc();
7481 // Insert instructions into newMBB based on incoming instruction
7482 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7483 "unexpected number of operands");
7484 MachineOperand& destOper = mInstr->getOperand(0);
7485 MachineOperand* argOpers[2 + X86AddrNumOperands];
7486 int numArgs = mInstr->getNumOperands() - 1;
7487 for (int i=0; i < numArgs; ++i)
7488 argOpers[i] = &mInstr->getOperand(i+1);
7490 // x86 address has 4 operands: base, index, scale, and displacement
7491 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7492 int valArgIndx = lastAddrIndx + 1;
7494 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7495 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7496 for (int i=0; i <= lastAddrIndx; ++i)
7497 (*MIB).addOperand(*argOpers[i]);
7499 // We only support register and immediate values
7500 assert((argOpers[valArgIndx]->isReg() ||
7501 argOpers[valArgIndx]->isImm()) &&
7504 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7505 if (argOpers[valArgIndx]->isReg())
7506 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7508 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7509 (*MIB).addOperand(*argOpers[valArgIndx]);
7511 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7514 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7519 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7520 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7524 // Cmp and exchange if none has modified the memory location
7525 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7526 for (int i=0; i <= lastAddrIndx; ++i)
7527 (*MIB).addOperand(*argOpers[i]);
7529 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7530 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7532 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7533 MIB.addReg(X86::EAX);
7536 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7538 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7544 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7545 MachineBasicBlock *BB) const {
7546 DebugLoc dl = MI->getDebugLoc();
7547 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7548 switch (MI->getOpcode()) {
7549 default: assert(false && "Unexpected instr type to insert");
7550 case X86::CMOV_V1I64:
7551 case X86::CMOV_FR32:
7552 case X86::CMOV_FR64:
7553 case X86::CMOV_V4F32:
7554 case X86::CMOV_V2F64:
7555 case X86::CMOV_V2I64: {
7556 // To "insert" a SELECT_CC instruction, we actually have to insert the
7557 // diamond control-flow pattern. The incoming instruction knows the
7558 // destination vreg to set, the condition code register to branch on, the
7559 // true/false values to select between, and a branch opcode to use.
7560 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7561 MachineFunction::iterator It = BB;
7567 // cmpTY ccX, r1, r2
7569 // fallthrough --> copy0MBB
7570 MachineBasicBlock *thisMBB = BB;
7571 MachineFunction *F = BB->getParent();
7572 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7573 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7575 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7576 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7577 F->insert(It, copy0MBB);
7578 F->insert(It, sinkMBB);
7579 // Update machine-CFG edges by transferring all successors of the current
7580 // block to the new block which will contain the Phi node for the select.
7581 sinkMBB->transferSuccessors(BB);
7583 // Add the true and fallthrough blocks as its successors.
7584 BB->addSuccessor(copy0MBB);
7585 BB->addSuccessor(sinkMBB);
7588 // %FalseValue = ...
7589 // # fallthrough to sinkMBB
7592 // Update machine-CFG edges
7593 BB->addSuccessor(sinkMBB);
7596 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7599 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7600 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7601 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7603 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7607 case X86::FP32_TO_INT16_IN_MEM:
7608 case X86::FP32_TO_INT32_IN_MEM:
7609 case X86::FP32_TO_INT64_IN_MEM:
7610 case X86::FP64_TO_INT16_IN_MEM:
7611 case X86::FP64_TO_INT32_IN_MEM:
7612 case X86::FP64_TO_INT64_IN_MEM:
7613 case X86::FP80_TO_INT16_IN_MEM:
7614 case X86::FP80_TO_INT32_IN_MEM:
7615 case X86::FP80_TO_INT64_IN_MEM: {
7616 // Change the floating point control register to use "round towards zero"
7617 // mode when truncating to an integer value.
7618 MachineFunction *F = BB->getParent();
7619 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7620 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7622 // Load the old value of the high byte of the control word...
7624 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7625 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7628 // Set the high part to be round to zero...
7629 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7632 // Reload the modified control word now...
7633 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7635 // Restore the memory image of control word to original value
7636 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7639 // Get the X86 opcode to use.
7641 switch (MI->getOpcode()) {
7642 default: llvm_unreachable("illegal opcode!");
7643 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7644 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7645 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7646 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7647 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7648 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7649 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7650 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7651 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7655 MachineOperand &Op = MI->getOperand(0);
7657 AM.BaseType = X86AddressMode::RegBase;
7658 AM.Base.Reg = Op.getReg();
7660 AM.BaseType = X86AddressMode::FrameIndexBase;
7661 AM.Base.FrameIndex = Op.getIndex();
7663 Op = MI->getOperand(1);
7665 AM.Scale = Op.getImm();
7666 Op = MI->getOperand(2);
7668 AM.IndexReg = Op.getImm();
7669 Op = MI->getOperand(3);
7670 if (Op.isGlobal()) {
7671 AM.GV = Op.getGlobal();
7673 AM.Disp = Op.getImm();
7675 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7676 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7678 // Reload the original control word now.
7679 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7681 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7684 case X86::ATOMAND32:
7685 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7686 X86::AND32ri, X86::MOV32rm,
7687 X86::LCMPXCHG32, X86::MOV32rr,
7688 X86::NOT32r, X86::EAX,
7689 X86::GR32RegisterClass);
7691 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7692 X86::OR32ri, X86::MOV32rm,
7693 X86::LCMPXCHG32, X86::MOV32rr,
7694 X86::NOT32r, X86::EAX,
7695 X86::GR32RegisterClass);
7696 case X86::ATOMXOR32:
7697 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7698 X86::XOR32ri, X86::MOV32rm,
7699 X86::LCMPXCHG32, X86::MOV32rr,
7700 X86::NOT32r, X86::EAX,
7701 X86::GR32RegisterClass);
7702 case X86::ATOMNAND32:
7703 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7704 X86::AND32ri, X86::MOV32rm,
7705 X86::LCMPXCHG32, X86::MOV32rr,
7706 X86::NOT32r, X86::EAX,
7707 X86::GR32RegisterClass, true);
7708 case X86::ATOMMIN32:
7709 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7710 case X86::ATOMMAX32:
7711 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7712 case X86::ATOMUMIN32:
7713 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7714 case X86::ATOMUMAX32:
7715 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7717 case X86::ATOMAND16:
7718 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7719 X86::AND16ri, X86::MOV16rm,
7720 X86::LCMPXCHG16, X86::MOV16rr,
7721 X86::NOT16r, X86::AX,
7722 X86::GR16RegisterClass);
7724 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7725 X86::OR16ri, X86::MOV16rm,
7726 X86::LCMPXCHG16, X86::MOV16rr,
7727 X86::NOT16r, X86::AX,
7728 X86::GR16RegisterClass);
7729 case X86::ATOMXOR16:
7730 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7731 X86::XOR16ri, X86::MOV16rm,
7732 X86::LCMPXCHG16, X86::MOV16rr,
7733 X86::NOT16r, X86::AX,
7734 X86::GR16RegisterClass);
7735 case X86::ATOMNAND16:
7736 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7737 X86::AND16ri, X86::MOV16rm,
7738 X86::LCMPXCHG16, X86::MOV16rr,
7739 X86::NOT16r, X86::AX,
7740 X86::GR16RegisterClass, true);
7741 case X86::ATOMMIN16:
7742 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7743 case X86::ATOMMAX16:
7744 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7745 case X86::ATOMUMIN16:
7746 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7747 case X86::ATOMUMAX16:
7748 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7751 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7752 X86::AND8ri, X86::MOV8rm,
7753 X86::LCMPXCHG8, X86::MOV8rr,
7754 X86::NOT8r, X86::AL,
7755 X86::GR8RegisterClass);
7757 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7758 X86::OR8ri, X86::MOV8rm,
7759 X86::LCMPXCHG8, X86::MOV8rr,
7760 X86::NOT8r, X86::AL,
7761 X86::GR8RegisterClass);
7763 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7764 X86::XOR8ri, X86::MOV8rm,
7765 X86::LCMPXCHG8, X86::MOV8rr,
7766 X86::NOT8r, X86::AL,
7767 X86::GR8RegisterClass);
7768 case X86::ATOMNAND8:
7769 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7770 X86::AND8ri, X86::MOV8rm,
7771 X86::LCMPXCHG8, X86::MOV8rr,
7772 X86::NOT8r, X86::AL,
7773 X86::GR8RegisterClass, true);
7774 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7775 // This group is for 64-bit host.
7776 case X86::ATOMAND64:
7777 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7778 X86::AND64ri32, X86::MOV64rm,
7779 X86::LCMPXCHG64, X86::MOV64rr,
7780 X86::NOT64r, X86::RAX,
7781 X86::GR64RegisterClass);
7783 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7784 X86::OR64ri32, X86::MOV64rm,
7785 X86::LCMPXCHG64, X86::MOV64rr,
7786 X86::NOT64r, X86::RAX,
7787 X86::GR64RegisterClass);
7788 case X86::ATOMXOR64:
7789 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7790 X86::XOR64ri32, X86::MOV64rm,
7791 X86::LCMPXCHG64, X86::MOV64rr,
7792 X86::NOT64r, X86::RAX,
7793 X86::GR64RegisterClass);
7794 case X86::ATOMNAND64:
7795 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7796 X86::AND64ri32, X86::MOV64rm,
7797 X86::LCMPXCHG64, X86::MOV64rr,
7798 X86::NOT64r, X86::RAX,
7799 X86::GR64RegisterClass, true);
7800 case X86::ATOMMIN64:
7801 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7802 case X86::ATOMMAX64:
7803 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7804 case X86::ATOMUMIN64:
7805 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7806 case X86::ATOMUMAX64:
7807 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7809 // This group does 64-bit operations on a 32-bit host.
7810 case X86::ATOMAND6432:
7811 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7812 X86::AND32rr, X86::AND32rr,
7813 X86::AND32ri, X86::AND32ri,
7815 case X86::ATOMOR6432:
7816 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7817 X86::OR32rr, X86::OR32rr,
7818 X86::OR32ri, X86::OR32ri,
7820 case X86::ATOMXOR6432:
7821 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7822 X86::XOR32rr, X86::XOR32rr,
7823 X86::XOR32ri, X86::XOR32ri,
7825 case X86::ATOMNAND6432:
7826 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7827 X86::AND32rr, X86::AND32rr,
7828 X86::AND32ri, X86::AND32ri,
7830 case X86::ATOMADD6432:
7831 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7832 X86::ADD32rr, X86::ADC32rr,
7833 X86::ADD32ri, X86::ADC32ri,
7835 case X86::ATOMSUB6432:
7836 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7837 X86::SUB32rr, X86::SBB32rr,
7838 X86::SUB32ri, X86::SBB32ri,
7840 case X86::ATOMSWAP6432:
7841 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7842 X86::MOV32rr, X86::MOV32rr,
7843 X86::MOV32ri, X86::MOV32ri,
7848 //===----------------------------------------------------------------------===//
7849 // X86 Optimization Hooks
7850 //===----------------------------------------------------------------------===//
7852 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7856 const SelectionDAG &DAG,
7857 unsigned Depth) const {
7858 unsigned Opc = Op.getOpcode();
7859 assert((Opc >= ISD::BUILTIN_OP_END ||
7860 Opc == ISD::INTRINSIC_WO_CHAIN ||
7861 Opc == ISD::INTRINSIC_W_CHAIN ||
7862 Opc == ISD::INTRINSIC_VOID) &&
7863 "Should use MaskedValueIsZero if you don't know whether Op"
7864 " is a target node!");
7866 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7875 // These nodes' second result is a boolean.
7876 if (Op.getResNo() == 0)
7880 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7881 Mask.getBitWidth() - 1);
7886 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7887 /// node is a GlobalAddress + offset.
7888 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7889 GlobalValue* &GA, int64_t &Offset) const{
7890 if (N->getOpcode() == X86ISD::Wrapper) {
7891 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7892 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7893 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7897 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7900 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7901 const TargetLowering &TLI) {
7904 if (TLI.isGAPlusOffset(Base, GV, Offset))
7905 return (GV->getAlignment() >= N && (Offset % N) == 0);
7906 // DAG combine handles the stack object case.
7910 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7911 MVT EVT, LoadSDNode *&LDBase,
7912 unsigned &LastLoadedElt,
7913 SelectionDAG &DAG, MachineFrameInfo *MFI,
7914 const TargetLowering &TLI) {
7916 LastLoadedElt = -1U;
7917 for (unsigned i = 0; i < NumElems; ++i) {
7918 if (N->getMaskElt(i) < 0) {
7924 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7925 if (!Elt.getNode() ||
7926 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7929 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
7931 LDBase = cast<LoadSDNode>(Elt.getNode());
7935 if (Elt.getOpcode() == ISD::UNDEF)
7938 LoadSDNode *LD = cast<LoadSDNode>(Elt);
7939 if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
7946 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7947 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7948 /// if the load addresses are consecutive, non-overlapping, and in the right
7949 /// order. In the case of v2i64, it will see if it can rewrite the
7950 /// shuffle to be an appropriate build vector so it can take advantage of
7951 // performBuildVectorCombine.
7952 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7953 const TargetLowering &TLI) {
7954 DebugLoc dl = N->getDebugLoc();
7955 MVT VT = N->getValueType(0);
7956 MVT EVT = VT.getVectorElementType();
7957 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7958 unsigned NumElems = VT.getVectorNumElements();
7960 if (VT.getSizeInBits() != 128)
7963 // Try to combine a vector_shuffle into a 128-bit load.
7964 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7965 LoadSDNode *LD = NULL;
7966 unsigned LastLoadedElt;
7967 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
7971 if (LastLoadedElt == NumElems - 1) {
7972 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
7973 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7974 LD->getSrcValue(), LD->getSrcValueOffset(),
7976 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7977 LD->getSrcValue(), LD->getSrcValueOffset(),
7978 LD->isVolatile(), LD->getAlignment());
7979 } else if (NumElems == 4 && LastLoadedElt == 1) {
7980 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7981 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7982 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7983 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
7988 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7989 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7990 const X86Subtarget *Subtarget) {
7991 DebugLoc DL = N->getDebugLoc();
7992 SDValue Cond = N->getOperand(0);
7993 // Get the LHS/RHS of the select.
7994 SDValue LHS = N->getOperand(1);
7995 SDValue RHS = N->getOperand(2);
7997 // If we have SSE[12] support, try to form min/max nodes.
7998 if (Subtarget->hasSSE2() &&
7999 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8000 Cond.getOpcode() == ISD::SETCC) {
8001 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8003 unsigned Opcode = 0;
8004 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8007 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
8010 if (!UnsafeFPMath) break;
8012 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
8014 Opcode = X86ISD::FMIN;
8017 case ISD::SETOGT: // (X > Y) ? X : Y -> max
8020 if (!UnsafeFPMath) break;
8022 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
8024 Opcode = X86ISD::FMAX;
8027 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8030 case ISD::SETOGT: // (X > Y) ? Y : X -> min
8033 if (!UnsafeFPMath) break;
8035 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
8037 Opcode = X86ISD::FMIN;
8040 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
8043 if (!UnsafeFPMath) break;
8045 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
8047 Opcode = X86ISD::FMAX;
8053 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8056 // If this is a select between two integer constants, try to do some
8058 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8059 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8060 // Don't do this for crazy integer types.
8061 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8062 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8063 // so that TrueC (the true value) is larger than FalseC.
8064 bool NeedsCondInvert = false;
8066 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8067 // Efficiently invertible.
8068 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8069 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8070 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8071 NeedsCondInvert = true;
8072 std::swap(TrueC, FalseC);
8075 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8076 if (FalseC->getAPIntValue() == 0 &&
8077 TrueC->getAPIntValue().isPowerOf2()) {
8078 if (NeedsCondInvert) // Invert the condition if needed.
8079 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8080 DAG.getConstant(1, Cond.getValueType()));
8082 // Zero extend the condition if needed.
8083 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8085 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8086 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8087 DAG.getConstant(ShAmt, MVT::i8));
8090 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8091 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8092 if (NeedsCondInvert) // Invert the condition if needed.
8093 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8094 DAG.getConstant(1, Cond.getValueType()));
8096 // Zero extend the condition if needed.
8097 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8098 FalseC->getValueType(0), Cond);
8099 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8100 SDValue(FalseC, 0));
8103 // Optimize cases that will turn into an LEA instruction. This requires
8104 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8105 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8106 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8107 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8109 bool isFastMultiplier = false;
8111 switch ((unsigned char)Diff) {
8113 case 1: // result = add base, cond
8114 case 2: // result = lea base( , cond*2)
8115 case 3: // result = lea base(cond, cond*2)
8116 case 4: // result = lea base( , cond*4)
8117 case 5: // result = lea base(cond, cond*4)
8118 case 8: // result = lea base( , cond*8)
8119 case 9: // result = lea base(cond, cond*8)
8120 isFastMultiplier = true;
8125 if (isFastMultiplier) {
8126 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8127 if (NeedsCondInvert) // Invert the condition if needed.
8128 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8129 DAG.getConstant(1, Cond.getValueType()));
8131 // Zero extend the condition if needed.
8132 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8134 // Scale the condition by the difference.
8136 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8137 DAG.getConstant(Diff, Cond.getValueType()));
8139 // Add the base if non-zero.
8140 if (FalseC->getAPIntValue() != 0)
8141 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8142 SDValue(FalseC, 0));
8152 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8153 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8154 TargetLowering::DAGCombinerInfo &DCI) {
8155 DebugLoc DL = N->getDebugLoc();
8157 // If the flag operand isn't dead, don't touch this CMOV.
8158 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8161 // If this is a select between two integer constants, try to do some
8162 // optimizations. Note that the operands are ordered the opposite of SELECT
8164 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8165 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8166 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8167 // larger than FalseC (the false value).
8168 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8170 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8171 CC = X86::GetOppositeBranchCondition(CC);
8172 std::swap(TrueC, FalseC);
8175 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8176 // This is efficient for any integer data type (including i8/i16) and
8178 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8179 SDValue Cond = N->getOperand(3);
8180 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8181 DAG.getConstant(CC, MVT::i8), Cond);
8183 // Zero extend the condition if needed.
8184 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8186 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8187 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8188 DAG.getConstant(ShAmt, MVT::i8));
8189 if (N->getNumValues() == 2) // Dead flag value?
8190 return DCI.CombineTo(N, Cond, SDValue());
8194 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8195 // for any integer data type, including i8/i16.
8196 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8197 SDValue Cond = N->getOperand(3);
8198 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8199 DAG.getConstant(CC, MVT::i8), Cond);
8201 // Zero extend the condition if needed.
8202 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8203 FalseC->getValueType(0), Cond);
8204 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8205 SDValue(FalseC, 0));
8207 if (N->getNumValues() == 2) // Dead flag value?
8208 return DCI.CombineTo(N, Cond, SDValue());
8212 // Optimize cases that will turn into an LEA instruction. This requires
8213 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8214 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8215 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8216 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8218 bool isFastMultiplier = false;
8220 switch ((unsigned char)Diff) {
8222 case 1: // result = add base, cond
8223 case 2: // result = lea base( , cond*2)
8224 case 3: // result = lea base(cond, cond*2)
8225 case 4: // result = lea base( , cond*4)
8226 case 5: // result = lea base(cond, cond*4)
8227 case 8: // result = lea base( , cond*8)
8228 case 9: // result = lea base(cond, cond*8)
8229 isFastMultiplier = true;
8234 if (isFastMultiplier) {
8235 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8236 SDValue Cond = N->getOperand(3);
8237 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8238 DAG.getConstant(CC, MVT::i8), Cond);
8239 // Zero extend the condition if needed.
8240 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8242 // Scale the condition by the difference.
8244 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8245 DAG.getConstant(Diff, Cond.getValueType()));
8247 // Add the base if non-zero.
8248 if (FalseC->getAPIntValue() != 0)
8249 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8250 SDValue(FalseC, 0));
8251 if (N->getNumValues() == 2) // Dead flag value?
8252 return DCI.CombineTo(N, Cond, SDValue());
8262 /// PerformMulCombine - Optimize a single multiply with constant into two
8263 /// in order to implement it with two cheaper instructions, e.g.
8264 /// LEA + SHL, LEA + LEA.
8265 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8266 TargetLowering::DAGCombinerInfo &DCI) {
8267 if (DAG.getMachineFunction().
8268 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8271 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8274 MVT VT = N->getValueType(0);
8278 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8281 uint64_t MulAmt = C->getZExtValue();
8282 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8285 uint64_t MulAmt1 = 0;
8286 uint64_t MulAmt2 = 0;
8287 if ((MulAmt % 9) == 0) {
8289 MulAmt2 = MulAmt / 9;
8290 } else if ((MulAmt % 5) == 0) {
8292 MulAmt2 = MulAmt / 5;
8293 } else if ((MulAmt % 3) == 0) {
8295 MulAmt2 = MulAmt / 3;
8298 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8299 DebugLoc DL = N->getDebugLoc();
8301 if (isPowerOf2_64(MulAmt2) &&
8302 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8303 // If second multiplifer is pow2, issue it first. We want the multiply by
8304 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8306 std::swap(MulAmt1, MulAmt2);
8309 if (isPowerOf2_64(MulAmt1))
8310 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8311 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8313 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8314 DAG.getConstant(MulAmt1, VT));
8316 if (isPowerOf2_64(MulAmt2))
8317 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8318 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8320 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8321 DAG.getConstant(MulAmt2, VT));
8323 // Do not add new nodes to DAG combiner worklist.
8324 DCI.CombineTo(N, NewMul, false);
8330 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8332 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8333 const X86Subtarget *Subtarget) {
8334 // On X86 with SSE2 support, we can transform this to a vector shift if
8335 // all elements are shifted by the same amount. We can't do this in legalize
8336 // because the a constant vector is typically transformed to a constant pool
8337 // so we have no knowledge of the shift amount.
8338 if (!Subtarget->hasSSE2())
8341 MVT VT = N->getValueType(0);
8342 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8345 SDValue ShAmtOp = N->getOperand(1);
8346 MVT EltVT = VT.getVectorElementType();
8347 DebugLoc DL = N->getDebugLoc();
8349 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8350 unsigned NumElts = VT.getVectorNumElements();
8352 for (; i != NumElts; ++i) {
8353 SDValue Arg = ShAmtOp.getOperand(i);
8354 if (Arg.getOpcode() == ISD::UNDEF) continue;
8358 for (; i != NumElts; ++i) {
8359 SDValue Arg = ShAmtOp.getOperand(i);
8360 if (Arg.getOpcode() == ISD::UNDEF) continue;
8361 if (Arg != BaseShAmt) {
8365 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8366 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8367 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8368 DAG.getIntPtrConstant(0));
8372 if (EltVT.bitsGT(MVT::i32))
8373 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8374 else if (EltVT.bitsLT(MVT::i32))
8375 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8377 // The shift amount is identical so we can do a vector shift.
8378 SDValue ValOp = N->getOperand(0);
8379 switch (N->getOpcode()) {
8381 llvm_unreachable("Unknown shift opcode!");
8384 if (VT == MVT::v2i64)
8385 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8386 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8388 if (VT == MVT::v4i32)
8389 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8390 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8392 if (VT == MVT::v8i16)
8393 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8394 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8398 if (VT == MVT::v4i32)
8399 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8400 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8402 if (VT == MVT::v8i16)
8403 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8404 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8408 if (VT == MVT::v2i64)
8409 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8410 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8412 if (VT == MVT::v4i32)
8413 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8414 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8416 if (VT == MVT::v8i16)
8417 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8418 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8425 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8426 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8427 const X86Subtarget *Subtarget) {
8428 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8429 // the FP state in cases where an emms may be missing.
8430 // A preferable solution to the general problem is to figure out the right
8431 // places to insert EMMS. This qualifies as a quick hack.
8433 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8434 StoreSDNode *St = cast<StoreSDNode>(N);
8435 MVT VT = St->getValue().getValueType();
8436 if (VT.getSizeInBits() != 64)
8439 const Function *F = DAG.getMachineFunction().getFunction();
8440 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8441 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8442 && Subtarget->hasSSE2();
8443 if ((VT.isVector() ||
8444 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8445 isa<LoadSDNode>(St->getValue()) &&
8446 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8447 St->getChain().hasOneUse() && !St->isVolatile()) {
8448 SDNode* LdVal = St->getValue().getNode();
8450 int TokenFactorIndex = -1;
8451 SmallVector<SDValue, 8> Ops;
8452 SDNode* ChainVal = St->getChain().getNode();
8453 // Must be a store of a load. We currently handle two cases: the load
8454 // is a direct child, and it's under an intervening TokenFactor. It is
8455 // possible to dig deeper under nested TokenFactors.
8456 if (ChainVal == LdVal)
8457 Ld = cast<LoadSDNode>(St->getChain());
8458 else if (St->getValue().hasOneUse() &&
8459 ChainVal->getOpcode() == ISD::TokenFactor) {
8460 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8461 if (ChainVal->getOperand(i).getNode() == LdVal) {
8462 TokenFactorIndex = i;
8463 Ld = cast<LoadSDNode>(St->getValue());
8465 Ops.push_back(ChainVal->getOperand(i));
8469 if (!Ld || !ISD::isNormalLoad(Ld))
8472 // If this is not the MMX case, i.e. we are just turning i64 load/store
8473 // into f64 load/store, avoid the transformation if there are multiple
8474 // uses of the loaded value.
8475 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8478 DebugLoc LdDL = Ld->getDebugLoc();
8479 DebugLoc StDL = N->getDebugLoc();
8480 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8481 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8483 if (Subtarget->is64Bit() || F64IsLegal) {
8484 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8485 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8486 Ld->getBasePtr(), Ld->getSrcValue(),
8487 Ld->getSrcValueOffset(), Ld->isVolatile(),
8488 Ld->getAlignment());
8489 SDValue NewChain = NewLd.getValue(1);
8490 if (TokenFactorIndex != -1) {
8491 Ops.push_back(NewChain);
8492 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8495 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8496 St->getSrcValue(), St->getSrcValueOffset(),
8497 St->isVolatile(), St->getAlignment());
8500 // Otherwise, lower to two pairs of 32-bit loads / stores.
8501 SDValue LoAddr = Ld->getBasePtr();
8502 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8503 DAG.getConstant(4, MVT::i32));
8505 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8506 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8507 Ld->isVolatile(), Ld->getAlignment());
8508 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8509 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8511 MinAlign(Ld->getAlignment(), 4));
8513 SDValue NewChain = LoLd.getValue(1);
8514 if (TokenFactorIndex != -1) {
8515 Ops.push_back(LoLd);
8516 Ops.push_back(HiLd);
8517 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8521 LoAddr = St->getBasePtr();
8522 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8523 DAG.getConstant(4, MVT::i32));
8525 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8526 St->getSrcValue(), St->getSrcValueOffset(),
8527 St->isVolatile(), St->getAlignment());
8528 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8530 St->getSrcValueOffset() + 4,
8532 MinAlign(St->getAlignment(), 4));
8533 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8538 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8539 /// X86ISD::FXOR nodes.
8540 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8541 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8542 // F[X]OR(0.0, x) -> x
8543 // F[X]OR(x, 0.0) -> x
8544 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8545 if (C->getValueAPF().isPosZero())
8546 return N->getOperand(1);
8547 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8548 if (C->getValueAPF().isPosZero())
8549 return N->getOperand(0);
8553 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8554 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8555 // FAND(0.0, x) -> 0.0
8556 // FAND(x, 0.0) -> 0.0
8557 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8558 if (C->getValueAPF().isPosZero())
8559 return N->getOperand(0);
8560 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8561 if (C->getValueAPF().isPosZero())
8562 return N->getOperand(1);
8566 static SDValue PerformBTCombine(SDNode *N,
8568 TargetLowering::DAGCombinerInfo &DCI) {
8569 // BT ignores high bits in the bit index operand.
8570 SDValue Op1 = N->getOperand(1);
8571 if (Op1.hasOneUse()) {
8572 unsigned BitWidth = Op1.getValueSizeInBits();
8573 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8574 APInt KnownZero, KnownOne;
8575 TargetLowering::TargetLoweringOpt TLO(DAG);
8576 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8577 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8578 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8579 DCI.CommitTargetLoweringOpt(TLO);
8584 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8585 SDValue Op = N->getOperand(0);
8586 if (Op.getOpcode() == ISD::BIT_CONVERT)
8587 Op = Op.getOperand(0);
8588 MVT VT = N->getValueType(0), OpVT = Op.getValueType();
8589 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8590 VT.getVectorElementType().getSizeInBits() ==
8591 OpVT.getVectorElementType().getSizeInBits()) {
8592 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8597 // On X86 and X86-64, atomic operations are lowered to locked instructions.
8598 // Locked instructions, in turn, have implicit fence semantics (all memory
8599 // operations are flushed before issuing the locked instruction, and the
8600 // are not buffered), so we can fold away the common pattern of
8601 // fence-atomic-fence.
8602 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
8603 SDValue atomic = N->getOperand(0);
8604 switch (atomic.getOpcode()) {
8605 case ISD::ATOMIC_CMP_SWAP:
8606 case ISD::ATOMIC_SWAP:
8607 case ISD::ATOMIC_LOAD_ADD:
8608 case ISD::ATOMIC_LOAD_SUB:
8609 case ISD::ATOMIC_LOAD_AND:
8610 case ISD::ATOMIC_LOAD_OR:
8611 case ISD::ATOMIC_LOAD_XOR:
8612 case ISD::ATOMIC_LOAD_NAND:
8613 case ISD::ATOMIC_LOAD_MIN:
8614 case ISD::ATOMIC_LOAD_MAX:
8615 case ISD::ATOMIC_LOAD_UMIN:
8616 case ISD::ATOMIC_LOAD_UMAX:
8622 SDValue fence = atomic.getOperand(0);
8623 if (fence.getOpcode() != ISD::MEMBARRIER)
8626 switch (atomic.getOpcode()) {
8627 case ISD::ATOMIC_CMP_SWAP:
8628 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8629 atomic.getOperand(1), atomic.getOperand(2),
8630 atomic.getOperand(3));
8631 case ISD::ATOMIC_SWAP:
8632 case ISD::ATOMIC_LOAD_ADD:
8633 case ISD::ATOMIC_LOAD_SUB:
8634 case ISD::ATOMIC_LOAD_AND:
8635 case ISD::ATOMIC_LOAD_OR:
8636 case ISD::ATOMIC_LOAD_XOR:
8637 case ISD::ATOMIC_LOAD_NAND:
8638 case ISD::ATOMIC_LOAD_MIN:
8639 case ISD::ATOMIC_LOAD_MAX:
8640 case ISD::ATOMIC_LOAD_UMIN:
8641 case ISD::ATOMIC_LOAD_UMAX:
8642 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8643 atomic.getOperand(1), atomic.getOperand(2));
8649 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8650 DAGCombinerInfo &DCI) const {
8651 SelectionDAG &DAG = DCI.DAG;
8652 switch (N->getOpcode()) {
8654 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8655 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8656 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8657 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8660 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8661 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8663 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8664 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8665 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8666 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
8667 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
8673 //===----------------------------------------------------------------------===//
8674 // X86 Inline Assembly Support
8675 //===----------------------------------------------------------------------===//
8677 static bool LowerToBSwap(CallInst *CI) {
8678 // FIXME: this should verify that we are targetting a 486 or better. If not,
8679 // we will turn this bswap into something that will be lowered to logical ops
8680 // instead of emitting the bswap asm. For now, we don't support 486 or lower
8681 // so don't worry about this.
8683 // Verify this is a simple bswap.
8684 if (CI->getNumOperands() != 2 ||
8685 CI->getType() != CI->getOperand(1)->getType() ||
8686 !CI->getType()->isInteger())
8689 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8690 if (!Ty || Ty->getBitWidth() % 16 != 0)
8693 // Okay, we can do this xform, do so now.
8694 const Type *Tys[] = { Ty };
8695 Module *M = CI->getParent()->getParent()->getParent();
8696 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
8698 Value *Op = CI->getOperand(1);
8699 Op = CallInst::Create(Int, Op, CI->getName(), CI);
8701 CI->replaceAllUsesWith(Op);
8702 CI->eraseFromParent();
8706 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
8707 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8708 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
8710 std::string AsmStr = IA->getAsmString();
8712 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
8713 std::vector<std::string> AsmPieces;
8714 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
8716 switch (AsmPieces.size()) {
8717 default: return false;
8719 AsmStr = AsmPieces[0];
8721 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
8724 if (AsmPieces.size() == 2 &&
8725 (AsmPieces[0] == "bswap" ||
8726 AsmPieces[0] == "bswapq" ||
8727 AsmPieces[0] == "bswapl") &&
8728 (AsmPieces[1] == "$0" ||
8729 AsmPieces[1] == "${0:q}")) {
8730 // No need to check constraints, nothing other than the equivalent of
8731 // "=r,0" would be valid here.
8732 return LowerToBSwap(CI);
8734 // rorw $$8, ${0:w} --> llvm.bswap.i16
8735 if (CI->getType() == Type::Int16Ty &&
8736 AsmPieces.size() == 3 &&
8737 AsmPieces[0] == "rorw" &&
8738 AsmPieces[1] == "$$8," &&
8739 AsmPieces[2] == "${0:w}" &&
8740 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
8741 return LowerToBSwap(CI);
8745 if (CI->getType() == Type::Int64Ty && Constraints.size() >= 2 &&
8746 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
8747 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
8748 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
8749 std::vector<std::string> Words;
8750 SplitString(AsmPieces[0], Words, " \t");
8751 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
8753 SplitString(AsmPieces[1], Words, " \t");
8754 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
8756 SplitString(AsmPieces[2], Words, " \t,");
8757 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
8758 Words[2] == "%edx") {
8759 return LowerToBSwap(CI);
8771 /// getConstraintType - Given a constraint letter, return the type of
8772 /// constraint it is for this target.
8773 X86TargetLowering::ConstraintType
8774 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8775 if (Constraint.size() == 1) {
8776 switch (Constraint[0]) {
8788 return C_RegisterClass;
8796 return TargetLowering::getConstraintType(Constraint);
8799 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8800 /// with another that has more specific requirements based on the type of the
8801 /// corresponding operand.
8802 const char *X86TargetLowering::
8803 LowerXConstraint(MVT ConstraintVT) const {
8804 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8805 // 'f' like normal targets.
8806 if (ConstraintVT.isFloatingPoint()) {
8807 if (Subtarget->hasSSE2())
8809 if (Subtarget->hasSSE1())
8813 return TargetLowering::LowerXConstraint(ConstraintVT);
8816 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8817 /// vector. If it is invalid, don't add anything to Ops.
8818 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8821 std::vector<SDValue>&Ops,
8822 SelectionDAG &DAG) const {
8823 SDValue Result(0, 0);
8825 switch (Constraint) {
8828 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8829 if (C->getZExtValue() <= 31) {
8830 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8837 if (C->getZExtValue() <= 63) {
8838 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8845 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
8846 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8853 if (C->getZExtValue() <= 255) {
8854 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8860 // 32-bit signed value
8861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8862 const ConstantInt *CI = C->getConstantIntValue();
8863 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8864 // Widen to 64 bits here to get it sign extended.
8865 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8868 // FIXME gcc accepts some relocatable values here too, but only in certain
8869 // memory models; it's complicated.
8874 // 32-bit unsigned value
8875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8876 const ConstantInt *CI = C->getConstantIntValue();
8877 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8878 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8882 // FIXME gcc accepts some relocatable values here too, but only in certain
8883 // memory models; it's complicated.
8887 // Literal immediates are always ok.
8888 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8889 // Widen to 64 bits here to get it sign extended.
8890 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8894 // If we are in non-pic codegen mode, we allow the address of a global (with
8895 // an optional displacement) to be used with 'i'.
8896 GlobalAddressSDNode *GA = 0;
8899 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8901 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8902 Offset += GA->getOffset();
8904 } else if (Op.getOpcode() == ISD::ADD) {
8905 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8906 Offset += C->getZExtValue();
8907 Op = Op.getOperand(0);
8910 } else if (Op.getOpcode() == ISD::SUB) {
8911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8912 Offset += -C->getZExtValue();
8913 Op = Op.getOperand(0);
8918 // Otherwise, this isn't something we can handle, reject it.
8922 GlobalValue *GV = GA->getGlobal();
8923 // If we require an extra load to get this address, as in PIC mode, we
8925 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
8926 getTargetMachine())))
8930 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
8932 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
8938 if (Result.getNode()) {
8939 Ops.push_back(Result);
8942 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8946 std::vector<unsigned> X86TargetLowering::
8947 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8949 if (Constraint.size() == 1) {
8950 // FIXME: not handling fp-stack yet!
8951 switch (Constraint[0]) { // GCC X86 Constraint Letters
8952 default: break; // Unknown constraint letter
8953 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
8954 if (Subtarget->is64Bit()) {
8956 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
8957 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
8958 X86::R10D,X86::R11D,X86::R12D,
8959 X86::R13D,X86::R14D,X86::R15D,
8960 X86::EBP, X86::ESP, 0);
8961 else if (VT == MVT::i16)
8962 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
8963 X86::SI, X86::DI, X86::R8W,X86::R9W,
8964 X86::R10W,X86::R11W,X86::R12W,
8965 X86::R13W,X86::R14W,X86::R15W,
8966 X86::BP, X86::SP, 0);
8967 else if (VT == MVT::i8)
8968 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
8969 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
8970 X86::R10B,X86::R11B,X86::R12B,
8971 X86::R13B,X86::R14B,X86::R15B,
8972 X86::BPL, X86::SPL, 0);
8974 else if (VT == MVT::i64)
8975 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
8976 X86::RSI, X86::RDI, X86::R8, X86::R9,
8977 X86::R10, X86::R11, X86::R12,
8978 X86::R13, X86::R14, X86::R15,
8979 X86::RBP, X86::RSP, 0);
8983 // 32-bit fallthrough
8986 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8987 else if (VT == MVT::i16)
8988 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8989 else if (VT == MVT::i8)
8990 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8991 else if (VT == MVT::i64)
8992 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8997 return std::vector<unsigned>();
9000 std::pair<unsigned, const TargetRegisterClass*>
9001 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9003 // First, see if this is a constraint that directly corresponds to an LLVM
9005 if (Constraint.size() == 1) {
9006 // GCC Constraint Letters
9007 switch (Constraint[0]) {
9009 case 'r': // GENERAL_REGS
9010 case 'R': // LEGACY_REGS
9011 case 'l': // INDEX_REGS
9013 return std::make_pair(0U, X86::GR8RegisterClass);
9015 return std::make_pair(0U, X86::GR16RegisterClass);
9016 if (VT == MVT::i32 || !Subtarget->is64Bit())
9017 return std::make_pair(0U, X86::GR32RegisterClass);
9018 return std::make_pair(0U, X86::GR64RegisterClass);
9019 case 'f': // FP Stack registers.
9020 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9021 // value to the correct fpstack register class.
9022 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9023 return std::make_pair(0U, X86::RFP32RegisterClass);
9024 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9025 return std::make_pair(0U, X86::RFP64RegisterClass);
9026 return std::make_pair(0U, X86::RFP80RegisterClass);
9027 case 'y': // MMX_REGS if MMX allowed.
9028 if (!Subtarget->hasMMX()) break;
9029 return std::make_pair(0U, X86::VR64RegisterClass);
9030 case 'Y': // SSE_REGS if SSE2 allowed
9031 if (!Subtarget->hasSSE2()) break;
9033 case 'x': // SSE_REGS if SSE1 allowed
9034 if (!Subtarget->hasSSE1()) break;
9036 switch (VT.getSimpleVT()) {
9038 // Scalar SSE types.
9041 return std::make_pair(0U, X86::FR32RegisterClass);
9044 return std::make_pair(0U, X86::FR64RegisterClass);
9052 return std::make_pair(0U, X86::VR128RegisterClass);
9058 // Use the default implementation in TargetLowering to convert the register
9059 // constraint into a member of a register class.
9060 std::pair<unsigned, const TargetRegisterClass*> Res;
9061 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9063 // Not found as a standard register?
9064 if (Res.second == 0) {
9065 // GCC calls "st(0)" just plain "st".
9066 if (StringsEqualNoCase("{st}", Constraint)) {
9067 Res.first = X86::ST0;
9068 Res.second = X86::RFP80RegisterClass;
9070 // 'A' means EAX + EDX.
9071 if (Constraint == "A") {
9072 Res.first = X86::EAX;
9073 Res.second = X86::GR32_ADRegisterClass;
9078 // Otherwise, check to see if this is a register class of the wrong value
9079 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9080 // turn into {ax},{dx}.
9081 if (Res.second->hasType(VT))
9082 return Res; // Correct type already, nothing to do.
9084 // All of the single-register GCC register classes map their values onto
9085 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9086 // really want an 8-bit or 32-bit register, map to the appropriate register
9087 // class and return the appropriate register.
9088 if (Res.second == X86::GR16RegisterClass) {
9089 if (VT == MVT::i8) {
9090 unsigned DestReg = 0;
9091 switch (Res.first) {
9093 case X86::AX: DestReg = X86::AL; break;
9094 case X86::DX: DestReg = X86::DL; break;
9095 case X86::CX: DestReg = X86::CL; break;
9096 case X86::BX: DestReg = X86::BL; break;
9099 Res.first = DestReg;
9100 Res.second = X86::GR8RegisterClass;
9102 } else if (VT == MVT::i32) {
9103 unsigned DestReg = 0;
9104 switch (Res.first) {
9106 case X86::AX: DestReg = X86::EAX; break;
9107 case X86::DX: DestReg = X86::EDX; break;
9108 case X86::CX: DestReg = X86::ECX; break;
9109 case X86::BX: DestReg = X86::EBX; break;
9110 case X86::SI: DestReg = X86::ESI; break;
9111 case X86::DI: DestReg = X86::EDI; break;
9112 case X86::BP: DestReg = X86::EBP; break;
9113 case X86::SP: DestReg = X86::ESP; break;
9116 Res.first = DestReg;
9117 Res.second = X86::GR32RegisterClass;
9119 } else if (VT == MVT::i64) {
9120 unsigned DestReg = 0;
9121 switch (Res.first) {
9123 case X86::AX: DestReg = X86::RAX; break;
9124 case X86::DX: DestReg = X86::RDX; break;
9125 case X86::CX: DestReg = X86::RCX; break;
9126 case X86::BX: DestReg = X86::RBX; break;
9127 case X86::SI: DestReg = X86::RSI; break;
9128 case X86::DI: DestReg = X86::RDI; break;
9129 case X86::BP: DestReg = X86::RBP; break;
9130 case X86::SP: DestReg = X86::RSP; break;
9133 Res.first = DestReg;
9134 Res.second = X86::GR64RegisterClass;
9137 } else if (Res.second == X86::FR32RegisterClass ||
9138 Res.second == X86::FR64RegisterClass ||
9139 Res.second == X86::VR128RegisterClass) {
9140 // Handle references to XMM physical registers that got mapped into the
9141 // wrong class. This can happen with constraints like {xmm0} where the
9142 // target independent register mapper will just pick the first match it can
9143 // find, ignoring the required type.
9145 Res.second = X86::FR32RegisterClass;
9146 else if (VT == MVT::f64)
9147 Res.second = X86::FR64RegisterClass;
9148 else if (X86::VR128RegisterClass->hasType(VT))
9149 Res.second = X86::VR128RegisterClass;
9155 //===----------------------------------------------------------------------===//
9156 // X86 Widen vector type
9157 //===----------------------------------------------------------------------===//
9159 /// getWidenVectorType: given a vector type, returns the type to widen
9160 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9161 /// If there is no vector type that we want to widen to, returns MVT::Other
9162 /// When and where to widen is target dependent based on the cost of
9163 /// scalarizing vs using the wider vector type.
9165 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
9166 assert(VT.isVector());
9167 if (isTypeLegal(VT))
9170 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9171 // type based on element type. This would speed up our search (though
9172 // it may not be worth it since the size of the list is relatively
9174 MVT EltVT = VT.getVectorElementType();
9175 unsigned NElts = VT.getVectorNumElements();
9177 // On X86, it make sense to widen any vector wider than 1
9181 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9182 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9183 MVT SVT = (MVT::SimpleValueType)nVT;
9185 if (isTypeLegal(SVT) &&
9186 SVT.getVectorElementType() == EltVT &&
9187 SVT.getVectorNumElements() > NElts)