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 "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
43 // Forward declarations.
44 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
46 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
47 : TargetLowering(TM) {
48 Subtarget = &TM.getSubtarget<X86Subtarget>();
49 X86ScalarSSEf64 = Subtarget->hasSSE2();
50 X86ScalarSSEf32 = Subtarget->hasSSE1();
51 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
55 RegInfo = TM.getRegisterInfo();
58 // Set up the TargetLowering object.
60 // X86 is weird, it always uses i8 for shift amounts and setcc results.
61 setShiftAmountType(MVT::i8);
62 setSetCCResultContents(ZeroOrOneSetCCResult);
63 setSchedulingPreference(SchedulingForRegPressure);
64 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
65 setStackPointerRegisterToSaveRestore(X86StackPtr);
67 if (Subtarget->isTargetDarwin()) {
68 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(false);
70 setUseUnderscoreLongJmp(false);
71 } else if (Subtarget->isTargetMingw()) {
72 // MS runtime is weird: it exports _setjmp, but longjmp!
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(false);
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(true);
80 // Set up the register classes.
81 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84 if (Subtarget->is64Bit())
85 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
87 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 // We don't accept any truncstore of integer registers.
90 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
99 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
101 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
103 if (Subtarget->is64Bit()) {
104 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
105 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
108 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
109 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
111 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
114 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
116 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
117 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
118 // SSE has no i16 to fp conversion, only i32
119 if (X86ScalarSSEf32) {
120 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
121 // f32 and f64 cases are Legal, f80 case is not
122 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
124 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
125 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
128 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
129 // are Legal, f80 is custom lowered.
130 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
131 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
133 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
135 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
136 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
138 if (X86ScalarSSEf32) {
139 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
140 // f32 and f64 cases are Legal, f80 case is not
141 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
143 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
144 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
147 // Handle FP_TO_UINT by promoting the destination to a larger signed
149 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
150 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
151 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
153 if (Subtarget->is64Bit()) {
154 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
155 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
157 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
158 // Expand FP_TO_UINT into a select.
159 // FIXME: We would like to use a Custom expander here eventually to do
160 // the optimal thing for SSE vs. the default expansion in the legalizer.
161 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
163 // With SSE3 we can use fisttpll to convert to a signed i64.
164 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
167 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
168 if (!X86ScalarSSEf64) {
169 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
170 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
173 // Scalar integer divide and remainder are lowered to use operations that
174 // produce two results, to match the available instructions. This exposes
175 // the two-result form to trivial CSE, which is able to combine x/y and x%y
176 // into a single instruction.
178 // Scalar integer multiply-high is also lowered to use two-result
179 // operations, to match the available instructions. However, plain multiply
180 // (low) operations are left as Legal, as there are single-result
181 // instructions for this in x86. Using the two-result multiply instructions
182 // when both high and low results are needed must be arranged by dagcombine.
183 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
184 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
185 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
186 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
187 setOperationAction(ISD::SREM , MVT::i8 , Expand);
188 setOperationAction(ISD::UREM , MVT::i8 , Expand);
189 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
190 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
191 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
192 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
193 setOperationAction(ISD::SREM , MVT::i16 , Expand);
194 setOperationAction(ISD::UREM , MVT::i16 , Expand);
195 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
196 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
197 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
198 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
199 setOperationAction(ISD::SREM , MVT::i32 , Expand);
200 setOperationAction(ISD::UREM , MVT::i32 , Expand);
201 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
202 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
203 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
205 setOperationAction(ISD::SREM , MVT::i64 , Expand);
206 setOperationAction(ISD::UREM , MVT::i64 , Expand);
208 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
209 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
210 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
211 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
212 if (Subtarget->is64Bit())
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
217 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
218 setOperationAction(ISD::FREM , MVT::f32 , Expand);
219 setOperationAction(ISD::FREM , MVT::f64 , Expand);
220 setOperationAction(ISD::FREM , MVT::f80 , Expand);
221 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
223 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
224 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
226 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
227 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
229 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
230 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
231 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
232 if (Subtarget->is64Bit()) {
233 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
234 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
235 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
238 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
239 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
241 // These should be promoted to a larger select which is supported.
242 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
243 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
244 // X86 wants to expand cmov itself.
245 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
246 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
249 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
252 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
255 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
258 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
260 // X86 ret instruction may pop stack.
261 setOperationAction(ISD::RET , MVT::Other, Custom);
262 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
265 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
266 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
269 if (Subtarget->is64Bit())
270 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
271 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
272 if (Subtarget->is64Bit()) {
273 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
274 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
275 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
276 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
278 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
279 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
280 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
281 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
282 if (Subtarget->is64Bit()) {
283 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
284 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
285 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
288 if (Subtarget->hasSSE1())
289 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
291 if (!Subtarget->hasSSE2())
292 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
294 // Expand certain atomics
295 setOperationAction(ISD::ATOMIC_CMP_SWAP_8 , MVT::i8, Custom);
296 setOperationAction(ISD::ATOMIC_CMP_SWAP_16, MVT::i16, Custom);
297 setOperationAction(ISD::ATOMIC_CMP_SWAP_32, MVT::i32, Custom);
298 setOperationAction(ISD::ATOMIC_CMP_SWAP_64, MVT::i64, Custom);
300 setOperationAction(ISD::ATOMIC_LOAD_SUB_8 , MVT::i8, Custom);
301 setOperationAction(ISD::ATOMIC_LOAD_SUB_16, MVT::i16, Custom);
302 setOperationAction(ISD::ATOMIC_LOAD_SUB_32, MVT::i32, Custom);
303 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
305 if (!Subtarget->is64Bit()) {
306 setOperationAction(ISD::ATOMIC_LOAD_ADD_64, MVT::i64, Custom);
307 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
308 setOperationAction(ISD::ATOMIC_LOAD_AND_64, MVT::i64, Custom);
309 setOperationAction(ISD::ATOMIC_LOAD_OR_64, MVT::i64, Custom);
310 setOperationAction(ISD::ATOMIC_LOAD_XOR_64, MVT::i64, Custom);
311 setOperationAction(ISD::ATOMIC_LOAD_NAND_64, MVT::i64, Custom);
312 setOperationAction(ISD::ATOMIC_SWAP_64, MVT::i64, Custom);
315 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
316 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
317 // FIXME - use subtarget debug flags
318 if (!Subtarget->isTargetDarwin() &&
319 !Subtarget->isTargetELF() &&
320 !Subtarget->isTargetCygMing()) {
321 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
322 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
325 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
326 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
327 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
328 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
329 if (Subtarget->is64Bit()) {
330 setExceptionPointerRegister(X86::RAX);
331 setExceptionSelectorRegister(X86::RDX);
333 setExceptionPointerRegister(X86::EAX);
334 setExceptionSelectorRegister(X86::EDX);
336 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
337 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
339 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
341 setOperationAction(ISD::TRAP, MVT::Other, Legal);
343 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
344 setOperationAction(ISD::VASTART , MVT::Other, Custom);
345 setOperationAction(ISD::VAEND , MVT::Other, Expand);
346 if (Subtarget->is64Bit()) {
347 setOperationAction(ISD::VAARG , MVT::Other, Custom);
348 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
350 setOperationAction(ISD::VAARG , MVT::Other, Expand);
351 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
354 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
355 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
356 if (Subtarget->is64Bit())
357 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
358 if (Subtarget->isTargetCygMing())
359 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
361 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
363 if (X86ScalarSSEf64) {
364 // f32 and f64 use SSE.
365 // Set up the FP register classes.
366 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
367 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
369 // Use ANDPD to simulate FABS.
370 setOperationAction(ISD::FABS , MVT::f64, Custom);
371 setOperationAction(ISD::FABS , MVT::f32, Custom);
373 // Use XORP to simulate FNEG.
374 setOperationAction(ISD::FNEG , MVT::f64, Custom);
375 setOperationAction(ISD::FNEG , MVT::f32, Custom);
377 // Use ANDPD and ORPD to simulate FCOPYSIGN.
378 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
379 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
381 // We don't support sin/cos/fmod
382 setOperationAction(ISD::FSIN , MVT::f64, Expand);
383 setOperationAction(ISD::FCOS , MVT::f64, Expand);
384 setOperationAction(ISD::FSIN , MVT::f32, Expand);
385 setOperationAction(ISD::FCOS , MVT::f32, Expand);
387 // Expand FP immediates into loads from the stack, except for the special
389 addLegalFPImmediate(APFloat(+0.0)); // xorpd
390 addLegalFPImmediate(APFloat(+0.0f)); // xorps
392 // Floating truncations from f80 and extensions to f80 go through memory.
393 // If optimizing, we lie about this though and handle it in
394 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
396 setConvertAction(MVT::f32, MVT::f80, Expand);
397 setConvertAction(MVT::f64, MVT::f80, Expand);
398 setConvertAction(MVT::f80, MVT::f32, Expand);
399 setConvertAction(MVT::f80, MVT::f64, Expand);
401 } else if (X86ScalarSSEf32) {
402 // Use SSE for f32, x87 for f64.
403 // Set up the FP register classes.
404 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
405 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
407 // Use ANDPS to simulate FABS.
408 setOperationAction(ISD::FABS , MVT::f32, Custom);
410 // Use XORP to simulate FNEG.
411 setOperationAction(ISD::FNEG , MVT::f32, Custom);
413 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
415 // Use ANDPS and ORPS to simulate FCOPYSIGN.
416 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
417 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
419 // We don't support sin/cos/fmod
420 setOperationAction(ISD::FSIN , MVT::f32, Expand);
421 setOperationAction(ISD::FCOS , MVT::f32, Expand);
423 // Special cases we handle for FP constants.
424 addLegalFPImmediate(APFloat(+0.0f)); // xorps
425 addLegalFPImmediate(APFloat(+0.0)); // FLD0
426 addLegalFPImmediate(APFloat(+1.0)); // FLD1
427 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
428 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
430 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
431 // this though and handle it in InstructionSelectPreprocess so that
432 // dagcombine2 can hack on these.
434 setConvertAction(MVT::f32, MVT::f64, Expand);
435 setConvertAction(MVT::f32, MVT::f80, Expand);
436 setConvertAction(MVT::f80, MVT::f32, Expand);
437 setConvertAction(MVT::f64, MVT::f32, Expand);
438 // And x87->x87 truncations also.
439 setConvertAction(MVT::f80, MVT::f64, Expand);
443 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
444 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
447 // f32 and f64 in x87.
448 // Set up the FP register classes.
449 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
450 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
452 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
453 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
454 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
455 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
457 // Floating truncations go through memory. If optimizing, we lie about
458 // this though and handle it in InstructionSelectPreprocess so that
459 // dagcombine2 can hack on these.
461 setConvertAction(MVT::f80, MVT::f32, Expand);
462 setConvertAction(MVT::f64, MVT::f32, Expand);
463 setConvertAction(MVT::f80, MVT::f64, Expand);
467 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
468 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
470 addLegalFPImmediate(APFloat(+0.0)); // FLD0
471 addLegalFPImmediate(APFloat(+1.0)); // FLD1
472 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
473 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
474 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
475 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
476 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
477 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
480 // Long double always uses X87.
481 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
482 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
483 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
485 APFloat TmpFlt(+0.0);
486 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
487 addLegalFPImmediate(TmpFlt); // FLD0
489 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
490 APFloat TmpFlt2(+1.0);
491 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
492 addLegalFPImmediate(TmpFlt2); // FLD1
493 TmpFlt2.changeSign();
494 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
498 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
499 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
502 // Always use a library call for pow.
503 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
504 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
505 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
507 setOperationAction(ISD::FLOG, MVT::f80, Expand);
508 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
509 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
510 setOperationAction(ISD::FEXP, MVT::f80, Expand);
511 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
513 // First set operation action for all vector types to expand. Then we
514 // will selectively turn on ones that can be effectively codegen'd.
515 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
516 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
517 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
524 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
525 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
527 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
532 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
562 if (Subtarget->hasMMX()) {
563 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
564 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
565 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
566 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
567 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
569 // FIXME: add MMX packed arithmetics
571 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
572 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
573 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
574 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
576 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
577 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
578 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
579 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
581 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
582 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
584 setOperationAction(ISD::AND, MVT::v8i8, Promote);
585 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
586 setOperationAction(ISD::AND, MVT::v4i16, Promote);
587 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
588 setOperationAction(ISD::AND, MVT::v2i32, Promote);
589 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
590 setOperationAction(ISD::AND, MVT::v1i64, Legal);
592 setOperationAction(ISD::OR, MVT::v8i8, Promote);
593 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
594 setOperationAction(ISD::OR, MVT::v4i16, Promote);
595 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
596 setOperationAction(ISD::OR, MVT::v2i32, Promote);
597 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
598 setOperationAction(ISD::OR, MVT::v1i64, Legal);
600 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
601 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
602 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
603 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
604 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
605 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
606 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
608 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
609 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
610 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
611 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
612 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
613 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
614 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
615 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
616 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
620 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
621 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
622 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
624 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
625 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
626 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
627 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
630 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
634 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
637 if (Subtarget->hasSSE1()) {
638 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
640 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
641 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
642 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
643 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
644 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
645 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
646 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
650 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
651 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
654 if (Subtarget->hasSSE2()) {
655 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
656 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
657 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
658 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
659 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
661 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
662 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
663 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
664 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
665 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
666 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
667 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
668 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
669 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
670 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
671 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
672 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
673 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
674 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
675 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
677 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
678 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
679 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
680 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
682 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
684 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
685 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
686 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
688 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
689 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
690 MVT VT = (MVT::SimpleValueType)i;
691 // Do not attempt to custom lower non-power-of-2 vectors
692 if (!isPowerOf2_32(VT.getVectorNumElements()))
694 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
695 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
698 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
699 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
700 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
701 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
703 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
704 if (Subtarget->is64Bit()) {
705 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
706 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
709 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
710 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
711 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
712 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
713 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
714 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
715 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
716 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
717 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
718 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
719 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
720 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
723 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
725 // Custom lower v2i64 and v2f64 selects.
726 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
727 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
728 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
729 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
733 if (Subtarget->hasSSE41()) {
734 // FIXME: Do we need to handle scalar-to-vector here?
735 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
736 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
738 // i8 and i16 vectors are custom , because the source register and source
739 // source memory operand types are not the same width. f32 vectors are
740 // custom since the immediate controlling the insert encodes additional
742 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
743 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
744 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
745 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
747 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
750 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
752 if (Subtarget->is64Bit()) {
753 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
758 if (Subtarget->hasSSE42()) {
759 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
762 // We want to custom lower some of our intrinsics.
763 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
765 // We have target-specific dag combine patterns for the following nodes:
766 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
767 setTargetDAGCombine(ISD::BUILD_VECTOR);
768 setTargetDAGCombine(ISD::SELECT);
769 setTargetDAGCombine(ISD::STORE);
771 computeRegisterProperties();
773 // FIXME: These should be based on subtarget info. Plus, the values should
774 // be smaller when we are in optimizing for size mode.
775 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
776 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
777 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
778 allowUnalignedMemoryAccesses = true; // x86 supports it!
779 setPrefLoopAlignment(16);
783 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
788 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
789 /// the desired ByVal argument alignment.
790 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
793 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
794 if (VTy->getBitWidth() == 128)
796 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
797 unsigned EltAlign = 0;
798 getMaxByValAlign(ATy->getElementType(), EltAlign);
799 if (EltAlign > MaxAlign)
801 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
802 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
803 unsigned EltAlign = 0;
804 getMaxByValAlign(STy->getElementType(i), EltAlign);
805 if (EltAlign > MaxAlign)
814 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
815 /// function arguments in the caller parameter area. For X86, aggregates
816 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
817 /// are at 4-byte boundaries.
818 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
819 if (Subtarget->is64Bit()) {
820 // Max of 8 and alignment of type.
821 unsigned TyAlign = TD->getABITypeAlignment(Ty);
828 if (Subtarget->hasSSE1())
829 getMaxByValAlign(Ty, Align);
833 /// getOptimalMemOpType - Returns the target specific optimal type for load
834 /// and store operations as a result of memset, memcpy, and memmove
835 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
838 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
839 bool isSrcConst, bool isSrcStr) const {
840 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
842 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
844 if (Subtarget->is64Bit() && Size >= 8)
850 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
852 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
853 SelectionDAG &DAG) const {
854 if (usesGlobalOffsetTable())
855 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
856 if (!Subtarget->isPICStyleRIPRel())
857 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
861 //===----------------------------------------------------------------------===//
862 // Return Value Calling Convention Implementation
863 //===----------------------------------------------------------------------===//
865 #include "X86GenCallingConv.inc"
867 /// LowerRET - Lower an ISD::RET node.
868 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
869 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
871 SmallVector<CCValAssign, 16> RVLocs;
872 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
873 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
874 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
875 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
877 // If this is the first return lowered for this function, add the regs to the
878 // liveout set for the function.
879 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
880 for (unsigned i = 0; i != RVLocs.size(); ++i)
881 if (RVLocs[i].isRegLoc())
882 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
884 SDValue Chain = Op.getOperand(0);
886 // Handle tail call return.
887 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
888 if (Chain.getOpcode() == X86ISD::TAILCALL) {
889 SDValue TailCall = Chain;
890 SDValue TargetAddress = TailCall.getOperand(1);
891 SDValue StackAdjustment = TailCall.getOperand(2);
892 assert(((TargetAddress.getOpcode() == ISD::Register &&
893 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
894 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
895 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
896 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
897 "Expecting an global address, external symbol, or register");
898 assert(StackAdjustment.getOpcode() == ISD::Constant &&
899 "Expecting a const value");
901 SmallVector<SDValue,8> Operands;
902 Operands.push_back(Chain.getOperand(0));
903 Operands.push_back(TargetAddress);
904 Operands.push_back(StackAdjustment);
905 // Copy registers used by the call. Last operand is a flag so it is not
907 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
908 Operands.push_back(Chain.getOperand(i));
910 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
917 SmallVector<SDValue, 6> RetOps;
918 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
919 // Operand #1 = Bytes To Pop
920 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
922 // Copy the result values into the output registers.
923 for (unsigned i = 0; i != RVLocs.size(); ++i) {
924 CCValAssign &VA = RVLocs[i];
925 assert(VA.isRegLoc() && "Can only return in registers!");
926 SDValue ValToCopy = Op.getOperand(i*2+1);
928 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
929 // the RET instruction and handled by the FP Stackifier.
930 if (RVLocs[i].getLocReg() == X86::ST0 ||
931 RVLocs[i].getLocReg() == X86::ST1) {
932 // If this is a copy from an xmm register to ST(0), use an FPExtend to
933 // change the value to the FP stack register class.
934 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
935 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
936 RetOps.push_back(ValToCopy);
937 // Don't emit a copytoreg.
941 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
942 Flag = Chain.getValue(1);
945 // The x86-64 ABI for returning structs by value requires that we copy
946 // the sret argument into %rax for the return. We saved the argument into
947 // a virtual register in the entry block, so now we copy the value out
949 if (Subtarget->is64Bit() &&
950 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
951 MachineFunction &MF = DAG.getMachineFunction();
952 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
953 unsigned Reg = FuncInfo->getSRetReturnReg();
955 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
956 FuncInfo->setSRetReturnReg(Reg);
958 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
960 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
961 Flag = Chain.getValue(1);
964 RetOps[0] = Chain; // Update chain.
966 // Add the flag if we have it.
968 RetOps.push_back(Flag);
970 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
974 /// LowerCallResult - Lower the result values of an ISD::CALL into the
975 /// appropriate copies out of appropriate physical registers. This assumes that
976 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
977 /// being lowered. The returns a SDNode with the same number of values as the
979 SDNode *X86TargetLowering::
980 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
981 unsigned CallingConv, SelectionDAG &DAG) {
983 // Assign locations to each value returned by this call.
984 SmallVector<CCValAssign, 16> RVLocs;
985 bool isVarArg = TheCall->isVarArg();
986 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
987 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
989 SmallVector<SDValue, 8> ResultVals;
991 // Copy all of the result registers out of their specified physreg.
992 for (unsigned i = 0; i != RVLocs.size(); ++i) {
993 MVT CopyVT = RVLocs[i].getValVT();
995 // If this is a call to a function that returns an fp value on the floating
996 // point stack, but where we prefer to use the value in xmm registers, copy
997 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
998 if ((RVLocs[i].getLocReg() == X86::ST0 ||
999 RVLocs[i].getLocReg() == X86::ST1) &&
1000 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1004 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1005 CopyVT, InFlag).getValue(1);
1006 SDValue Val = Chain.getValue(0);
1007 InFlag = Chain.getValue(2);
1009 if (CopyVT != RVLocs[i].getValVT()) {
1010 // Round the F80 the right size, which also moves to the appropriate xmm
1012 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1013 // This truncation won't change the value.
1014 DAG.getIntPtrConstant(1));
1017 ResultVals.push_back(Val);
1020 // Merge everything together with a MERGE_VALUES node.
1021 ResultVals.push_back(Chain);
1022 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
1023 ResultVals.size()).getNode();
1027 //===----------------------------------------------------------------------===//
1028 // C & StdCall & Fast Calling Convention implementation
1029 //===----------------------------------------------------------------------===//
1030 // StdCall calling convention seems to be standard for many Windows' API
1031 // routines and around. It differs from C calling convention just a little:
1032 // callee should clean up the stack, not caller. Symbols should be also
1033 // decorated in some fancy way :) It doesn't support any vector arguments.
1034 // For info on fast calling convention see Fast Calling Convention (tail call)
1035 // implementation LowerX86_32FastCCCallTo.
1037 /// AddLiveIn - This helper function adds the specified physical register to the
1038 /// MachineFunction as a live in value. It also creates a corresponding virtual
1039 /// register for it.
1040 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1041 const TargetRegisterClass *RC) {
1042 assert(RC->contains(PReg) && "Not the correct regclass!");
1043 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1044 MF.getRegInfo().addLiveIn(PReg, VReg);
1048 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1050 static bool CallIsStructReturn(CallSDNode *TheCall) {
1051 unsigned NumOps = TheCall->getNumArgs();
1055 return TheCall->getArgFlags(0).isSRet();
1058 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1059 /// return semantics.
1060 static bool ArgsAreStructReturn(SDValue Op) {
1061 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1065 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1068 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1069 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1071 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1075 switch (CallingConv) {
1078 case CallingConv::X86_StdCall:
1079 return !Subtarget->is64Bit();
1080 case CallingConv::X86_FastCall:
1081 return !Subtarget->is64Bit();
1082 case CallingConv::Fast:
1083 return PerformTailCallOpt;
1087 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1088 /// given CallingConvention value.
1089 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1090 if (Subtarget->is64Bit()) {
1091 if (Subtarget->isTargetWin64())
1092 return CC_X86_Win64_C;
1093 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1094 return CC_X86_64_TailCall;
1099 if (CC == CallingConv::X86_FastCall)
1100 return CC_X86_32_FastCall;
1101 else if (CC == CallingConv::Fast)
1102 return CC_X86_32_FastCC;
1107 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1108 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1110 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1111 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1112 if (CC == CallingConv::X86_FastCall)
1114 else if (CC == CallingConv::X86_StdCall)
1120 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1121 /// in a register before calling.
1122 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1123 return !IsTailCall && !Is64Bit &&
1124 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1125 Subtarget->isPICStyleGOT();
1128 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1129 /// address to be loaded in a register.
1131 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1132 return !Is64Bit && IsTailCall &&
1133 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1134 Subtarget->isPICStyleGOT();
1137 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1138 /// by "Src" to address "Dst" with size and alignment information specified by
1139 /// the specific parameter attribute. The copy will be passed as a byval
1140 /// function parameter.
1142 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1143 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1144 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1145 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1146 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1149 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1150 const CCValAssign &VA,
1151 MachineFrameInfo *MFI,
1153 SDValue Root, unsigned i) {
1154 // Create the nodes corresponding to a load from this parameter slot.
1155 ISD::ArgFlagsTy Flags =
1156 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1157 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1158 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1160 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1161 // changed with more analysis.
1162 // In case of tail call optimization mark all arguments mutable. Since they
1163 // could be overwritten by lowering of arguments in case of a tail call.
1164 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1165 VA.getLocMemOffset(), isImmutable);
1166 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1167 if (Flags.isByVal())
1169 return DAG.getLoad(VA.getValVT(), Root, FIN,
1170 PseudoSourceValue::getFixedStack(FI), 0);
1174 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1175 MachineFunction &MF = DAG.getMachineFunction();
1176 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1178 const Function* Fn = MF.getFunction();
1179 if (Fn->hasExternalLinkage() &&
1180 Subtarget->isTargetCygMing() &&
1181 Fn->getName() == "main")
1182 FuncInfo->setForceFramePointer(true);
1184 // Decorate the function name.
1185 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1187 MachineFrameInfo *MFI = MF.getFrameInfo();
1188 SDValue Root = Op.getOperand(0);
1189 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1190 unsigned CC = MF.getFunction()->getCallingConv();
1191 bool Is64Bit = Subtarget->is64Bit();
1192 bool IsWin64 = Subtarget->isTargetWin64();
1194 assert(!(isVarArg && CC == CallingConv::Fast) &&
1195 "Var args not supported with calling convention fastcc");
1197 // Assign locations to all of the incoming arguments.
1198 SmallVector<CCValAssign, 16> ArgLocs;
1199 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1200 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1202 SmallVector<SDValue, 8> ArgValues;
1203 unsigned LastVal = ~0U;
1204 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1205 CCValAssign &VA = ArgLocs[i];
1206 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1208 assert(VA.getValNo() != LastVal &&
1209 "Don't support value assigned to multiple locs yet");
1210 LastVal = VA.getValNo();
1212 if (VA.isRegLoc()) {
1213 MVT RegVT = VA.getLocVT();
1214 TargetRegisterClass *RC;
1215 if (RegVT == MVT::i32)
1216 RC = X86::GR32RegisterClass;
1217 else if (Is64Bit && RegVT == MVT::i64)
1218 RC = X86::GR64RegisterClass;
1219 else if (RegVT == MVT::f32)
1220 RC = X86::FR32RegisterClass;
1221 else if (RegVT == MVT::f64)
1222 RC = X86::FR64RegisterClass;
1223 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1224 RC = X86::VR128RegisterClass;
1225 else if (RegVT.isVector()) {
1226 assert(RegVT.getSizeInBits() == 64);
1228 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1230 // Darwin calling convention passes MMX values in either GPRs or
1231 // XMMs in x86-64. Other targets pass them in memory.
1232 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1233 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1236 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1241 assert(0 && "Unknown argument type!");
1244 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1245 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1247 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1248 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1250 if (VA.getLocInfo() == CCValAssign::SExt)
1251 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1252 DAG.getValueType(VA.getValVT()));
1253 else if (VA.getLocInfo() == CCValAssign::ZExt)
1254 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1255 DAG.getValueType(VA.getValVT()));
1257 if (VA.getLocInfo() != CCValAssign::Full)
1258 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1260 // Handle MMX values passed in GPRs.
1261 if (Is64Bit && RegVT != VA.getLocVT()) {
1262 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1263 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1264 else if (RC == X86::VR128RegisterClass) {
1265 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1266 DAG.getConstant(0, MVT::i64));
1267 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1271 ArgValues.push_back(ArgValue);
1273 assert(VA.isMemLoc());
1274 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1278 // The x86-64 ABI for returning structs by value requires that we copy
1279 // the sret argument into %rax for the return. Save the argument into
1280 // a virtual register so that we can access it from the return points.
1281 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1282 MachineFunction &MF = DAG.getMachineFunction();
1283 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1284 unsigned Reg = FuncInfo->getSRetReturnReg();
1286 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1287 FuncInfo->setSRetReturnReg(Reg);
1289 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1290 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1293 unsigned StackSize = CCInfo.getNextStackOffset();
1294 // align stack specially for tail calls
1295 if (PerformTailCallOpt && CC == CallingConv::Fast)
1296 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1298 // If the function takes variable number of arguments, make a frame index for
1299 // the start of the first vararg value... for expansion of llvm.va_start.
1301 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1302 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1305 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1307 // FIXME: We should really autogenerate these arrays
1308 static const unsigned GPR64ArgRegsWin64[] = {
1309 X86::RCX, X86::RDX, X86::R8, X86::R9
1311 static const unsigned XMMArgRegsWin64[] = {
1312 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1314 static const unsigned GPR64ArgRegs64Bit[] = {
1315 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1317 static const unsigned XMMArgRegs64Bit[] = {
1318 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1319 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1321 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1324 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1325 GPR64ArgRegs = GPR64ArgRegsWin64;
1326 XMMArgRegs = XMMArgRegsWin64;
1328 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1329 GPR64ArgRegs = GPR64ArgRegs64Bit;
1330 XMMArgRegs = XMMArgRegs64Bit;
1332 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1334 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1337 // For X86-64, if there are vararg parameters that are passed via
1338 // registers, then we must store them to their spots on the stack so they
1339 // may be loaded by deferencing the result of va_next.
1340 VarArgsGPOffset = NumIntRegs * 8;
1341 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1342 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1343 TotalNumXMMRegs * 16, 16);
1345 // Store the integer parameter registers.
1346 SmallVector<SDValue, 8> MemOps;
1347 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1348 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1349 DAG.getIntPtrConstant(VarArgsGPOffset));
1350 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1351 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1352 X86::GR64RegisterClass);
1353 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1355 DAG.getStore(Val.getValue(1), Val, FIN,
1356 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1357 MemOps.push_back(Store);
1358 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1359 DAG.getIntPtrConstant(8));
1362 // Now store the XMM (fp + vector) parameter registers.
1363 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1364 DAG.getIntPtrConstant(VarArgsFPOffset));
1365 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1366 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1367 X86::VR128RegisterClass);
1368 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1370 DAG.getStore(Val.getValue(1), Val, FIN,
1371 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1372 MemOps.push_back(Store);
1373 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1374 DAG.getIntPtrConstant(16));
1376 if (!MemOps.empty())
1377 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1378 &MemOps[0], MemOps.size());
1382 ArgValues.push_back(Root);
1384 // Some CCs need callee pop.
1385 if (IsCalleePop(isVarArg, CC)) {
1386 BytesToPopOnReturn = StackSize; // Callee pops everything.
1387 BytesCallerReserves = 0;
1389 BytesToPopOnReturn = 0; // Callee pops nothing.
1390 // If this is an sret function, the return should pop the hidden pointer.
1391 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1392 BytesToPopOnReturn = 4;
1393 BytesCallerReserves = StackSize;
1397 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1398 if (CC == CallingConv::X86_FastCall)
1399 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1402 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1404 // Return the new list of results.
1405 return DAG.getMergeValues(Op.getNode()->getVTList(), &ArgValues[0],
1406 ArgValues.size()).getValue(Op.getResNo());
1410 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1411 const SDValue &StackPtr,
1412 const CCValAssign &VA,
1414 SDValue Arg, ISD::ArgFlagsTy Flags) {
1415 unsigned LocMemOffset = VA.getLocMemOffset();
1416 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1417 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1418 if (Flags.isByVal()) {
1419 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1421 return DAG.getStore(Chain, Arg, PtrOff,
1422 PseudoSourceValue::getStack(), LocMemOffset);
1425 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1426 /// optimization is performed and it is required.
1428 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1429 SDValue &OutRetAddr,
1434 if (!IsTailCall || FPDiff==0) return Chain;
1436 // Adjust the Return address stack slot.
1437 MVT VT = getPointerTy();
1438 OutRetAddr = getReturnAddressFrameIndex(DAG);
1439 // Load the "old" Return address.
1440 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1441 return SDValue(OutRetAddr.getNode(), 1);
1444 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1445 /// optimization is performed and it is required (FPDiff!=0).
1447 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1448 SDValue Chain, SDValue RetAddrFrIdx,
1449 bool Is64Bit, int FPDiff) {
1450 // Store the return address to the appropriate stack slot.
1451 if (!FPDiff) return Chain;
1452 // Calculate the new stack slot for the return address.
1453 int SlotSize = Is64Bit ? 8 : 4;
1454 int NewReturnAddrFI =
1455 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1456 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1457 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1458 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1459 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1463 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1464 MachineFunction &MF = DAG.getMachineFunction();
1465 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1466 SDValue Chain = TheCall->getChain();
1467 unsigned CC = TheCall->getCallingConv();
1468 bool isVarArg = TheCall->isVarArg();
1469 bool IsTailCall = TheCall->isTailCall() &&
1470 CC == CallingConv::Fast && PerformTailCallOpt;
1471 SDValue Callee = TheCall->getCallee();
1472 bool Is64Bit = Subtarget->is64Bit();
1473 bool IsStructRet = CallIsStructReturn(TheCall);
1475 assert(!(isVarArg && CC == CallingConv::Fast) &&
1476 "Var args not supported with calling convention fastcc");
1478 // Analyze operands of the call, assigning locations to each operand.
1479 SmallVector<CCValAssign, 16> ArgLocs;
1480 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1481 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1483 // Get a count of how many bytes are to be pushed on the stack.
1484 unsigned NumBytes = CCInfo.getNextStackOffset();
1485 if (PerformTailCallOpt && CC == CallingConv::Fast)
1486 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1490 // Lower arguments at fp - stackoffset + fpdiff.
1491 unsigned NumBytesCallerPushed =
1492 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1493 FPDiff = NumBytesCallerPushed - NumBytes;
1495 // Set the delta of movement of the returnaddr stackslot.
1496 // But only set if delta is greater than previous delta.
1497 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1498 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1501 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1503 SDValue RetAddrFrIdx;
1504 // Load return adress for tail calls.
1505 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1508 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1509 SmallVector<SDValue, 8> MemOpChains;
1512 // Walk the register/memloc assignments, inserting copies/loads. In the case
1513 // of tail call optimization arguments are handle later.
1514 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1515 CCValAssign &VA = ArgLocs[i];
1516 SDValue Arg = TheCall->getArg(i);
1517 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1518 bool isByVal = Flags.isByVal();
1520 // Promote the value if needed.
1521 switch (VA.getLocInfo()) {
1522 default: assert(0 && "Unknown loc info!");
1523 case CCValAssign::Full: break;
1524 case CCValAssign::SExt:
1525 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1527 case CCValAssign::ZExt:
1528 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1530 case CCValAssign::AExt:
1531 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1535 if (VA.isRegLoc()) {
1537 MVT RegVT = VA.getLocVT();
1538 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1539 switch (VA.getLocReg()) {
1542 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1544 // Special case: passing MMX values in GPR registers.
1545 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1548 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1549 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1550 // Special case: passing MMX values in XMM registers.
1551 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1552 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1553 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1554 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1555 getMOVLMask(2, DAG));
1560 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1562 if (!IsTailCall || (IsTailCall && isByVal)) {
1563 assert(VA.isMemLoc());
1564 if (StackPtr.getNode() == 0)
1565 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1567 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1568 Chain, Arg, Flags));
1573 if (!MemOpChains.empty())
1574 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1575 &MemOpChains[0], MemOpChains.size());
1577 // Build a sequence of copy-to-reg nodes chained together with token chain
1578 // and flag operands which copy the outgoing args into registers.
1580 // Tail call byval lowering might overwrite argument registers so in case of
1581 // tail call optimization the copies to registers are lowered later.
1583 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1584 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1586 InFlag = Chain.getValue(1);
1589 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1591 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1592 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1593 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1595 InFlag = Chain.getValue(1);
1597 // If we are tail calling and generating PIC/GOT style code load the address
1598 // of the callee into ecx. The value in ecx is used as target of the tail
1599 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1600 // calls on PIC/GOT architectures. Normally we would just put the address of
1601 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1602 // restored (since ebx is callee saved) before jumping to the target@PLT.
1603 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1604 // Note: The actual moving to ecx is done further down.
1605 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1606 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1607 !G->getGlobal()->hasProtectedVisibility())
1608 Callee = LowerGlobalAddress(Callee, DAG);
1609 else if (isa<ExternalSymbolSDNode>(Callee))
1610 Callee = LowerExternalSymbol(Callee,DAG);
1613 if (Is64Bit && isVarArg) {
1614 // From AMD64 ABI document:
1615 // For calls that may call functions that use varargs or stdargs
1616 // (prototype-less calls or calls to functions containing ellipsis (...) in
1617 // the declaration) %al is used as hidden argument to specify the number
1618 // of SSE registers used. The contents of %al do not need to match exactly
1619 // the number of registers, but must be an ubound on the number of SSE
1620 // registers used and is in the range 0 - 8 inclusive.
1622 // FIXME: Verify this on Win64
1623 // Count the number of XMM registers allocated.
1624 static const unsigned XMMArgRegs[] = {
1625 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1626 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1628 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1630 Chain = DAG.getCopyToReg(Chain, X86::AL,
1631 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1632 InFlag = Chain.getValue(1);
1636 // For tail calls lower the arguments to the 'real' stack slot.
1638 SmallVector<SDValue, 8> MemOpChains2;
1641 // Do not flag preceeding copytoreg stuff together with the following stuff.
1643 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1644 CCValAssign &VA = ArgLocs[i];
1645 if (!VA.isRegLoc()) {
1646 assert(VA.isMemLoc());
1647 SDValue Arg = TheCall->getArg(i);
1648 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1649 // Create frame index.
1650 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1651 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1652 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1653 FIN = DAG.getFrameIndex(FI, getPointerTy());
1655 if (Flags.isByVal()) {
1656 // Copy relative to framepointer.
1657 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1658 if (StackPtr.getNode() == 0)
1659 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1660 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1662 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1665 // Store relative to framepointer.
1666 MemOpChains2.push_back(
1667 DAG.getStore(Chain, Arg, FIN,
1668 PseudoSourceValue::getFixedStack(FI), 0));
1673 if (!MemOpChains2.empty())
1674 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1675 &MemOpChains2[0], MemOpChains2.size());
1677 // Copy arguments to their registers.
1678 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1679 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1681 InFlag = Chain.getValue(1);
1685 // Store the return address to the appropriate stack slot.
1686 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1690 // If the callee is a GlobalAddress node (quite common, every direct call is)
1691 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1692 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1693 // We should use extra load for direct calls to dllimported functions in
1695 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1696 getTargetMachine(), true))
1697 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1698 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1699 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1700 } else if (IsTailCall) {
1701 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1703 Chain = DAG.getCopyToReg(Chain,
1704 DAG.getRegister(Opc, getPointerTy()),
1706 Callee = DAG.getRegister(Opc, getPointerTy());
1707 // Add register as live out.
1708 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1711 // Returns a chain & a flag for retval copy to use.
1712 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1713 SmallVector<SDValue, 8> Ops;
1716 Ops.push_back(Chain);
1717 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1718 Ops.push_back(DAG.getIntPtrConstant(0));
1719 if (InFlag.getNode())
1720 Ops.push_back(InFlag);
1721 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1722 InFlag = Chain.getValue(1);
1724 // Returns a chain & a flag for retval copy to use.
1725 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1729 Ops.push_back(Chain);
1730 Ops.push_back(Callee);
1733 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1735 // Add argument registers to the end of the list so that they are known live
1737 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1738 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1739 RegsToPass[i].second.getValueType()));
1741 // Add an implicit use GOT pointer in EBX.
1742 if (!IsTailCall && !Is64Bit &&
1743 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1744 Subtarget->isPICStyleGOT())
1745 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1747 // Add an implicit use of AL for x86 vararg functions.
1748 if (Is64Bit && isVarArg)
1749 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1751 if (InFlag.getNode())
1752 Ops.push_back(InFlag);
1755 assert(InFlag.getNode() &&
1756 "Flag must be set. Depend on flag being set in LowerRET");
1757 Chain = DAG.getNode(X86ISD::TAILCALL,
1758 TheCall->getVTList(), &Ops[0], Ops.size());
1760 return SDValue(Chain.getNode(), Op.getResNo());
1763 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1764 InFlag = Chain.getValue(1);
1766 // Create the CALLSEQ_END node.
1767 unsigned NumBytesForCalleeToPush;
1768 if (IsCalleePop(isVarArg, CC))
1769 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1770 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1771 // If this is is a call to a struct-return function, the callee
1772 // pops the hidden struct pointer, so we have to push it back.
1773 // This is common for Darwin/X86, Linux & Mingw32 targets.
1774 NumBytesForCalleeToPush = 4;
1776 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1778 // Returns a flag for retval copy to use.
1779 Chain = DAG.getCALLSEQ_END(Chain,
1780 DAG.getIntPtrConstant(NumBytes),
1781 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1783 InFlag = Chain.getValue(1);
1785 // Handle result values, copying them out of physregs into vregs that we
1787 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1792 //===----------------------------------------------------------------------===//
1793 // Fast Calling Convention (tail call) implementation
1794 //===----------------------------------------------------------------------===//
1796 // Like std call, callee cleans arguments, convention except that ECX is
1797 // reserved for storing the tail called function address. Only 2 registers are
1798 // free for argument passing (inreg). Tail call optimization is performed
1800 // * tailcallopt is enabled
1801 // * caller/callee are fastcc
1802 // On X86_64 architecture with GOT-style position independent code only local
1803 // (within module) calls are supported at the moment.
1804 // To keep the stack aligned according to platform abi the function
1805 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1806 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1807 // If a tail called function callee has more arguments than the caller the
1808 // caller needs to make sure that there is room to move the RETADDR to. This is
1809 // achieved by reserving an area the size of the argument delta right after the
1810 // original REtADDR, but before the saved framepointer or the spilled registers
1811 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1823 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1824 /// for a 16 byte align requirement.
1825 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1826 SelectionDAG& DAG) {
1827 MachineFunction &MF = DAG.getMachineFunction();
1828 const TargetMachine &TM = MF.getTarget();
1829 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1830 unsigned StackAlignment = TFI.getStackAlignment();
1831 uint64_t AlignMask = StackAlignment - 1;
1832 int64_t Offset = StackSize;
1833 uint64_t SlotSize = TD->getPointerSize();
1834 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1835 // Number smaller than 12 so just add the difference.
1836 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1838 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1839 Offset = ((~AlignMask) & Offset) + StackAlignment +
1840 (StackAlignment-SlotSize);
1845 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1846 /// following the call is a return. A function is eligible if caller/callee
1847 /// calling conventions match, currently only fastcc supports tail calls, and
1848 /// the function CALL is immediatly followed by a RET.
1849 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1851 SelectionDAG& DAG) const {
1852 if (!PerformTailCallOpt)
1855 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1856 MachineFunction &MF = DAG.getMachineFunction();
1857 unsigned CallerCC = MF.getFunction()->getCallingConv();
1858 unsigned CalleeCC= TheCall->getCallingConv();
1859 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1860 SDValue Callee = TheCall->getCallee();
1861 // On x86/32Bit PIC/GOT tail calls are supported.
1862 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1863 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1866 // Can only do local tail calls (in same module, hidden or protected) on
1867 // x86_64 PIC/GOT at the moment.
1868 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1869 return G->getGlobal()->hasHiddenVisibility()
1870 || G->getGlobal()->hasProtectedVisibility();
1878 X86TargetLowering::createFastISel(MachineFunction &mf,
1879 MachineModuleInfo *mmo,
1880 DenseMap<const Value *, unsigned> &vm,
1881 DenseMap<const BasicBlock *,
1882 MachineBasicBlock *> &bm,
1883 DenseMap<const AllocaInst *, int> &am) {
1885 return X86::createFastISel(mf, mmo, vm, bm, am);
1889 //===----------------------------------------------------------------------===//
1890 // Other Lowering Hooks
1891 //===----------------------------------------------------------------------===//
1894 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1895 MachineFunction &MF = DAG.getMachineFunction();
1896 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1897 int ReturnAddrIndex = FuncInfo->getRAIndex();
1898 uint64_t SlotSize = TD->getPointerSize();
1900 if (ReturnAddrIndex == 0) {
1901 // Set up a frame object for the return address.
1902 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1903 FuncInfo->setRAIndex(ReturnAddrIndex);
1906 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1910 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1911 /// specific condition code. It returns a false if it cannot do a direct
1912 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1914 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1915 unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1916 SelectionDAG &DAG) {
1917 X86CC = X86::COND_INVALID;
1919 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1920 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1921 // X > -1 -> X == 0, jump !sign.
1922 RHS = DAG.getConstant(0, RHS.getValueType());
1923 X86CC = X86::COND_NS;
1925 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1926 // X < 0 -> X == 0, jump on sign.
1927 X86CC = X86::COND_S;
1929 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1931 RHS = DAG.getConstant(0, RHS.getValueType());
1932 X86CC = X86::COND_LE;
1937 switch (SetCCOpcode) {
1939 case ISD::SETEQ: X86CC = X86::COND_E; break;
1940 case ISD::SETGT: X86CC = X86::COND_G; break;
1941 case ISD::SETGE: X86CC = X86::COND_GE; break;
1942 case ISD::SETLT: X86CC = X86::COND_L; break;
1943 case ISD::SETLE: X86CC = X86::COND_LE; break;
1944 case ISD::SETNE: X86CC = X86::COND_NE; break;
1945 case ISD::SETULT: X86CC = X86::COND_B; break;
1946 case ISD::SETUGT: X86CC = X86::COND_A; break;
1947 case ISD::SETULE: X86CC = X86::COND_BE; break;
1948 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1951 // First determine if it requires or is profitable to flip the operands.
1953 switch (SetCCOpcode) {
1963 // If LHS is a foldable load, but RHS is not, flip the condition.
1965 (ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
1966 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
1967 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1971 std::swap(LHS, RHS);
1973 // On a floating point condition, the flags are set as follows:
1975 // 0 | 0 | 0 | X > Y
1976 // 0 | 0 | 1 | X < Y
1977 // 1 | 0 | 0 | X == Y
1978 // 1 | 1 | 1 | unordered
1979 switch (SetCCOpcode) {
1983 X86CC = X86::COND_E;
1985 case ISD::SETOLT: // flipped
1988 X86CC = X86::COND_A;
1990 case ISD::SETOLE: // flipped
1993 X86CC = X86::COND_AE;
1995 case ISD::SETUGT: // flipped
1998 X86CC = X86::COND_B;
2000 case ISD::SETUGE: // flipped
2003 X86CC = X86::COND_BE;
2007 X86CC = X86::COND_NE;
2010 X86CC = X86::COND_P;
2013 X86CC = X86::COND_NP;
2018 return X86CC != X86::COND_INVALID;
2021 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2022 /// code. Current x86 isa includes the following FP cmov instructions:
2023 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2024 static bool hasFPCMov(unsigned X86CC) {
2040 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2041 /// true if Op is undef or if its value falls within the specified range (L, H].
2042 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2043 if (Op.getOpcode() == ISD::UNDEF)
2046 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2047 return (Val >= Low && Val < Hi);
2050 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2051 /// true if Op is undef or if its value equal to the specified value.
2052 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2053 if (Op.getOpcode() == ISD::UNDEF)
2055 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2058 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2059 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2060 bool X86::isPSHUFDMask(SDNode *N) {
2061 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2063 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2066 // Check if the value doesn't reference the second vector.
2067 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2068 SDValue Arg = N->getOperand(i);
2069 if (Arg.getOpcode() == ISD::UNDEF) continue;
2070 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2071 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2078 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2079 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2080 bool X86::isPSHUFHWMask(SDNode *N) {
2081 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2083 if (N->getNumOperands() != 8)
2086 // Lower quadword copied in order.
2087 for (unsigned i = 0; i != 4; ++i) {
2088 SDValue Arg = N->getOperand(i);
2089 if (Arg.getOpcode() == ISD::UNDEF) continue;
2090 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2091 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2095 // Upper quadword shuffled.
2096 for (unsigned i = 4; i != 8; ++i) {
2097 SDValue Arg = N->getOperand(i);
2098 if (Arg.getOpcode() == ISD::UNDEF) continue;
2099 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2100 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2101 if (Val < 4 || Val > 7)
2108 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2109 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2110 bool X86::isPSHUFLWMask(SDNode *N) {
2111 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2113 if (N->getNumOperands() != 8)
2116 // Upper quadword copied in order.
2117 for (unsigned i = 4; i != 8; ++i)
2118 if (!isUndefOrEqual(N->getOperand(i), i))
2121 // Lower quadword shuffled.
2122 for (unsigned i = 0; i != 4; ++i)
2123 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2129 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2130 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2131 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2132 if (NumElems != 2 && NumElems != 4) return false;
2134 unsigned Half = NumElems / 2;
2135 for (unsigned i = 0; i < Half; ++i)
2136 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2138 for (unsigned i = Half; i < NumElems; ++i)
2139 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2145 bool X86::isSHUFPMask(SDNode *N) {
2146 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2147 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2150 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2151 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2152 /// half elements to come from vector 1 (which would equal the dest.) and
2153 /// the upper half to come from vector 2.
2154 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2155 if (NumOps != 2 && NumOps != 4) return false;
2157 unsigned Half = NumOps / 2;
2158 for (unsigned i = 0; i < Half; ++i)
2159 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2161 for (unsigned i = Half; i < NumOps; ++i)
2162 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2167 static bool isCommutedSHUFP(SDNode *N) {
2168 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2169 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2172 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2173 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2174 bool X86::isMOVHLPSMask(SDNode *N) {
2175 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2177 if (N->getNumOperands() != 4)
2180 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2181 return isUndefOrEqual(N->getOperand(0), 6) &&
2182 isUndefOrEqual(N->getOperand(1), 7) &&
2183 isUndefOrEqual(N->getOperand(2), 2) &&
2184 isUndefOrEqual(N->getOperand(3), 3);
2187 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2188 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2190 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2191 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2193 if (N->getNumOperands() != 4)
2196 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2197 return isUndefOrEqual(N->getOperand(0), 2) &&
2198 isUndefOrEqual(N->getOperand(1), 3) &&
2199 isUndefOrEqual(N->getOperand(2), 2) &&
2200 isUndefOrEqual(N->getOperand(3), 3);
2203 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2204 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2205 bool X86::isMOVLPMask(SDNode *N) {
2206 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2208 unsigned NumElems = N->getNumOperands();
2209 if (NumElems != 2 && NumElems != 4)
2212 for (unsigned i = 0; i < NumElems/2; ++i)
2213 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2216 for (unsigned i = NumElems/2; i < NumElems; ++i)
2217 if (!isUndefOrEqual(N->getOperand(i), i))
2223 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2224 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2226 bool X86::isMOVHPMask(SDNode *N) {
2227 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2229 unsigned NumElems = N->getNumOperands();
2230 if (NumElems != 2 && NumElems != 4)
2233 for (unsigned i = 0; i < NumElems/2; ++i)
2234 if (!isUndefOrEqual(N->getOperand(i), i))
2237 for (unsigned i = 0; i < NumElems/2; ++i) {
2238 SDValue Arg = N->getOperand(i + NumElems/2);
2239 if (!isUndefOrEqual(Arg, i + NumElems))
2246 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2247 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2248 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2249 bool V2IsSplat = false) {
2250 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2253 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2254 SDValue BitI = Elts[i];
2255 SDValue BitI1 = Elts[i+1];
2256 if (!isUndefOrEqual(BitI, j))
2259 if (isUndefOrEqual(BitI1, NumElts))
2262 if (!isUndefOrEqual(BitI1, j + NumElts))
2270 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2271 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2272 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2275 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2276 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2277 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2278 bool V2IsSplat = false) {
2279 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2282 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2283 SDValue BitI = Elts[i];
2284 SDValue BitI1 = Elts[i+1];
2285 if (!isUndefOrEqual(BitI, j + NumElts/2))
2288 if (isUndefOrEqual(BitI1, NumElts))
2291 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2299 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2300 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2301 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2304 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2305 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2307 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2308 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2310 unsigned NumElems = N->getNumOperands();
2311 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2314 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2315 SDValue BitI = N->getOperand(i);
2316 SDValue BitI1 = N->getOperand(i+1);
2318 if (!isUndefOrEqual(BitI, j))
2320 if (!isUndefOrEqual(BitI1, j))
2327 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2328 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2330 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2331 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2333 unsigned NumElems = N->getNumOperands();
2334 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2337 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2338 SDValue BitI = N->getOperand(i);
2339 SDValue BitI1 = N->getOperand(i + 1);
2341 if (!isUndefOrEqual(BitI, j))
2343 if (!isUndefOrEqual(BitI1, j))
2350 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2351 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2352 /// MOVSD, and MOVD, i.e. setting the lowest element.
2353 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2354 if (NumElts != 2 && NumElts != 4)
2357 if (!isUndefOrEqual(Elts[0], NumElts))
2360 for (unsigned i = 1; i < NumElts; ++i) {
2361 if (!isUndefOrEqual(Elts[i], i))
2368 bool X86::isMOVLMask(SDNode *N) {
2369 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2370 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2373 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2374 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2375 /// element of vector 2 and the other elements to come from vector 1 in order.
2376 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2377 bool V2IsSplat = false,
2378 bool V2IsUndef = false) {
2379 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2382 if (!isUndefOrEqual(Ops[0], 0))
2385 for (unsigned i = 1; i < NumOps; ++i) {
2386 SDValue Arg = Ops[i];
2387 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2388 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2389 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2396 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2397 bool V2IsUndef = false) {
2398 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2399 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2400 V2IsSplat, V2IsUndef);
2403 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2404 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2405 bool X86::isMOVSHDUPMask(SDNode *N) {
2406 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2408 if (N->getNumOperands() != 4)
2411 // Expect 1, 1, 3, 3
2412 for (unsigned i = 0; i < 2; ++i) {
2413 SDValue Arg = N->getOperand(i);
2414 if (Arg.getOpcode() == ISD::UNDEF) continue;
2415 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2416 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2417 if (Val != 1) return false;
2421 for (unsigned i = 2; i < 4; ++i) {
2422 SDValue Arg = N->getOperand(i);
2423 if (Arg.getOpcode() == ISD::UNDEF) continue;
2424 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2425 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2426 if (Val != 3) return false;
2430 // Don't use movshdup if it can be done with a shufps.
2434 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2435 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2436 bool X86::isMOVSLDUPMask(SDNode *N) {
2437 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2439 if (N->getNumOperands() != 4)
2442 // Expect 0, 0, 2, 2
2443 for (unsigned i = 0; i < 2; ++i) {
2444 SDValue Arg = N->getOperand(i);
2445 if (Arg.getOpcode() == ISD::UNDEF) continue;
2446 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2447 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2448 if (Val != 0) return false;
2452 for (unsigned i = 2; i < 4; ++i) {
2453 SDValue Arg = N->getOperand(i);
2454 if (Arg.getOpcode() == ISD::UNDEF) continue;
2455 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2456 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2457 if (Val != 2) return false;
2461 // Don't use movshdup if it can be done with a shufps.
2465 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2466 /// specifies a identity operation on the LHS or RHS.
2467 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2468 unsigned NumElems = N->getNumOperands();
2469 for (unsigned i = 0; i < NumElems; ++i)
2470 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2475 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2476 /// a splat of a single element.
2477 static bool isSplatMask(SDNode *N) {
2478 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2480 // This is a splat operation if each element of the permute is the same, and
2481 // if the value doesn't reference the second vector.
2482 unsigned NumElems = N->getNumOperands();
2483 SDValue ElementBase;
2485 for (; i != NumElems; ++i) {
2486 SDValue Elt = N->getOperand(i);
2487 if (isa<ConstantSDNode>(Elt)) {
2493 if (!ElementBase.getNode())
2496 for (; i != NumElems; ++i) {
2497 SDValue Arg = N->getOperand(i);
2498 if (Arg.getOpcode() == ISD::UNDEF) continue;
2499 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2500 if (Arg != ElementBase) return false;
2503 // Make sure it is a splat of the first vector operand.
2504 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2507 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2508 /// a splat of a single element and it's a 2 or 4 element mask.
2509 bool X86::isSplatMask(SDNode *N) {
2510 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2512 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2513 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2515 return ::isSplatMask(N);
2518 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2519 /// specifies a splat of zero element.
2520 bool X86::isSplatLoMask(SDNode *N) {
2521 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2523 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2524 if (!isUndefOrEqual(N->getOperand(i), 0))
2529 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2530 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2531 bool X86::isMOVDDUPMask(SDNode *N) {
2532 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2534 unsigned e = N->getNumOperands() / 2;
2535 for (unsigned i = 0; i < e; ++i)
2536 if (!isUndefOrEqual(N->getOperand(i), i))
2538 for (unsigned i = 0; i < e; ++i)
2539 if (!isUndefOrEqual(N->getOperand(e+i), i))
2544 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2545 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2547 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2548 unsigned NumOperands = N->getNumOperands();
2549 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2551 for (unsigned i = 0; i < NumOperands; ++i) {
2553 SDValue Arg = N->getOperand(NumOperands-i-1);
2554 if (Arg.getOpcode() != ISD::UNDEF)
2555 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2556 if (Val >= NumOperands) Val -= NumOperands;
2558 if (i != NumOperands - 1)
2565 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2566 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2568 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2570 // 8 nodes, but we only care about the last 4.
2571 for (unsigned i = 7; i >= 4; --i) {
2573 SDValue Arg = N->getOperand(i);
2574 if (Arg.getOpcode() != ISD::UNDEF)
2575 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2584 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2585 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2587 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2589 // 8 nodes, but we only care about the first 4.
2590 for (int i = 3; i >= 0; --i) {
2592 SDValue Arg = N->getOperand(i);
2593 if (Arg.getOpcode() != ISD::UNDEF)
2594 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2603 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2604 /// specifies a 8 element shuffle that can be broken into a pair of
2605 /// PSHUFHW and PSHUFLW.
2606 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2607 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2609 if (N->getNumOperands() != 8)
2612 // Lower quadword shuffled.
2613 for (unsigned i = 0; i != 4; ++i) {
2614 SDValue Arg = N->getOperand(i);
2615 if (Arg.getOpcode() == ISD::UNDEF) continue;
2616 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2617 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2622 // Upper quadword shuffled.
2623 for (unsigned i = 4; i != 8; ++i) {
2624 SDValue Arg = N->getOperand(i);
2625 if (Arg.getOpcode() == ISD::UNDEF) continue;
2626 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2627 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2628 if (Val < 4 || Val > 7)
2635 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2636 /// values in ther permute mask.
2637 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2638 SDValue &V2, SDValue &Mask,
2639 SelectionDAG &DAG) {
2640 MVT VT = Op.getValueType();
2641 MVT MaskVT = Mask.getValueType();
2642 MVT EltVT = MaskVT.getVectorElementType();
2643 unsigned NumElems = Mask.getNumOperands();
2644 SmallVector<SDValue, 8> MaskVec;
2646 for (unsigned i = 0; i != NumElems; ++i) {
2647 SDValue Arg = Mask.getOperand(i);
2648 if (Arg.getOpcode() == ISD::UNDEF) {
2649 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2652 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2653 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2655 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2657 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2661 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2662 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2665 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2666 /// the two vector operands have swapped position.
2668 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2669 MVT MaskVT = Mask.getValueType();
2670 MVT EltVT = MaskVT.getVectorElementType();
2671 unsigned NumElems = Mask.getNumOperands();
2672 SmallVector<SDValue, 8> MaskVec;
2673 for (unsigned i = 0; i != NumElems; ++i) {
2674 SDValue Arg = Mask.getOperand(i);
2675 if (Arg.getOpcode() == ISD::UNDEF) {
2676 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2679 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2680 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2682 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2684 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2686 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2690 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2691 /// match movhlps. The lower half elements should come from upper half of
2692 /// V1 (and in order), and the upper half elements should come from the upper
2693 /// half of V2 (and in order).
2694 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2695 unsigned NumElems = Mask->getNumOperands();
2698 for (unsigned i = 0, e = 2; i != e; ++i)
2699 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2701 for (unsigned i = 2; i != 4; ++i)
2702 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2707 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2708 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2710 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2711 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2713 N = N->getOperand(0).getNode();
2714 if (!ISD::isNON_EXTLoad(N))
2717 *LD = cast<LoadSDNode>(N);
2721 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2722 /// match movlp{s|d}. The lower half elements should come from lower half of
2723 /// V1 (and in order), and the upper half elements should come from the upper
2724 /// half of V2 (and in order). And since V1 will become the source of the
2725 /// MOVLP, it must be either a vector load or a scalar load to vector.
2726 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2727 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2729 // Is V2 is a vector load, don't do this transformation. We will try to use
2730 // load folding shufps op.
2731 if (ISD::isNON_EXTLoad(V2))
2734 unsigned NumElems = Mask->getNumOperands();
2735 if (NumElems != 2 && NumElems != 4)
2737 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2738 if (!isUndefOrEqual(Mask->getOperand(i), i))
2740 for (unsigned i = NumElems/2; i != NumElems; ++i)
2741 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2746 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2748 static bool isSplatVector(SDNode *N) {
2749 if (N->getOpcode() != ISD::BUILD_VECTOR)
2752 SDValue SplatValue = N->getOperand(0);
2753 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2754 if (N->getOperand(i) != SplatValue)
2759 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2761 static bool isUndefShuffle(SDNode *N) {
2762 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2765 SDValue V1 = N->getOperand(0);
2766 SDValue V2 = N->getOperand(1);
2767 SDValue Mask = N->getOperand(2);
2768 unsigned NumElems = Mask.getNumOperands();
2769 for (unsigned i = 0; i != NumElems; ++i) {
2770 SDValue Arg = Mask.getOperand(i);
2771 if (Arg.getOpcode() != ISD::UNDEF) {
2772 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2773 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2775 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2782 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2784 static inline bool isZeroNode(SDValue Elt) {
2785 return ((isa<ConstantSDNode>(Elt) &&
2786 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2787 (isa<ConstantFPSDNode>(Elt) &&
2788 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2791 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2792 /// to an zero vector.
2793 static bool isZeroShuffle(SDNode *N) {
2794 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2797 SDValue V1 = N->getOperand(0);
2798 SDValue V2 = N->getOperand(1);
2799 SDValue Mask = N->getOperand(2);
2800 unsigned NumElems = Mask.getNumOperands();
2801 for (unsigned i = 0; i != NumElems; ++i) {
2802 SDValue Arg = Mask.getOperand(i);
2803 if (Arg.getOpcode() == ISD::UNDEF)
2806 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2807 if (Idx < NumElems) {
2808 unsigned Opc = V1.getNode()->getOpcode();
2809 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2811 if (Opc != ISD::BUILD_VECTOR ||
2812 !isZeroNode(V1.getNode()->getOperand(Idx)))
2814 } else if (Idx >= NumElems) {
2815 unsigned Opc = V2.getNode()->getOpcode();
2816 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2818 if (Opc != ISD::BUILD_VECTOR ||
2819 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2826 /// getZeroVector - Returns a vector of specified type with all zero elements.
2828 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2829 assert(VT.isVector() && "Expected a vector type");
2831 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2832 // type. This ensures they get CSE'd.
2834 if (VT.getSizeInBits() == 64) { // MMX
2835 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2836 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2837 } else if (HasSSE2) { // SSE2
2838 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2839 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2841 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2842 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2844 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2847 /// getOnesVector - Returns a vector of specified type with all bits set.
2849 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2850 assert(VT.isVector() && "Expected a vector type");
2852 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2853 // type. This ensures they get CSE'd.
2854 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2856 if (VT.getSizeInBits() == 64) // MMX
2857 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2859 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2860 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2864 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2865 /// that point to V2 points to its first element.
2866 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2867 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2869 bool Changed = false;
2870 SmallVector<SDValue, 8> MaskVec;
2871 unsigned NumElems = Mask.getNumOperands();
2872 for (unsigned i = 0; i != NumElems; ++i) {
2873 SDValue Arg = Mask.getOperand(i);
2874 if (Arg.getOpcode() != ISD::UNDEF) {
2875 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2876 if (Val > NumElems) {
2877 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2881 MaskVec.push_back(Arg);
2885 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2886 &MaskVec[0], MaskVec.size());
2890 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2891 /// operation of specified width.
2892 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2893 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2894 MVT BaseVT = MaskVT.getVectorElementType();
2896 SmallVector<SDValue, 8> MaskVec;
2897 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2898 for (unsigned i = 1; i != NumElems; ++i)
2899 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2900 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2903 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2904 /// of specified width.
2905 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2906 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2907 MVT BaseVT = MaskVT.getVectorElementType();
2908 SmallVector<SDValue, 8> MaskVec;
2909 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2910 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2911 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2913 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2916 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2917 /// of specified width.
2918 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2919 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2920 MVT BaseVT = MaskVT.getVectorElementType();
2921 unsigned Half = NumElems/2;
2922 SmallVector<SDValue, 8> MaskVec;
2923 for (unsigned i = 0; i != Half; ++i) {
2924 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2925 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2927 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2930 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2931 /// element #0 of a vector with the specified index, leaving the rest of the
2932 /// elements in place.
2933 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2934 SelectionDAG &DAG) {
2935 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2936 MVT BaseVT = MaskVT.getVectorElementType();
2937 SmallVector<SDValue, 8> MaskVec;
2938 // Element #0 of the result gets the elt we are replacing.
2939 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2940 for (unsigned i = 1; i != NumElems; ++i)
2941 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2942 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2945 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2946 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2947 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2948 MVT VT = Op.getValueType();
2951 SDValue V1 = Op.getOperand(0);
2952 SDValue Mask = Op.getOperand(2);
2953 unsigned NumElems = Mask.getNumOperands();
2954 // Special handling of v4f32 -> v4i32.
2955 if (VT != MVT::v4f32) {
2956 Mask = getUnpacklMask(NumElems, DAG);
2957 while (NumElems > 4) {
2958 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2961 Mask = getZeroVector(MVT::v4i32, true, DAG);
2964 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2965 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2966 DAG.getNode(ISD::UNDEF, PVT), Mask);
2967 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2970 /// isVectorLoad - Returns true if the node is a vector load, a scalar
2971 /// load that's promoted to vector, or a load bitcasted.
2972 static bool isVectorLoad(SDValue Op) {
2973 assert(Op.getValueType().isVector() && "Expected a vector type");
2974 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
2975 Op.getOpcode() == ISD::BIT_CONVERT) {
2976 return isa<LoadSDNode>(Op.getOperand(0));
2978 return isa<LoadSDNode>(Op);
2982 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
2984 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
2985 SelectionDAG &DAG, bool HasSSE3) {
2986 // If we have sse3 and shuffle has more than one use or input is a load, then
2987 // use movddup. Otherwise, use movlhps.
2988 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
2989 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
2990 MVT VT = Op.getValueType();
2993 unsigned NumElems = PVT.getVectorNumElements();
2994 if (NumElems == 2) {
2995 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2996 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2998 assert(NumElems == 4);
2999 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3000 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3001 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
3004 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3005 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3006 DAG.getNode(ISD::UNDEF, PVT), Mask);
3007 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3010 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3011 /// vector of zero or undef vector. This produces a shuffle where the low
3012 /// element of V2 is swizzled into the zero/undef vector, landing at element
3013 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3014 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3015 bool isZero, bool HasSSE2,
3016 SelectionDAG &DAG) {
3017 MVT VT = V2.getValueType();
3019 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
3020 unsigned NumElems = V2.getValueType().getVectorNumElements();
3021 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3022 MVT EVT = MaskVT.getVectorElementType();
3023 SmallVector<SDValue, 16> MaskVec;
3024 for (unsigned i = 0; i != NumElems; ++i)
3025 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3026 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3028 MaskVec.push_back(DAG.getConstant(i, EVT));
3029 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3030 &MaskVec[0], MaskVec.size());
3031 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3034 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3035 /// a shuffle that is zero.
3037 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3038 unsigned NumElems, bool Low,
3039 SelectionDAG &DAG) {
3040 unsigned NumZeros = 0;
3041 for (unsigned i = 0; i < NumElems; ++i) {
3042 unsigned Index = Low ? i : NumElems-i-1;
3043 SDValue Idx = Mask.getOperand(Index);
3044 if (Idx.getOpcode() == ISD::UNDEF) {
3048 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3049 if (Elt.getNode() && isZeroNode(Elt))
3057 /// isVectorShift - Returns true if the shuffle can be implemented as a
3058 /// logical left or right shift of a vector.
3059 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3060 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3061 unsigned NumElems = Mask.getNumOperands();
3064 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3067 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3072 bool SeenV1 = false;
3073 bool SeenV2 = false;
3074 for (unsigned i = NumZeros; i < NumElems; ++i) {
3075 unsigned Val = isLeft ? (i - NumZeros) : i;
3076 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3077 if (Idx.getOpcode() == ISD::UNDEF)
3079 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3080 if (Index < NumElems)
3089 if (SeenV1 && SeenV2)
3092 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3098 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3100 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3101 unsigned NumNonZero, unsigned NumZero,
3102 SelectionDAG &DAG, TargetLowering &TLI) {
3108 for (unsigned i = 0; i < 16; ++i) {
3109 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3110 if (ThisIsNonZero && First) {
3112 V = getZeroVector(MVT::v8i16, true, DAG);
3114 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3119 SDValue ThisElt(0, 0), LastElt(0, 0);
3120 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3121 if (LastIsNonZero) {
3122 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3124 if (ThisIsNonZero) {
3125 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3126 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3127 ThisElt, DAG.getConstant(8, MVT::i8));
3129 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3133 if (ThisElt.getNode())
3134 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3135 DAG.getIntPtrConstant(i/2));
3139 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3142 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3144 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3145 unsigned NumNonZero, unsigned NumZero,
3146 SelectionDAG &DAG, TargetLowering &TLI) {
3152 for (unsigned i = 0; i < 8; ++i) {
3153 bool isNonZero = (NonZeros & (1 << i)) != 0;
3157 V = getZeroVector(MVT::v8i16, true, DAG);
3159 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3162 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3163 DAG.getIntPtrConstant(i));
3170 /// getVShift - Return a vector logical shift node.
3172 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3173 unsigned NumBits, SelectionDAG &DAG,
3174 const TargetLowering &TLI) {
3175 bool isMMX = VT.getSizeInBits() == 64;
3176 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3177 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3178 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3179 return DAG.getNode(ISD::BIT_CONVERT, VT,
3180 DAG.getNode(Opc, ShVT, SrcOp,
3181 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3185 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3186 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3187 if (ISD::isBuildVectorAllZeros(Op.getNode())
3188 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3189 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3190 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3191 // eliminated on x86-32 hosts.
3192 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3195 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3196 return getOnesVector(Op.getValueType(), DAG);
3197 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3200 MVT VT = Op.getValueType();
3201 MVT EVT = VT.getVectorElementType();
3202 unsigned EVTBits = EVT.getSizeInBits();
3204 unsigned NumElems = Op.getNumOperands();
3205 unsigned NumZero = 0;
3206 unsigned NumNonZero = 0;
3207 unsigned NonZeros = 0;
3208 bool IsAllConstants = true;
3209 SmallSet<SDValue, 8> Values;
3210 for (unsigned i = 0; i < NumElems; ++i) {
3211 SDValue Elt = Op.getOperand(i);
3212 if (Elt.getOpcode() == ISD::UNDEF)
3215 if (Elt.getOpcode() != ISD::Constant &&
3216 Elt.getOpcode() != ISD::ConstantFP)
3217 IsAllConstants = false;
3218 if (isZeroNode(Elt))
3221 NonZeros |= (1 << i);
3226 if (NumNonZero == 0) {
3227 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3228 return DAG.getNode(ISD::UNDEF, VT);
3231 // Special case for single non-zero, non-undef, element.
3232 if (NumNonZero == 1 && NumElems <= 4) {
3233 unsigned Idx = CountTrailingZeros_32(NonZeros);
3234 SDValue Item = Op.getOperand(Idx);
3236 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3237 // the value are obviously zero, truncate the value to i32 and do the
3238 // insertion that way. Only do this if the value is non-constant or if the
3239 // value is a constant being inserted into element 0. It is cheaper to do
3240 // a constant pool load than it is to do a movd + shuffle.
3241 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3242 (!IsAllConstants || Idx == 0)) {
3243 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3244 // Handle MMX and SSE both.
3245 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3246 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3248 // Truncate the value (which may itself be a constant) to i32, and
3249 // convert it to a vector with movd (S2V+shuffle to zero extend).
3250 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3251 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3252 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3253 Subtarget->hasSSE2(), DAG);
3255 // Now we have our 32-bit value zero extended in the low element of
3256 // a vector. If Idx != 0, swizzle it into place.
3259 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3260 getSwapEltZeroMask(VecElts, Idx, DAG)
3262 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3264 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3268 // If we have a constant or non-constant insertion into the low element of
3269 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3270 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3271 // depending on what the source datatype is. Because we can only get here
3272 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3274 // Don't do this for i64 values on x86-32.
3275 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3276 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3277 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3278 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3279 Subtarget->hasSSE2(), DAG);
3282 // Is it a vector logical left shift?
3283 if (NumElems == 2 && Idx == 1 &&
3284 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3285 unsigned NumBits = VT.getSizeInBits();
3286 return getVShift(true, VT,
3287 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3288 NumBits/2, DAG, *this);
3291 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3294 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3295 // is a non-constant being inserted into an element other than the low one,
3296 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3297 // movd/movss) to move this into the low element, then shuffle it into
3299 if (EVTBits == 32) {
3300 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3302 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3303 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3304 Subtarget->hasSSE2(), DAG);
3305 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3306 MVT MaskEVT = MaskVT.getVectorElementType();
3307 SmallVector<SDValue, 8> MaskVec;
3308 for (unsigned i = 0; i < NumElems; i++)
3309 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3310 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3311 &MaskVec[0], MaskVec.size());
3312 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3313 DAG.getNode(ISD::UNDEF, VT), Mask);
3317 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3318 if (Values.size() == 1)
3321 // A vector full of immediates; various special cases are already
3322 // handled, so this is best done with a single constant-pool load.
3326 // Let legalizer expand 2-wide build_vectors.
3327 if (EVTBits == 64) {
3328 if (NumNonZero == 1) {
3329 // One half is zero or undef.
3330 unsigned Idx = CountTrailingZeros_32(NonZeros);
3331 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3332 Op.getOperand(Idx));
3333 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3334 Subtarget->hasSSE2(), DAG);
3339 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3340 if (EVTBits == 8 && NumElems == 16) {
3341 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3343 if (V.getNode()) return V;
3346 if (EVTBits == 16 && NumElems == 8) {
3347 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3349 if (V.getNode()) return V;
3352 // If element VT is == 32 bits, turn it into a number of shuffles.
3353 SmallVector<SDValue, 8> V;
3355 if (NumElems == 4 && NumZero > 0) {
3356 for (unsigned i = 0; i < 4; ++i) {
3357 bool isZero = !(NonZeros & (1 << i));
3359 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3361 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3364 for (unsigned i = 0; i < 2; ++i) {
3365 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3368 V[i] = V[i*2]; // Must be a zero vector.
3371 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3372 getMOVLMask(NumElems, DAG));
3375 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3376 getMOVLMask(NumElems, DAG));
3379 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3380 getUnpacklMask(NumElems, DAG));
3385 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3386 MVT EVT = MaskVT.getVectorElementType();
3387 SmallVector<SDValue, 8> MaskVec;
3388 bool Reverse = (NonZeros & 0x3) == 2;
3389 for (unsigned i = 0; i < 2; ++i)
3391 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3393 MaskVec.push_back(DAG.getConstant(i, EVT));
3394 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3395 for (unsigned i = 0; i < 2; ++i)
3397 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3399 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3400 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3401 &MaskVec[0], MaskVec.size());
3402 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3405 if (Values.size() > 2) {
3406 // Expand into a number of unpckl*.
3408 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3409 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3410 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3411 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3412 for (unsigned i = 0; i < NumElems; ++i)
3413 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3415 while (NumElems != 0) {
3416 for (unsigned i = 0; i < NumElems; ++i)
3417 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3428 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3429 SDValue PermMask, SelectionDAG &DAG,
3430 TargetLowering &TLI) {
3432 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3433 MVT MaskEVT = MaskVT.getVectorElementType();
3434 MVT PtrVT = TLI.getPointerTy();
3435 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3436 PermMask.getNode()->op_end());
3438 // First record which half of which vector the low elements come from.
3439 SmallVector<unsigned, 4> LowQuad(4);
3440 for (unsigned i = 0; i < 4; ++i) {
3441 SDValue Elt = MaskElts[i];
3442 if (Elt.getOpcode() == ISD::UNDEF)
3444 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3445 int QuadIdx = EltIdx / 4;
3449 int BestLowQuad = -1;
3450 unsigned MaxQuad = 1;
3451 for (unsigned i = 0; i < 4; ++i) {
3452 if (LowQuad[i] > MaxQuad) {
3454 MaxQuad = LowQuad[i];
3458 // Record which half of which vector the high elements come from.
3459 SmallVector<unsigned, 4> HighQuad(4);
3460 for (unsigned i = 4; i < 8; ++i) {
3461 SDValue Elt = MaskElts[i];
3462 if (Elt.getOpcode() == ISD::UNDEF)
3464 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3465 int QuadIdx = EltIdx / 4;
3466 ++HighQuad[QuadIdx];
3469 int BestHighQuad = -1;
3471 for (unsigned i = 0; i < 4; ++i) {
3472 if (HighQuad[i] > MaxQuad) {
3474 MaxQuad = HighQuad[i];
3478 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3479 if (BestLowQuad != -1 || BestHighQuad != -1) {
3480 // First sort the 4 chunks in order using shufpd.
3481 SmallVector<SDValue, 8> MaskVec;
3483 if (BestLowQuad != -1)
3484 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3486 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3488 if (BestHighQuad != -1)
3489 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3491 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3493 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3494 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3495 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3496 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3497 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3499 // Now sort high and low parts separately.
3500 BitVector InOrder(8);
3501 if (BestLowQuad != -1) {
3502 // Sort lower half in order using PSHUFLW.
3504 bool AnyOutOrder = false;
3506 for (unsigned i = 0; i != 4; ++i) {
3507 SDValue Elt = MaskElts[i];
3508 if (Elt.getOpcode() == ISD::UNDEF) {
3509 MaskVec.push_back(Elt);
3512 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3516 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3518 // If this element is in the right place after this shuffle, then
3520 if ((int)(EltIdx / 4) == BestLowQuad)
3525 for (unsigned i = 4; i != 8; ++i)
3526 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3527 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3528 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3532 if (BestHighQuad != -1) {
3533 // Sort high half in order using PSHUFHW if possible.
3536 for (unsigned i = 0; i != 4; ++i)
3537 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3539 bool AnyOutOrder = false;
3540 for (unsigned i = 4; i != 8; ++i) {
3541 SDValue Elt = MaskElts[i];
3542 if (Elt.getOpcode() == ISD::UNDEF) {
3543 MaskVec.push_back(Elt);
3546 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3550 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3552 // If this element is in the right place after this shuffle, then
3554 if ((int)(EltIdx / 4) == BestHighQuad)
3560 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3561 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3565 // The other elements are put in the right place using pextrw and pinsrw.
3566 for (unsigned i = 0; i != 8; ++i) {
3569 SDValue Elt = MaskElts[i];
3570 if (Elt.getOpcode() == ISD::UNDEF)
3572 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3573 SDValue ExtOp = (EltIdx < 8)
3574 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3575 DAG.getConstant(EltIdx, PtrVT))
3576 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3577 DAG.getConstant(EltIdx - 8, PtrVT));
3578 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3579 DAG.getConstant(i, PtrVT));
3585 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3586 // few as possible. First, let's find out how many elements are already in the
3588 unsigned V1InOrder = 0;
3589 unsigned V1FromV1 = 0;
3590 unsigned V2InOrder = 0;
3591 unsigned V2FromV2 = 0;
3592 SmallVector<SDValue, 8> V1Elts;
3593 SmallVector<SDValue, 8> V2Elts;
3594 for (unsigned i = 0; i < 8; ++i) {
3595 SDValue Elt = MaskElts[i];
3596 if (Elt.getOpcode() == ISD::UNDEF) {
3597 V1Elts.push_back(Elt);
3598 V2Elts.push_back(Elt);
3603 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3605 V1Elts.push_back(Elt);
3606 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3608 } else if (EltIdx == i+8) {
3609 V1Elts.push_back(Elt);
3610 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3612 } else if (EltIdx < 8) {
3613 V1Elts.push_back(Elt);
3616 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3621 if (V2InOrder > V1InOrder) {
3622 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3624 std::swap(V1Elts, V2Elts);
3625 std::swap(V1FromV1, V2FromV2);
3628 if ((V1FromV1 + V1InOrder) != 8) {
3629 // Some elements are from V2.
3631 // If there are elements that are from V1 but out of place,
3632 // then first sort them in place
3633 SmallVector<SDValue, 8> MaskVec;
3634 for (unsigned i = 0; i < 8; ++i) {
3635 SDValue Elt = V1Elts[i];
3636 if (Elt.getOpcode() == ISD::UNDEF) {
3637 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3640 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3642 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3644 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3646 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3647 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3651 for (unsigned i = 0; i < 8; ++i) {
3652 SDValue Elt = V1Elts[i];
3653 if (Elt.getOpcode() == ISD::UNDEF)
3655 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3658 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3659 DAG.getConstant(EltIdx - 8, PtrVT));
3660 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3661 DAG.getConstant(i, PtrVT));
3665 // All elements are from V1.
3667 for (unsigned i = 0; i < 8; ++i) {
3668 SDValue Elt = V1Elts[i];
3669 if (Elt.getOpcode() == ISD::UNDEF)
3671 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3672 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3673 DAG.getConstant(EltIdx, PtrVT));
3674 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3675 DAG.getConstant(i, PtrVT));
3681 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3682 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3683 /// done when every pair / quad of shuffle mask elements point to elements in
3684 /// the right sequence. e.g.
3685 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3687 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3689 SDValue PermMask, SelectionDAG &DAG,
3690 TargetLowering &TLI) {
3691 unsigned NumElems = PermMask.getNumOperands();
3692 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3693 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3694 MVT MaskEltVT = MaskVT.getVectorElementType();
3696 switch (VT.getSimpleVT()) {
3697 default: assert(false && "Unexpected!");
3698 case MVT::v4f32: NewVT = MVT::v2f64; break;
3699 case MVT::v4i32: NewVT = MVT::v2i64; break;
3700 case MVT::v8i16: NewVT = MVT::v4i32; break;
3701 case MVT::v16i8: NewVT = MVT::v4i32; break;
3704 if (NewWidth == 2) {
3710 unsigned Scale = NumElems / NewWidth;
3711 SmallVector<SDValue, 8> MaskVec;
3712 for (unsigned i = 0; i < NumElems; i += Scale) {
3713 unsigned StartIdx = ~0U;
3714 for (unsigned j = 0; j < Scale; ++j) {
3715 SDValue Elt = PermMask.getOperand(i+j);
3716 if (Elt.getOpcode() == ISD::UNDEF)
3718 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3719 if (StartIdx == ~0U)
3720 StartIdx = EltIdx - (EltIdx % Scale);
3721 if (EltIdx != StartIdx + j)
3724 if (StartIdx == ~0U)
3725 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3727 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3730 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3731 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3732 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3733 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3734 &MaskVec[0], MaskVec.size()));
3737 /// getVZextMovL - Return a zero-extending vector move low node.
3739 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3740 SDValue SrcOp, SelectionDAG &DAG,
3741 const X86Subtarget *Subtarget) {
3742 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3743 LoadSDNode *LD = NULL;
3744 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3745 LD = dyn_cast<LoadSDNode>(SrcOp);
3747 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3749 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3750 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3751 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3752 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3753 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3755 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3756 return DAG.getNode(ISD::BIT_CONVERT, VT,
3757 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3758 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3765 return DAG.getNode(ISD::BIT_CONVERT, VT,
3766 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3767 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3770 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3773 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3774 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3775 MVT MaskVT = PermMask.getValueType();
3776 MVT MaskEVT = MaskVT.getVectorElementType();
3777 SmallVector<std::pair<int, int>, 8> Locs;
3779 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3782 for (unsigned i = 0; i != 4; ++i) {
3783 SDValue Elt = PermMask.getOperand(i);
3784 if (Elt.getOpcode() == ISD::UNDEF) {
3785 Locs[i] = std::make_pair(-1, -1);
3787 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3788 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3790 Locs[i] = std::make_pair(0, NumLo);
3794 Locs[i] = std::make_pair(1, NumHi);
3796 Mask1[2+NumHi] = Elt;
3802 if (NumLo <= 2 && NumHi <= 2) {
3803 // If no more than two elements come from either vector. This can be
3804 // implemented with two shuffles. First shuffle gather the elements.
3805 // The second shuffle, which takes the first shuffle as both of its
3806 // vector operands, put the elements into the right order.
3807 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3808 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3809 &Mask1[0], Mask1.size()));
3811 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3812 for (unsigned i = 0; i != 4; ++i) {
3813 if (Locs[i].first == -1)
3816 unsigned Idx = (i < 2) ? 0 : 4;
3817 Idx += Locs[i].first * 2 + Locs[i].second;
3818 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3822 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3823 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3824 &Mask2[0], Mask2.size()));
3825 } else if (NumLo == 3 || NumHi == 3) {
3826 // Otherwise, we must have three elements from one vector, call it X, and
3827 // one element from the other, call it Y. First, use a shufps to build an
3828 // intermediate vector with the one element from Y and the element from X
3829 // that will be in the same half in the final destination (the indexes don't
3830 // matter). Then, use a shufps to build the final vector, taking the half
3831 // containing the element from Y from the intermediate, and the other half
3834 // Normalize it so the 3 elements come from V1.
3835 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3839 // Find the element from V2.
3841 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3842 SDValue Elt = PermMask.getOperand(HiIndex);
3843 if (Elt.getOpcode() == ISD::UNDEF)
3845 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3850 Mask1[0] = PermMask.getOperand(HiIndex);
3851 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3852 Mask1[2] = PermMask.getOperand(HiIndex^1);
3853 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3854 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3855 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3858 Mask1[0] = PermMask.getOperand(0);
3859 Mask1[1] = PermMask.getOperand(1);
3860 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3861 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3862 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3863 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3865 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3866 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3867 Mask1[2] = PermMask.getOperand(2);
3868 Mask1[3] = PermMask.getOperand(3);
3869 if (Mask1[2].getOpcode() != ISD::UNDEF)
3871 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3873 if (Mask1[3].getOpcode() != ISD::UNDEF)
3875 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3877 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3878 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3882 // Break it into (shuffle shuffle_hi, shuffle_lo).
3884 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3885 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3886 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3887 unsigned MaskIdx = 0;
3890 for (unsigned i = 0; i != 4; ++i) {
3897 SDValue Elt = PermMask.getOperand(i);
3898 if (Elt.getOpcode() == ISD::UNDEF) {
3899 Locs[i] = std::make_pair(-1, -1);
3900 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3901 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3902 (*MaskPtr)[LoIdx] = Elt;
3905 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3906 (*MaskPtr)[HiIdx] = Elt;
3911 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3912 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3913 &LoMask[0], LoMask.size()));
3914 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3915 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3916 &HiMask[0], HiMask.size()));
3917 SmallVector<SDValue, 8> MaskOps;
3918 for (unsigned i = 0; i != 4; ++i) {
3919 if (Locs[i].first == -1) {
3920 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3922 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3923 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3926 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3927 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3928 &MaskOps[0], MaskOps.size()));
3932 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3933 SDValue V1 = Op.getOperand(0);
3934 SDValue V2 = Op.getOperand(1);
3935 SDValue PermMask = Op.getOperand(2);
3936 MVT VT = Op.getValueType();
3937 unsigned NumElems = PermMask.getNumOperands();
3938 bool isMMX = VT.getSizeInBits() == 64;
3939 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3940 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3941 bool V1IsSplat = false;
3942 bool V2IsSplat = false;
3944 if (isUndefShuffle(Op.getNode()))
3945 return DAG.getNode(ISD::UNDEF, VT);
3947 if (isZeroShuffle(Op.getNode()))
3948 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3950 if (isIdentityMask(PermMask.getNode()))
3952 else if (isIdentityMask(PermMask.getNode(), true))
3955 // Canonicalize movddup shuffles.
3956 if (V2IsUndef && Subtarget->hasSSE2() &&
3957 X86::isMOVDDUPMask(PermMask.getNode()))
3958 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
3960 if (isSplatMask(PermMask.getNode())) {
3961 if (isMMX || NumElems < 4) return Op;
3962 // Promote it to a v4{if}32 splat.
3963 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3966 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3968 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3969 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3970 if (NewOp.getNode())
3971 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3972 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3973 // FIXME: Figure out a cleaner way to do this.
3974 // Try to make use of movq to zero out the top part.
3975 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3976 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3978 if (NewOp.getNode()) {
3979 SDValue NewV1 = NewOp.getOperand(0);
3980 SDValue NewV2 = NewOp.getOperand(1);
3981 SDValue NewMask = NewOp.getOperand(2);
3982 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
3983 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3984 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3987 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3988 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3990 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
3991 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3996 // Check if this can be converted into a logical shift.
3997 bool isLeft = false;
4000 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4001 if (isShift && ShVal.hasOneUse()) {
4002 // If the shifted value has multiple uses, it may be cheaper to use
4003 // v_set0 + movlhps or movhlps, etc.
4004 MVT EVT = VT.getVectorElementType();
4005 ShAmt *= EVT.getSizeInBits();
4006 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4009 if (X86::isMOVLMask(PermMask.getNode())) {
4012 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4013 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
4018 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4019 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4020 X86::isMOVHLPSMask(PermMask.getNode()) ||
4021 X86::isMOVHPMask(PermMask.getNode()) ||
4022 X86::isMOVLPMask(PermMask.getNode())))
4025 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4026 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4027 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4030 // No better options. Use a vshl / vsrl.
4031 MVT EVT = VT.getVectorElementType();
4032 ShAmt *= EVT.getSizeInBits();
4033 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4036 bool Commuted = false;
4037 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4038 // 1,1,1,1 -> v8i16 though.
4039 V1IsSplat = isSplatVector(V1.getNode());
4040 V2IsSplat = isSplatVector(V2.getNode());
4042 // Canonicalize the splat or undef, if present, to be on the RHS.
4043 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4044 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4045 std::swap(V1IsSplat, V2IsSplat);
4046 std::swap(V1IsUndef, V2IsUndef);
4050 // FIXME: Figure out a cleaner way to do this.
4051 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4052 if (V2IsUndef) return V1;
4053 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4055 // V2 is a splat, so the mask may be malformed. That is, it may point
4056 // to any V2 element. The instruction selectior won't like this. Get
4057 // a corrected mask and commute to form a proper MOVS{S|D}.
4058 SDValue NewMask = getMOVLMask(NumElems, DAG);
4059 if (NewMask.getNode() != PermMask.getNode())
4060 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4065 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4066 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4067 X86::isUNPCKLMask(PermMask.getNode()) ||
4068 X86::isUNPCKHMask(PermMask.getNode()))
4072 // Normalize mask so all entries that point to V2 points to its first
4073 // element then try to match unpck{h|l} again. If match, return a
4074 // new vector_shuffle with the corrected mask.
4075 SDValue NewMask = NormalizeMask(PermMask, DAG);
4076 if (NewMask.getNode() != PermMask.getNode()) {
4077 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4078 SDValue NewMask = getUnpacklMask(NumElems, DAG);
4079 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4080 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4081 SDValue NewMask = getUnpackhMask(NumElems, DAG);
4082 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4087 // Normalize the node to match x86 shuffle ops if needed
4088 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4089 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4092 // Commute is back and try unpck* again.
4093 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4094 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4095 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4096 X86::isUNPCKLMask(PermMask.getNode()) ||
4097 X86::isUNPCKHMask(PermMask.getNode()))
4101 // Try PSHUF* first, then SHUFP*.
4102 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4103 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4104 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4105 if (V2.getOpcode() != ISD::UNDEF)
4106 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4107 DAG.getNode(ISD::UNDEF, VT), PermMask);
4112 if (Subtarget->hasSSE2() &&
4113 (X86::isPSHUFDMask(PermMask.getNode()) ||
4114 X86::isPSHUFHWMask(PermMask.getNode()) ||
4115 X86::isPSHUFLWMask(PermMask.getNode()))) {
4117 if (VT == MVT::v4f32) {
4119 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4120 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4121 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4122 } else if (V2.getOpcode() != ISD::UNDEF)
4123 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4124 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4126 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4130 // Binary or unary shufps.
4131 if (X86::isSHUFPMask(PermMask.getNode()) ||
4132 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4136 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4137 if (VT == MVT::v8i16) {
4138 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4139 if (NewOp.getNode())
4143 // Handle all 4 wide cases with a number of shuffles except for MMX.
4144 if (NumElems == 4 && !isMMX)
4145 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4151 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4152 SelectionDAG &DAG) {
4153 MVT VT = Op.getValueType();
4154 if (VT.getSizeInBits() == 8) {
4155 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4156 Op.getOperand(0), Op.getOperand(1));
4157 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4158 DAG.getValueType(VT));
4159 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4160 } else if (VT.getSizeInBits() == 16) {
4161 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4162 Op.getOperand(0), Op.getOperand(1));
4163 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4164 DAG.getValueType(VT));
4165 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4166 } else if (VT == MVT::f32) {
4167 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4168 // the result back to FR32 register. It's only worth matching if the
4169 // result has a single use which is a store or a bitcast to i32.
4170 if (!Op.hasOneUse())
4172 SDNode *User = *Op.getNode()->use_begin();
4173 if (User->getOpcode() != ISD::STORE &&
4174 (User->getOpcode() != ISD::BIT_CONVERT ||
4175 User->getValueType(0) != MVT::i32))
4177 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4178 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4180 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4187 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4188 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4191 if (Subtarget->hasSSE41()) {
4192 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4197 MVT VT = Op.getValueType();
4198 // TODO: handle v16i8.
4199 if (VT.getSizeInBits() == 16) {
4200 SDValue Vec = Op.getOperand(0);
4201 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4203 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4204 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4205 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4207 // Transform it so it match pextrw which produces a 32-bit result.
4208 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4209 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4210 Op.getOperand(0), Op.getOperand(1));
4211 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4212 DAG.getValueType(VT));
4213 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4214 } else if (VT.getSizeInBits() == 32) {
4215 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4218 // SHUFPS the element to the lowest double word, then movss.
4219 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4220 SmallVector<SDValue, 8> IdxVec;
4222 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4224 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4226 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4228 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4229 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4230 &IdxVec[0], IdxVec.size());
4231 SDValue Vec = Op.getOperand(0);
4232 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4233 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4234 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4235 DAG.getIntPtrConstant(0));
4236 } else if (VT.getSizeInBits() == 64) {
4237 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4238 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4239 // to match extract_elt for f64.
4240 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4244 // UNPCKHPD the element to the lowest double word, then movsd.
4245 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4246 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4247 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4248 SmallVector<SDValue, 8> IdxVec;
4249 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4251 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4252 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4253 &IdxVec[0], IdxVec.size());
4254 SDValue Vec = Op.getOperand(0);
4255 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4256 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4257 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4258 DAG.getIntPtrConstant(0));
4265 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4266 MVT VT = Op.getValueType();
4267 MVT EVT = VT.getVectorElementType();
4269 SDValue N0 = Op.getOperand(0);
4270 SDValue N1 = Op.getOperand(1);
4271 SDValue N2 = Op.getOperand(2);
4273 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4274 isa<ConstantSDNode>(N2)) {
4275 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4277 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4279 if (N1.getValueType() != MVT::i32)
4280 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4281 if (N2.getValueType() != MVT::i32)
4282 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4283 return DAG.getNode(Opc, VT, N0, N1, N2);
4284 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4285 // Bits [7:6] of the constant are the source select. This will always be
4286 // zero here. The DAG Combiner may combine an extract_elt index into these
4287 // bits. For example (insert (extract, 3), 2) could be matched by putting
4288 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4289 // Bits [5:4] of the constant are the destination select. This is the
4290 // value of the incoming immediate.
4291 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4292 // combine either bitwise AND or insert of float 0.0 to set these bits.
4293 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4294 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4300 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4301 MVT VT = Op.getValueType();
4302 MVT EVT = VT.getVectorElementType();
4304 if (Subtarget->hasSSE41())
4305 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4310 SDValue N0 = Op.getOperand(0);
4311 SDValue N1 = Op.getOperand(1);
4312 SDValue N2 = Op.getOperand(2);
4314 if (EVT.getSizeInBits() == 16) {
4315 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4316 // as its second argument.
4317 if (N1.getValueType() != MVT::i32)
4318 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4319 if (N2.getValueType() != MVT::i32)
4320 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4321 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4327 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4328 if (Op.getValueType() == MVT::v2f32)
4329 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4330 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4331 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4332 Op.getOperand(0))));
4334 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4335 MVT VT = MVT::v2i32;
4336 switch (Op.getValueType().getSimpleVT()) {
4343 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4344 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4347 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4348 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4349 // one of the above mentioned nodes. It has to be wrapped because otherwise
4350 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4351 // be used to form addressing mode. These wrapped nodes will be selected
4354 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4355 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4356 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4358 CP->getAlignment());
4359 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4360 // With PIC, the address is actually $g + Offset.
4361 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4362 !Subtarget->isPICStyleRIPRel()) {
4363 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4364 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4372 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4373 SelectionDAG &DAG) const {
4374 SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4375 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4376 // With PIC, the address is actually $g + Offset.
4377 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4378 !Subtarget->isPICStyleRIPRel()) {
4379 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4380 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4384 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4385 // load the value at address GV, not the value of GV itself. This means that
4386 // the GlobalAddress must be in the base or index register of the address, not
4387 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4388 // The same applies for external symbols during PIC codegen
4389 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4390 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4391 PseudoSourceValue::getGOT(), 0);
4397 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4398 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4399 return LowerGlobalAddress(GV, DAG);
4402 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4404 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4407 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4408 DAG.getNode(X86ISD::GlobalBaseReg,
4410 InFlag = Chain.getValue(1);
4412 // emit leal symbol@TLSGD(,%ebx,1), %eax
4413 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4414 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4415 GA->getValueType(0),
4417 SDValue Ops[] = { Chain, TGA, InFlag };
4418 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4419 InFlag = Result.getValue(2);
4420 Chain = Result.getValue(1);
4422 // call ___tls_get_addr. This function receives its argument in
4423 // the register EAX.
4424 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4425 InFlag = Chain.getValue(1);
4427 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4428 SDValue Ops1[] = { Chain,
4429 DAG.getTargetExternalSymbol("___tls_get_addr",
4431 DAG.getRegister(X86::EAX, PtrVT),
4432 DAG.getRegister(X86::EBX, PtrVT),
4434 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4435 InFlag = Chain.getValue(1);
4437 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4440 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4442 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4444 SDValue InFlag, Chain;
4446 // emit leaq symbol@TLSGD(%rip), %rdi
4447 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4448 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4449 GA->getValueType(0),
4451 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4452 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4453 Chain = Result.getValue(1);
4454 InFlag = Result.getValue(2);
4456 // call __tls_get_addr. This function receives its argument in
4457 // the register RDI.
4458 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4459 InFlag = Chain.getValue(1);
4461 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4462 SDValue Ops1[] = { Chain,
4463 DAG.getTargetExternalSymbol("__tls_get_addr",
4465 DAG.getRegister(X86::RDI, PtrVT),
4467 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4468 InFlag = Chain.getValue(1);
4470 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4473 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4474 // "local exec" model.
4475 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4477 // Get the Thread Pointer
4478 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4479 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4481 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4482 GA->getValueType(0),
4484 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4486 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4487 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4488 PseudoSourceValue::getGOT(), 0);
4490 // The address of the thread local variable is the add of the thread
4491 // pointer with the offset of the variable.
4492 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4496 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4497 // TODO: implement the "local dynamic" model
4498 // TODO: implement the "initial exec"model for pic executables
4499 assert(Subtarget->isTargetELF() &&
4500 "TLS not implemented for non-ELF targets");
4501 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4502 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4503 // otherwise use the "Local Exec"TLS Model
4504 if (Subtarget->is64Bit()) {
4505 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4507 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4508 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4510 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4515 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4516 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4517 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4518 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4519 // With PIC, the address is actually $g + Offset.
4520 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4521 !Subtarget->isPICStyleRIPRel()) {
4522 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4523 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4530 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4531 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4532 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4533 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4534 // With PIC, the address is actually $g + Offset.
4535 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4536 !Subtarget->isPICStyleRIPRel()) {
4537 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4538 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4545 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4546 /// take a 2 x i32 value to shift plus a shift amount.
4547 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4548 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4549 MVT VT = Op.getValueType();
4550 unsigned VTBits = VT.getSizeInBits();
4551 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4552 SDValue ShOpLo = Op.getOperand(0);
4553 SDValue ShOpHi = Op.getOperand(1);
4554 SDValue ShAmt = Op.getOperand(2);
4555 SDValue Tmp1 = isSRA ?
4556 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4557 DAG.getConstant(0, VT);
4560 if (Op.getOpcode() == ISD::SHL_PARTS) {
4561 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4562 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4564 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4565 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4568 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4569 DAG.getConstant(VTBits, MVT::i8));
4570 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4571 AndNode, DAG.getConstant(0, MVT::i8));
4574 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4575 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4576 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4578 if (Op.getOpcode() == ISD::SHL_PARTS) {
4579 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4580 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4582 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4583 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4586 SDValue Ops[2] = { Lo, Hi };
4587 return DAG.getMergeValues(Ops, 2);
4590 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4591 MVT SrcVT = Op.getOperand(0).getValueType();
4592 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4593 "Unknown SINT_TO_FP to lower!");
4595 // These are really Legal; caller falls through into that case.
4596 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4598 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4599 Subtarget->is64Bit())
4602 unsigned Size = SrcVT.getSizeInBits()/8;
4603 MachineFunction &MF = DAG.getMachineFunction();
4604 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4605 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4606 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4608 PseudoSourceValue::getFixedStack(SSFI), 0);
4612 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4614 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4616 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4617 SmallVector<SDValue, 8> Ops;
4618 Ops.push_back(Chain);
4619 Ops.push_back(StackSlot);
4620 Ops.push_back(DAG.getValueType(SrcVT));
4621 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4622 Tys, &Ops[0], Ops.size());
4625 Chain = Result.getValue(1);
4626 SDValue InFlag = Result.getValue(2);
4628 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4629 // shouldn't be necessary except that RFP cannot be live across
4630 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4631 MachineFunction &MF = DAG.getMachineFunction();
4632 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4633 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4634 Tys = DAG.getVTList(MVT::Other);
4635 SmallVector<SDValue, 8> Ops;
4636 Ops.push_back(Chain);
4637 Ops.push_back(Result);
4638 Ops.push_back(StackSlot);
4639 Ops.push_back(DAG.getValueType(Op.getValueType()));
4640 Ops.push_back(InFlag);
4641 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4642 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4643 PseudoSourceValue::getFixedStack(SSFI), 0);
4649 std::pair<SDValue,SDValue> X86TargetLowering::
4650 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4651 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4652 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4653 "Unknown FP_TO_SINT to lower!");
4655 // These are really Legal.
4656 if (Op.getValueType() == MVT::i32 &&
4657 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4658 return std::make_pair(SDValue(), SDValue());
4659 if (Subtarget->is64Bit() &&
4660 Op.getValueType() == MVT::i64 &&
4661 Op.getOperand(0).getValueType() != MVT::f80)
4662 return std::make_pair(SDValue(), SDValue());
4664 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4666 MachineFunction &MF = DAG.getMachineFunction();
4667 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4668 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4669 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4671 switch (Op.getValueType().getSimpleVT()) {
4672 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4673 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4674 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4675 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4678 SDValue Chain = DAG.getEntryNode();
4679 SDValue Value = Op.getOperand(0);
4680 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4681 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4682 Chain = DAG.getStore(Chain, Value, StackSlot,
4683 PseudoSourceValue::getFixedStack(SSFI), 0);
4684 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4686 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4688 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4689 Chain = Value.getValue(1);
4690 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4691 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4694 // Build the FP_TO_INT*_IN_MEM
4695 SDValue Ops[] = { Chain, Value, StackSlot };
4696 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4698 return std::make_pair(FIST, StackSlot);
4701 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4702 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4703 SDValue FIST = Vals.first, StackSlot = Vals.second;
4704 if (FIST.getNode() == 0) return SDValue();
4707 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4710 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4711 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4712 SDValue FIST = Vals.first, StackSlot = Vals.second;
4713 if (FIST.getNode() == 0) return 0;
4715 MVT VT = N->getValueType(0);
4717 // Return a load from the stack slot.
4718 SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4720 // Use MERGE_VALUES to drop the chain result value and get a node with one
4721 // result. This requires turning off getMergeValues simplification, since
4722 // otherwise it will give us Res back.
4723 return DAG.getMergeValues(&Res, 1, false).getNode();
4726 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4727 MVT VT = Op.getValueType();
4730 EltVT = VT.getVectorElementType();
4731 std::vector<Constant*> CV;
4732 if (EltVT == MVT::f64) {
4733 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4737 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4743 Constant *C = ConstantVector::get(CV);
4744 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4745 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4746 PseudoSourceValue::getConstantPool(), 0,
4748 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4751 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4752 MVT VT = Op.getValueType();
4754 unsigned EltNum = 1;
4755 if (VT.isVector()) {
4756 EltVT = VT.getVectorElementType();
4757 EltNum = VT.getVectorNumElements();
4759 std::vector<Constant*> CV;
4760 if (EltVT == MVT::f64) {
4761 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4765 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4771 Constant *C = ConstantVector::get(CV);
4772 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4773 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4774 PseudoSourceValue::getConstantPool(), 0,
4776 if (VT.isVector()) {
4777 return DAG.getNode(ISD::BIT_CONVERT, VT,
4778 DAG.getNode(ISD::XOR, MVT::v2i64,
4779 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4780 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4782 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4786 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4787 SDValue Op0 = Op.getOperand(0);
4788 SDValue Op1 = Op.getOperand(1);
4789 MVT VT = Op.getValueType();
4790 MVT SrcVT = Op1.getValueType();
4792 // If second operand is smaller, extend it first.
4793 if (SrcVT.bitsLT(VT)) {
4794 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4797 // And if it is bigger, shrink it first.
4798 if (SrcVT.bitsGT(VT)) {
4799 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4803 // At this point the operands and the result should have the same
4804 // type, and that won't be f80 since that is not custom lowered.
4806 // First get the sign bit of second operand.
4807 std::vector<Constant*> CV;
4808 if (SrcVT == MVT::f64) {
4809 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4810 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4812 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4813 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4814 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4815 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4817 Constant *C = ConstantVector::get(CV);
4818 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4819 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4820 PseudoSourceValue::getConstantPool(), 0,
4822 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4824 // Shift sign bit right or left if the two operands have different types.
4825 if (SrcVT.bitsGT(VT)) {
4826 // Op0 is MVT::f32, Op1 is MVT::f64.
4827 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4828 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4829 DAG.getConstant(32, MVT::i32));
4830 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4831 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4832 DAG.getIntPtrConstant(0));
4835 // Clear first operand sign bit.
4837 if (VT == MVT::f64) {
4838 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4839 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4841 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4842 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4843 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4844 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4846 C = ConstantVector::get(CV);
4847 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4848 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4849 PseudoSourceValue::getConstantPool(), 0,
4851 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4853 // Or the value with the sign bit.
4854 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4857 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4858 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4860 SDValue Op0 = Op.getOperand(0);
4861 SDValue Op1 = Op.getOperand(1);
4862 SDValue CC = Op.getOperand(2);
4863 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4864 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4867 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4869 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4870 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4871 DAG.getConstant(X86CC, MVT::i8), Cond);
4874 assert(isFP && "Illegal integer SetCC!");
4876 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4877 switch (SetCCOpcode) {
4878 default: assert(false && "Illegal floating point SetCC!");
4879 case ISD::SETOEQ: { // !PF & ZF
4880 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4881 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4882 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4883 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4884 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4886 case ISD::SETUNE: { // PF | !ZF
4887 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4888 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4889 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4890 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4891 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4896 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4898 SDValue Op0 = Op.getOperand(0);
4899 SDValue Op1 = Op.getOperand(1);
4900 SDValue CC = Op.getOperand(2);
4901 MVT VT = Op.getValueType();
4902 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4903 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4907 MVT VT0 = Op0.getValueType();
4908 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4909 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4912 switch (SetCCOpcode) {
4915 case ISD::SETEQ: SSECC = 0; break;
4917 case ISD::SETGT: Swap = true; // Fallthrough
4919 case ISD::SETOLT: SSECC = 1; break;
4921 case ISD::SETGE: Swap = true; // Fallthrough
4923 case ISD::SETOLE: SSECC = 2; break;
4924 case ISD::SETUO: SSECC = 3; break;
4926 case ISD::SETNE: SSECC = 4; break;
4927 case ISD::SETULE: Swap = true;
4928 case ISD::SETUGE: SSECC = 5; break;
4929 case ISD::SETULT: Swap = true;
4930 case ISD::SETUGT: SSECC = 6; break;
4931 case ISD::SETO: SSECC = 7; break;
4934 std::swap(Op0, Op1);
4936 // In the two special cases we can't handle, emit two comparisons.
4938 if (SetCCOpcode == ISD::SETUEQ) {
4940 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4941 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4942 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4944 else if (SetCCOpcode == ISD::SETONE) {
4946 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4947 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4948 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4950 assert(0 && "Illegal FP comparison");
4952 // Handle all other FP comparisons here.
4953 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4956 // We are handling one of the integer comparisons here. Since SSE only has
4957 // GT and EQ comparisons for integer, swapping operands and multiple
4958 // operations may be required for some comparisons.
4959 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4960 bool Swap = false, Invert = false, FlipSigns = false;
4962 switch (VT.getSimpleVT()) {
4964 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4965 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4966 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4967 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4970 switch (SetCCOpcode) {
4972 case ISD::SETNE: Invert = true;
4973 case ISD::SETEQ: Opc = EQOpc; break;
4974 case ISD::SETLT: Swap = true;
4975 case ISD::SETGT: Opc = GTOpc; break;
4976 case ISD::SETGE: Swap = true;
4977 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
4978 case ISD::SETULT: Swap = true;
4979 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4980 case ISD::SETUGE: Swap = true;
4981 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4984 std::swap(Op0, Op1);
4986 // Since SSE has no unsigned integer comparisons, we need to flip the sign
4987 // bits of the inputs before performing those operations.
4989 MVT EltVT = VT.getVectorElementType();
4990 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4991 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4992 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4994 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4995 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4998 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
5000 // If the logical-not of the result is required, perform that now.
5002 MVT EltVT = VT.getVectorElementType();
5003 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
5004 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
5005 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
5007 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
5012 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5013 bool addTest = true;
5014 SDValue Cond = Op.getOperand(0);
5017 if (Cond.getOpcode() == ISD::SETCC)
5018 Cond = LowerSETCC(Cond, DAG);
5020 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5021 // setting operand in place of the X86ISD::SETCC.
5022 if (Cond.getOpcode() == X86ISD::SETCC) {
5023 CC = Cond.getOperand(0);
5025 SDValue Cmp = Cond.getOperand(1);
5026 unsigned Opc = Cmp.getOpcode();
5027 MVT VT = Op.getValueType();
5029 bool IllegalFPCMov = false;
5030 if (VT.isFloatingPoint() && !VT.isVector() &&
5031 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5032 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5034 if ((Opc == X86ISD::CMP ||
5035 Opc == X86ISD::COMI ||
5036 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
5043 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5044 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5047 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5049 SmallVector<SDValue, 4> Ops;
5050 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5051 // condition is true.
5052 Ops.push_back(Op.getOperand(2));
5053 Ops.push_back(Op.getOperand(1));
5055 Ops.push_back(Cond);
5056 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5059 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5060 bool addTest = true;
5061 SDValue Chain = Op.getOperand(0);
5062 SDValue Cond = Op.getOperand(1);
5063 SDValue Dest = Op.getOperand(2);
5066 if (Cond.getOpcode() == ISD::SETCC)
5067 Cond = LowerSETCC(Cond, DAG);
5069 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5070 // setting operand in place of the X86ISD::SETCC.
5071 if (Cond.getOpcode() == X86ISD::SETCC) {
5072 CC = Cond.getOperand(0);
5074 SDValue Cmp = Cond.getOperand(1);
5075 unsigned Opc = Cmp.getOpcode();
5076 if (Opc == X86ISD::CMP ||
5077 Opc == X86ISD::COMI ||
5078 Opc == X86ISD::UCOMI) {
5085 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5086 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5088 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5089 Chain, Op.getOperand(2), CC, Cond);
5093 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5094 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5095 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5096 // that the guard pages used by the OS virtual memory manager are allocated in
5097 // correct sequence.
5099 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5100 SelectionDAG &DAG) {
5101 assert(Subtarget->isTargetCygMing() &&
5102 "This should be used only on Cygwin/Mingw targets");
5105 SDValue Chain = Op.getOperand(0);
5106 SDValue Size = Op.getOperand(1);
5107 // FIXME: Ensure alignment here
5111 MVT IntPtr = getPointerTy();
5112 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5114 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
5116 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5117 Flag = Chain.getValue(1);
5119 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5120 SDValue Ops[] = { Chain,
5121 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5122 DAG.getRegister(X86::EAX, IntPtr),
5123 DAG.getRegister(X86StackPtr, SPTy),
5125 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5126 Flag = Chain.getValue(1);
5128 Chain = DAG.getCALLSEQ_END(Chain,
5129 DAG.getIntPtrConstant(0),
5130 DAG.getIntPtrConstant(0),
5133 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5135 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5136 return DAG.getMergeValues(Ops1, 2);
5140 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5142 SDValue Dst, SDValue Src,
5143 SDValue Size, unsigned Align,
5145 uint64_t DstSVOff) {
5146 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5148 // If not DWORD aligned or size is more than the threshold, call the library.
5149 // The libc version is likely to be faster for these cases. It can use the
5150 // address value and run time information about the CPU.
5151 if ((Align & 3) != 0 ||
5153 ConstantSize->getZExtValue() >
5154 getSubtarget()->getMaxInlineSizeThreshold()) {
5155 SDValue InFlag(0, 0);
5157 // Check to see if there is a specialized entry-point for memory zeroing.
5158 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5160 if (const char *bzeroEntry = V &&
5161 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5162 MVT IntPtr = getPointerTy();
5163 const Type *IntPtrTy = TD->getIntPtrType();
5164 TargetLowering::ArgListTy Args;
5165 TargetLowering::ArgListEntry Entry;
5167 Entry.Ty = IntPtrTy;
5168 Args.push_back(Entry);
5170 Args.push_back(Entry);
5171 std::pair<SDValue,SDValue> CallResult =
5172 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5173 CallingConv::C, false,
5174 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG);
5175 return CallResult.second;
5178 // Otherwise have the target-independent code call memset.
5182 uint64_t SizeVal = ConstantSize->getZExtValue();
5183 SDValue InFlag(0, 0);
5186 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5187 unsigned BytesLeft = 0;
5188 bool TwoRepStos = false;
5191 uint64_t Val = ValC->getZExtValue() & 255;
5193 // If the value is a constant, then we can potentially use larger sets.
5194 switch (Align & 3) {
5195 case 2: // WORD aligned
5198 Val = (Val << 8) | Val;
5200 case 0: // DWORD aligned
5203 Val = (Val << 8) | Val;
5204 Val = (Val << 16) | Val;
5205 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5208 Val = (Val << 32) | Val;
5211 default: // Byte aligned
5214 Count = DAG.getIntPtrConstant(SizeVal);
5218 if (AVT.bitsGT(MVT::i8)) {
5219 unsigned UBytes = AVT.getSizeInBits() / 8;
5220 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5221 BytesLeft = SizeVal % UBytes;
5224 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5226 InFlag = Chain.getValue(1);
5229 Count = DAG.getIntPtrConstant(SizeVal);
5230 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5231 InFlag = Chain.getValue(1);
5234 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5236 InFlag = Chain.getValue(1);
5237 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5239 InFlag = Chain.getValue(1);
5241 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5242 SmallVector<SDValue, 8> Ops;
5243 Ops.push_back(Chain);
5244 Ops.push_back(DAG.getValueType(AVT));
5245 Ops.push_back(InFlag);
5246 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5249 InFlag = Chain.getValue(1);
5251 MVT CVT = Count.getValueType();
5252 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5253 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5254 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5256 InFlag = Chain.getValue(1);
5257 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5259 Ops.push_back(Chain);
5260 Ops.push_back(DAG.getValueType(MVT::i8));
5261 Ops.push_back(InFlag);
5262 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5263 } else if (BytesLeft) {
5264 // Handle the last 1 - 7 bytes.
5265 unsigned Offset = SizeVal - BytesLeft;
5266 MVT AddrVT = Dst.getValueType();
5267 MVT SizeVT = Size.getValueType();
5269 Chain = DAG.getMemset(Chain,
5270 DAG.getNode(ISD::ADD, AddrVT, Dst,
5271 DAG.getConstant(Offset, AddrVT)),
5273 DAG.getConstant(BytesLeft, SizeVT),
5274 Align, DstSV, DstSVOff + Offset);
5277 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5282 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5283 SDValue Chain, SDValue Dst, SDValue Src,
5284 SDValue Size, unsigned Align,
5286 const Value *DstSV, uint64_t DstSVOff,
5287 const Value *SrcSV, uint64_t SrcSVOff) {
5288 // This requires the copy size to be a constant, preferrably
5289 // within a subtarget-specific limit.
5290 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5293 uint64_t SizeVal = ConstantSize->getZExtValue();
5294 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5297 /// If not DWORD aligned, call the library.
5298 if ((Align & 3) != 0)
5303 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5306 unsigned UBytes = AVT.getSizeInBits() / 8;
5307 unsigned CountVal = SizeVal / UBytes;
5308 SDValue Count = DAG.getIntPtrConstant(CountVal);
5309 unsigned BytesLeft = SizeVal % UBytes;
5311 SDValue InFlag(0, 0);
5312 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5314 InFlag = Chain.getValue(1);
5315 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5317 InFlag = Chain.getValue(1);
5318 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5320 InFlag = Chain.getValue(1);
5322 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5323 SmallVector<SDValue, 8> Ops;
5324 Ops.push_back(Chain);
5325 Ops.push_back(DAG.getValueType(AVT));
5326 Ops.push_back(InFlag);
5327 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5329 SmallVector<SDValue, 4> Results;
5330 Results.push_back(RepMovs);
5332 // Handle the last 1 - 7 bytes.
5333 unsigned Offset = SizeVal - BytesLeft;
5334 MVT DstVT = Dst.getValueType();
5335 MVT SrcVT = Src.getValueType();
5336 MVT SizeVT = Size.getValueType();
5337 Results.push_back(DAG.getMemcpy(Chain,
5338 DAG.getNode(ISD::ADD, DstVT, Dst,
5339 DAG.getConstant(Offset, DstVT)),
5340 DAG.getNode(ISD::ADD, SrcVT, Src,
5341 DAG.getConstant(Offset, SrcVT)),
5342 DAG.getConstant(BytesLeft, SizeVT),
5343 Align, AlwaysInline,
5344 DstSV, DstSVOff + Offset,
5345 SrcSV, SrcSVOff + Offset));
5348 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5351 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5352 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5353 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5354 SDValue TheChain = N->getOperand(0);
5355 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5356 if (Subtarget->is64Bit()) {
5357 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5358 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5359 MVT::i64, rax.getValue(2));
5360 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5361 DAG.getConstant(32, MVT::i8));
5363 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5366 return DAG.getMergeValues(Ops, 2).getNode();
5369 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5370 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5371 MVT::i32, eax.getValue(2));
5372 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5373 SDValue Ops[] = { eax, edx };
5374 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5376 // Use a MERGE_VALUES to return the value and chain.
5377 Ops[1] = edx.getValue(1);
5378 return DAG.getMergeValues(Ops, 2).getNode();
5381 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5382 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5384 if (!Subtarget->is64Bit()) {
5385 // vastart just stores the address of the VarArgsFrameIndex slot into the
5386 // memory location argument.
5387 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5388 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5392 // gp_offset (0 - 6 * 8)
5393 // fp_offset (48 - 48 + 8 * 16)
5394 // overflow_arg_area (point to parameters coming in memory).
5396 SmallVector<SDValue, 8> MemOps;
5397 SDValue FIN = Op.getOperand(1);
5399 SDValue Store = DAG.getStore(Op.getOperand(0),
5400 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5402 MemOps.push_back(Store);
5405 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5406 Store = DAG.getStore(Op.getOperand(0),
5407 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5409 MemOps.push_back(Store);
5411 // Store ptr to overflow_arg_area
5412 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5413 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5414 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5415 MemOps.push_back(Store);
5417 // Store ptr to reg_save_area.
5418 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5419 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5420 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5421 MemOps.push_back(Store);
5422 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5425 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5426 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5427 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5428 SDValue Chain = Op.getOperand(0);
5429 SDValue SrcPtr = Op.getOperand(1);
5430 SDValue SrcSV = Op.getOperand(2);
5432 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5437 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5438 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5439 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5440 SDValue Chain = Op.getOperand(0);
5441 SDValue DstPtr = Op.getOperand(1);
5442 SDValue SrcPtr = Op.getOperand(2);
5443 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5444 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5446 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5447 DAG.getIntPtrConstant(24), 8, false,
5448 DstSV, 0, SrcSV, 0);
5452 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5453 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5455 default: return SDValue(); // Don't custom lower most intrinsics.
5456 // Comparison intrinsics.
5457 case Intrinsic::x86_sse_comieq_ss:
5458 case Intrinsic::x86_sse_comilt_ss:
5459 case Intrinsic::x86_sse_comile_ss:
5460 case Intrinsic::x86_sse_comigt_ss:
5461 case Intrinsic::x86_sse_comige_ss:
5462 case Intrinsic::x86_sse_comineq_ss:
5463 case Intrinsic::x86_sse_ucomieq_ss:
5464 case Intrinsic::x86_sse_ucomilt_ss:
5465 case Intrinsic::x86_sse_ucomile_ss:
5466 case Intrinsic::x86_sse_ucomigt_ss:
5467 case Intrinsic::x86_sse_ucomige_ss:
5468 case Intrinsic::x86_sse_ucomineq_ss:
5469 case Intrinsic::x86_sse2_comieq_sd:
5470 case Intrinsic::x86_sse2_comilt_sd:
5471 case Intrinsic::x86_sse2_comile_sd:
5472 case Intrinsic::x86_sse2_comigt_sd:
5473 case Intrinsic::x86_sse2_comige_sd:
5474 case Intrinsic::x86_sse2_comineq_sd:
5475 case Intrinsic::x86_sse2_ucomieq_sd:
5476 case Intrinsic::x86_sse2_ucomilt_sd:
5477 case Intrinsic::x86_sse2_ucomile_sd:
5478 case Intrinsic::x86_sse2_ucomigt_sd:
5479 case Intrinsic::x86_sse2_ucomige_sd:
5480 case Intrinsic::x86_sse2_ucomineq_sd: {
5482 ISD::CondCode CC = ISD::SETCC_INVALID;
5485 case Intrinsic::x86_sse_comieq_ss:
5486 case Intrinsic::x86_sse2_comieq_sd:
5490 case Intrinsic::x86_sse_comilt_ss:
5491 case Intrinsic::x86_sse2_comilt_sd:
5495 case Intrinsic::x86_sse_comile_ss:
5496 case Intrinsic::x86_sse2_comile_sd:
5500 case Intrinsic::x86_sse_comigt_ss:
5501 case Intrinsic::x86_sse2_comigt_sd:
5505 case Intrinsic::x86_sse_comige_ss:
5506 case Intrinsic::x86_sse2_comige_sd:
5510 case Intrinsic::x86_sse_comineq_ss:
5511 case Intrinsic::x86_sse2_comineq_sd:
5515 case Intrinsic::x86_sse_ucomieq_ss:
5516 case Intrinsic::x86_sse2_ucomieq_sd:
5517 Opc = X86ISD::UCOMI;
5520 case Intrinsic::x86_sse_ucomilt_ss:
5521 case Intrinsic::x86_sse2_ucomilt_sd:
5522 Opc = X86ISD::UCOMI;
5525 case Intrinsic::x86_sse_ucomile_ss:
5526 case Intrinsic::x86_sse2_ucomile_sd:
5527 Opc = X86ISD::UCOMI;
5530 case Intrinsic::x86_sse_ucomigt_ss:
5531 case Intrinsic::x86_sse2_ucomigt_sd:
5532 Opc = X86ISD::UCOMI;
5535 case Intrinsic::x86_sse_ucomige_ss:
5536 case Intrinsic::x86_sse2_ucomige_sd:
5537 Opc = X86ISD::UCOMI;
5540 case Intrinsic::x86_sse_ucomineq_ss:
5541 case Intrinsic::x86_sse2_ucomineq_sd:
5542 Opc = X86ISD::UCOMI;
5548 SDValue LHS = Op.getOperand(1);
5549 SDValue RHS = Op.getOperand(2);
5550 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5552 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5553 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5554 DAG.getConstant(X86CC, MVT::i8), Cond);
5555 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5558 // Fix vector shift instructions where the last operand is a non-immediate
5560 case Intrinsic::x86_sse2_pslli_w:
5561 case Intrinsic::x86_sse2_pslli_d:
5562 case Intrinsic::x86_sse2_pslli_q:
5563 case Intrinsic::x86_sse2_psrli_w:
5564 case Intrinsic::x86_sse2_psrli_d:
5565 case Intrinsic::x86_sse2_psrli_q:
5566 case Intrinsic::x86_sse2_psrai_w:
5567 case Intrinsic::x86_sse2_psrai_d:
5568 case Intrinsic::x86_mmx_pslli_w:
5569 case Intrinsic::x86_mmx_pslli_d:
5570 case Intrinsic::x86_mmx_pslli_q:
5571 case Intrinsic::x86_mmx_psrli_w:
5572 case Intrinsic::x86_mmx_psrli_d:
5573 case Intrinsic::x86_mmx_psrli_q:
5574 case Intrinsic::x86_mmx_psrai_w:
5575 case Intrinsic::x86_mmx_psrai_d: {
5576 SDValue ShAmt = Op.getOperand(2);
5577 if (isa<ConstantSDNode>(ShAmt))
5580 unsigned NewIntNo = 0;
5581 MVT ShAmtVT = MVT::v4i32;
5583 case Intrinsic::x86_sse2_pslli_w:
5584 NewIntNo = Intrinsic::x86_sse2_psll_w;
5586 case Intrinsic::x86_sse2_pslli_d:
5587 NewIntNo = Intrinsic::x86_sse2_psll_d;
5589 case Intrinsic::x86_sse2_pslli_q:
5590 NewIntNo = Intrinsic::x86_sse2_psll_q;
5592 case Intrinsic::x86_sse2_psrli_w:
5593 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5595 case Intrinsic::x86_sse2_psrli_d:
5596 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5598 case Intrinsic::x86_sse2_psrli_q:
5599 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5601 case Intrinsic::x86_sse2_psrai_w:
5602 NewIntNo = Intrinsic::x86_sse2_psra_w;
5604 case Intrinsic::x86_sse2_psrai_d:
5605 NewIntNo = Intrinsic::x86_sse2_psra_d;
5608 ShAmtVT = MVT::v2i32;
5610 case Intrinsic::x86_mmx_pslli_w:
5611 NewIntNo = Intrinsic::x86_mmx_psll_w;
5613 case Intrinsic::x86_mmx_pslli_d:
5614 NewIntNo = Intrinsic::x86_mmx_psll_d;
5616 case Intrinsic::x86_mmx_pslli_q:
5617 NewIntNo = Intrinsic::x86_mmx_psll_q;
5619 case Intrinsic::x86_mmx_psrli_w:
5620 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5622 case Intrinsic::x86_mmx_psrli_d:
5623 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5625 case Intrinsic::x86_mmx_psrli_q:
5626 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5628 case Intrinsic::x86_mmx_psrai_w:
5629 NewIntNo = Intrinsic::x86_mmx_psra_w;
5631 case Intrinsic::x86_mmx_psrai_d:
5632 NewIntNo = Intrinsic::x86_mmx_psra_d;
5634 default: abort(); // Can't reach here.
5639 MVT VT = Op.getValueType();
5640 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5641 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5642 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5643 DAG.getConstant(NewIntNo, MVT::i32),
5644 Op.getOperand(1), ShAmt);
5649 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5650 // Depths > 0 not supported yet!
5651 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5654 // Just load the return address
5655 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5656 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5659 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5660 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5661 MFI->setFrameAddressIsTaken(true);
5662 MVT VT = Op.getValueType();
5663 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5664 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
5665 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
5667 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
5671 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5672 SelectionDAG &DAG) {
5673 return DAG.getIntPtrConstant(2*TD->getPointerSize());
5676 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5678 MachineFunction &MF = DAG.getMachineFunction();
5679 SDValue Chain = Op.getOperand(0);
5680 SDValue Offset = Op.getOperand(1);
5681 SDValue Handler = Op.getOperand(2);
5683 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5685 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5687 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5688 DAG.getIntPtrConstant(-TD->getPointerSize()));
5689 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5690 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5691 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5692 MF.getRegInfo().addLiveOut(StoreAddrReg);
5694 return DAG.getNode(X86ISD::EH_RETURN,
5696 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5699 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5700 SelectionDAG &DAG) {
5701 SDValue Root = Op.getOperand(0);
5702 SDValue Trmp = Op.getOperand(1); // trampoline
5703 SDValue FPtr = Op.getOperand(2); // nested function
5704 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5706 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5708 const X86InstrInfo *TII =
5709 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5711 if (Subtarget->is64Bit()) {
5712 SDValue OutChains[6];
5714 // Large code-model.
5716 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5717 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5719 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5720 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5722 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5724 // Load the pointer to the nested function into R11.
5725 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5726 SDValue Addr = Trmp;
5727 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5730 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5731 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5733 // Load the 'nest' parameter value into R10.
5734 // R10 is specified in X86CallingConv.td
5735 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5736 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5737 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5740 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5741 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5743 // Jump to the nested function.
5744 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5745 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5746 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5749 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5750 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5751 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5755 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5756 return DAG.getMergeValues(Ops, 2);
5758 const Function *Func =
5759 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5760 unsigned CC = Func->getCallingConv();
5765 assert(0 && "Unsupported calling convention");
5766 case CallingConv::C:
5767 case CallingConv::X86_StdCall: {
5768 // Pass 'nest' parameter in ECX.
5769 // Must be kept in sync with X86CallingConv.td
5772 // Check that ECX wasn't needed by an 'inreg' parameter.
5773 const FunctionType *FTy = Func->getFunctionType();
5774 const AttrListPtr &Attrs = Func->getAttributes();
5776 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5777 unsigned InRegCount = 0;
5780 for (FunctionType::param_iterator I = FTy->param_begin(),
5781 E = FTy->param_end(); I != E; ++I, ++Idx)
5782 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
5783 // FIXME: should only count parameters that are lowered to integers.
5784 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
5786 if (InRegCount > 2) {
5787 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5793 case CallingConv::X86_FastCall:
5794 case CallingConv::Fast:
5795 // Pass 'nest' parameter in EAX.
5796 // Must be kept in sync with X86CallingConv.td
5801 SDValue OutChains[4];
5804 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5805 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5807 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5808 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5809 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5812 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5813 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5815 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5816 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5817 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5818 TrmpAddr, 5, false, 1);
5820 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5821 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5824 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5825 return DAG.getMergeValues(Ops, 2);
5829 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5831 The rounding mode is in bits 11:10 of FPSR, and has the following
5838 FLT_ROUNDS, on the other hand, expects the following:
5845 To perform the conversion, we do:
5846 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5849 MachineFunction &MF = DAG.getMachineFunction();
5850 const TargetMachine &TM = MF.getTarget();
5851 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5852 unsigned StackAlignment = TFI.getStackAlignment();
5853 MVT VT = Op.getValueType();
5855 // Save FP Control Word to stack slot
5856 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5857 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5859 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5860 DAG.getEntryNode(), StackSlot);
5862 // Load FP Control Word from stack slot
5863 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5865 // Transform as necessary
5867 DAG.getNode(ISD::SRL, MVT::i16,
5868 DAG.getNode(ISD::AND, MVT::i16,
5869 CWD, DAG.getConstant(0x800, MVT::i16)),
5870 DAG.getConstant(11, MVT::i8));
5872 DAG.getNode(ISD::SRL, MVT::i16,
5873 DAG.getNode(ISD::AND, MVT::i16,
5874 CWD, DAG.getConstant(0x400, MVT::i16)),
5875 DAG.getConstant(9, MVT::i8));
5878 DAG.getNode(ISD::AND, MVT::i16,
5879 DAG.getNode(ISD::ADD, MVT::i16,
5880 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5881 DAG.getConstant(1, MVT::i16)),
5882 DAG.getConstant(3, MVT::i16));
5885 return DAG.getNode((VT.getSizeInBits() < 16 ?
5886 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5889 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5890 MVT VT = Op.getValueType();
5892 unsigned NumBits = VT.getSizeInBits();
5894 Op = Op.getOperand(0);
5895 if (VT == MVT::i8) {
5896 // Zero extend to i32 since there is not an i8 bsr.
5898 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5901 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5902 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5903 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5905 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5906 SmallVector<SDValue, 4> Ops;
5908 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5909 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5910 Ops.push_back(Op.getValue(1));
5911 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5913 // Finally xor with NumBits-1.
5914 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5917 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5921 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5922 MVT VT = Op.getValueType();
5924 unsigned NumBits = VT.getSizeInBits();
5926 Op = Op.getOperand(0);
5927 if (VT == MVT::i8) {
5929 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5932 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5933 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5934 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5936 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5937 SmallVector<SDValue, 4> Ops;
5939 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5940 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5941 Ops.push_back(Op.getValue(1));
5942 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5945 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5949 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5950 MVT T = Op.getValueType();
5953 switch(T.getSimpleVT()) {
5955 assert(false && "Invalid value type!");
5956 case MVT::i8: Reg = X86::AL; size = 1; break;
5957 case MVT::i16: Reg = X86::AX; size = 2; break;
5958 case MVT::i32: Reg = X86::EAX; size = 4; break;
5960 if (Subtarget->is64Bit()) {
5961 Reg = X86::RAX; size = 8;
5962 } else //Should go away when LowerType stuff lands
5963 return SDValue(ExpandATOMIC_CMP_SWAP(Op.getNode(), DAG), 0);
5966 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5967 Op.getOperand(2), SDValue());
5968 SDValue Ops[] = { cpIn.getValue(0),
5971 DAG.getTargetConstant(size, MVT::i8),
5973 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5974 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5976 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5980 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op,
5981 SelectionDAG &DAG) {
5982 MVT T = Op->getValueType(0);
5983 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5984 SDValue cpInL, cpInH;
5985 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5986 DAG.getConstant(0, MVT::i32));
5987 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5988 DAG.getConstant(1, MVT::i32));
5989 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5991 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5992 cpInH, cpInL.getValue(1));
5993 SDValue swapInL, swapInH;
5994 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5995 DAG.getConstant(0, MVT::i32));
5996 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5997 DAG.getConstant(1, MVT::i32));
5998 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5999 swapInL, cpInH.getValue(1));
6000 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
6001 swapInH, swapInL.getValue(1));
6002 SDValue Ops[] = { swapInH.getValue(0),
6004 swapInH.getValue(1) };
6005 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6006 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6007 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6008 Result.getValue(1));
6009 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6010 cpOutL.getValue(2));
6011 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6012 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
6013 SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
6014 return DAG.getMergeValues(Vals, 2).getNode();
6017 SDValue X86TargetLowering::LowerATOMIC_BINARY_64(SDValue Op,
6020 SDNode *Node = Op.getNode();
6021 MVT T = Node->getValueType(0);
6022 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6024 SDValue Chain = Node->getOperand(0);
6025 SDValue In1 = Node->getOperand(1);
6026 assert(Node->getOperand(2).getNode()->getOpcode()==ISD::BUILD_PAIR);
6027 SDValue In2L = Node->getOperand(2).getNode()->getOperand(0);
6028 SDValue In2H = Node->getOperand(2).getNode()->getOperand(1);
6029 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6030 // have a MemOperand. Pass the info through as a normal operand.
6031 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6032 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6033 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6034 SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6035 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6036 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
6037 SDValue Vals[2] = { ResultVal, Result.getValue(2) };
6038 return SDValue(DAG.getMergeValues(Vals, 2).getNode(), 0);
6041 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6042 SDNode *Node = Op.getNode();
6043 MVT T = Node->getValueType(0);
6044 SDValue negOp = DAG.getNode(ISD::SUB, T,
6045 DAG.getConstant(0, T), Node->getOperand(2));
6046 return DAG.getAtomic((Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_8 ?
6047 ISD::ATOMIC_LOAD_ADD_8 :
6048 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_16 ?
6049 ISD::ATOMIC_LOAD_ADD_16 :
6050 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_32 ?
6051 ISD::ATOMIC_LOAD_ADD_32 :
6052 ISD::ATOMIC_LOAD_ADD_64),
6053 Node->getOperand(0),
6054 Node->getOperand(1), negOp,
6055 cast<AtomicSDNode>(Node)->getSrcValue(),
6056 cast<AtomicSDNode>(Node)->getAlignment());
6059 /// LowerOperation - Provide custom lowering hooks for some operations.
6061 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6062 switch (Op.getOpcode()) {
6063 default: assert(0 && "Should not custom lower this!");
6064 case ISD::ATOMIC_CMP_SWAP_8:
6065 case ISD::ATOMIC_CMP_SWAP_16:
6066 case ISD::ATOMIC_CMP_SWAP_32:
6067 case ISD::ATOMIC_CMP_SWAP_64: return LowerCMP_SWAP(Op,DAG);
6068 case ISD::ATOMIC_LOAD_SUB_8:
6069 case ISD::ATOMIC_LOAD_SUB_16:
6070 case ISD::ATOMIC_LOAD_SUB_32: return LowerLOAD_SUB(Op,DAG);
6071 case ISD::ATOMIC_LOAD_SUB_64: return (Subtarget->is64Bit()) ?
6072 LowerLOAD_SUB(Op,DAG) :
6073 LowerATOMIC_BINARY_64(Op,DAG,
6074 X86ISD::ATOMSUB64_DAG);
6075 case ISD::ATOMIC_LOAD_AND_64: return LowerATOMIC_BINARY_64(Op,DAG,
6076 X86ISD::ATOMAND64_DAG);
6077 case ISD::ATOMIC_LOAD_OR_64: return LowerATOMIC_BINARY_64(Op, DAG,
6078 X86ISD::ATOMOR64_DAG);
6079 case ISD::ATOMIC_LOAD_XOR_64: return LowerATOMIC_BINARY_64(Op,DAG,
6080 X86ISD::ATOMXOR64_DAG);
6081 case ISD::ATOMIC_LOAD_NAND_64: return LowerATOMIC_BINARY_64(Op,DAG,
6082 X86ISD::ATOMNAND64_DAG);
6083 case ISD::ATOMIC_LOAD_ADD_64: return LowerATOMIC_BINARY_64(Op,DAG,
6084 X86ISD::ATOMADD64_DAG);
6085 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6086 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6087 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6088 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6089 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6090 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6091 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6092 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6093 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6094 case ISD::SHL_PARTS:
6095 case ISD::SRA_PARTS:
6096 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6097 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6098 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6099 case ISD::FABS: return LowerFABS(Op, DAG);
6100 case ISD::FNEG: return LowerFNEG(Op, DAG);
6101 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6102 case ISD::SETCC: return LowerSETCC(Op, DAG);
6103 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6104 case ISD::SELECT: return LowerSELECT(Op, DAG);
6105 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6106 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6107 case ISD::CALL: return LowerCALL(Op, DAG);
6108 case ISD::RET: return LowerRET(Op, DAG);
6109 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6110 case ISD::VASTART: return LowerVASTART(Op, DAG);
6111 case ISD::VAARG: return LowerVAARG(Op, DAG);
6112 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6113 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6114 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6115 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6116 case ISD::FRAME_TO_ARGS_OFFSET:
6117 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6118 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6119 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6120 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6121 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6122 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6123 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6125 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
6126 case ISD::READCYCLECOUNTER:
6127 return SDValue(ExpandREADCYCLECOUNTER(Op.getNode(), DAG), 0);
6131 /// ReplaceNodeResults - Replace a node with an illegal result type
6132 /// with a new node built out of custom code.
6133 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
6134 switch (N->getOpcode()) {
6135 default: assert(0 && "Should not custom lower this!");
6136 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
6137 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
6138 case ISD::ATOMIC_CMP_SWAP_64: return ExpandATOMIC_CMP_SWAP(N, DAG);
6142 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6144 default: return NULL;
6145 case X86ISD::BSF: return "X86ISD::BSF";
6146 case X86ISD::BSR: return "X86ISD::BSR";
6147 case X86ISD::SHLD: return "X86ISD::SHLD";
6148 case X86ISD::SHRD: return "X86ISD::SHRD";
6149 case X86ISD::FAND: return "X86ISD::FAND";
6150 case X86ISD::FOR: return "X86ISD::FOR";
6151 case X86ISD::FXOR: return "X86ISD::FXOR";
6152 case X86ISD::FSRL: return "X86ISD::FSRL";
6153 case X86ISD::FILD: return "X86ISD::FILD";
6154 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6155 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6156 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6157 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6158 case X86ISD::FLD: return "X86ISD::FLD";
6159 case X86ISD::FST: return "X86ISD::FST";
6160 case X86ISD::CALL: return "X86ISD::CALL";
6161 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6162 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6163 case X86ISD::CMP: return "X86ISD::CMP";
6164 case X86ISD::COMI: return "X86ISD::COMI";
6165 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6166 case X86ISD::SETCC: return "X86ISD::SETCC";
6167 case X86ISD::CMOV: return "X86ISD::CMOV";
6168 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6169 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6170 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6171 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6172 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6173 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6174 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6175 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6176 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6177 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6178 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6179 case X86ISD::FMAX: return "X86ISD::FMAX";
6180 case X86ISD::FMIN: return "X86ISD::FMIN";
6181 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6182 case X86ISD::FRCP: return "X86ISD::FRCP";
6183 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6184 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6185 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6186 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6187 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6188 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6189 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6190 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6191 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6192 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6193 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6194 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6195 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6196 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6197 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6198 case X86ISD::VSHL: return "X86ISD::VSHL";
6199 case X86ISD::VSRL: return "X86ISD::VSRL";
6200 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6201 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6202 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6203 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6204 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6205 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6206 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6207 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6208 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6209 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6213 // isLegalAddressingMode - Return true if the addressing mode represented
6214 // by AM is legal for this target, for a load/store of the specified type.
6215 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6216 const Type *Ty) const {
6217 // X86 supports extremely general addressing modes.
6219 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6220 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6224 // We can only fold this if we don't need an extra load.
6225 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6228 // X86-64 only supports addr of globals in small code model.
6229 if (Subtarget->is64Bit()) {
6230 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6232 // If lower 4G is not available, then we must use rip-relative addressing.
6233 if (AM.BaseOffs || AM.Scale > 1)
6244 // These scales always work.
6249 // These scales are formed with basereg+scalereg. Only accept if there is
6254 default: // Other stuff never works.
6262 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6263 if (!Ty1->isInteger() || !Ty2->isInteger())
6265 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6266 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6267 if (NumBits1 <= NumBits2)
6269 return Subtarget->is64Bit() || NumBits1 < 64;
6272 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6273 if (!VT1.isInteger() || !VT2.isInteger())
6275 unsigned NumBits1 = VT1.getSizeInBits();
6276 unsigned NumBits2 = VT2.getSizeInBits();
6277 if (NumBits1 <= NumBits2)
6279 return Subtarget->is64Bit() || NumBits1 < 64;
6282 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6283 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6284 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6285 /// are assumed to be legal.
6287 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6288 // Only do shuffles on 128-bit vector types for now.
6289 if (VT.getSizeInBits() == 64) return false;
6290 return (Mask.getNode()->getNumOperands() <= 4 ||
6291 isIdentityMask(Mask.getNode()) ||
6292 isIdentityMask(Mask.getNode(), true) ||
6293 isSplatMask(Mask.getNode()) ||
6294 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6295 X86::isUNPCKLMask(Mask.getNode()) ||
6296 X86::isUNPCKHMask(Mask.getNode()) ||
6297 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6298 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6302 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6303 MVT EVT, SelectionDAG &DAG) const {
6304 unsigned NumElts = BVOps.size();
6305 // Only do shuffles on 128-bit vector types for now.
6306 if (EVT.getSizeInBits() * NumElts == 64) return false;
6307 if (NumElts == 2) return true;
6309 return (isMOVLMask(&BVOps[0], 4) ||
6310 isCommutedMOVL(&BVOps[0], 4, true) ||
6311 isSHUFPMask(&BVOps[0], 4) ||
6312 isCommutedSHUFP(&BVOps[0], 4));
6317 //===----------------------------------------------------------------------===//
6318 // X86 Scheduler Hooks
6319 //===----------------------------------------------------------------------===//
6321 // private utility function
6323 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6324 MachineBasicBlock *MBB,
6332 TargetRegisterClass *RC,
6334 // For the atomic bitwise operator, we generate
6337 // ld t1 = [bitinstr.addr]
6338 // op t2 = t1, [bitinstr.val]
6340 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6342 // fallthrough -->nextMBB
6343 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6344 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6345 MachineFunction::iterator MBBIter = MBB;
6348 /// First build the CFG
6349 MachineFunction *F = MBB->getParent();
6350 MachineBasicBlock *thisMBB = MBB;
6351 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6352 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6353 F->insert(MBBIter, newMBB);
6354 F->insert(MBBIter, nextMBB);
6356 // Move all successors to thisMBB to nextMBB
6357 nextMBB->transferSuccessors(thisMBB);
6359 // Update thisMBB to fall through to newMBB
6360 thisMBB->addSuccessor(newMBB);
6362 // newMBB jumps to itself and fall through to nextMBB
6363 newMBB->addSuccessor(nextMBB);
6364 newMBB->addSuccessor(newMBB);
6366 // Insert instructions into newMBB based on incoming instruction
6367 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6368 MachineOperand& destOper = bInstr->getOperand(0);
6369 MachineOperand* argOpers[6];
6370 int numArgs = bInstr->getNumOperands() - 1;
6371 for (int i=0; i < numArgs; ++i)
6372 argOpers[i] = &bInstr->getOperand(i+1);
6374 // x86 address has 4 operands: base, index, scale, and displacement
6375 int lastAddrIndx = 3; // [0,3]
6378 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6379 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6380 for (int i=0; i <= lastAddrIndx; ++i)
6381 (*MIB).addOperand(*argOpers[i]);
6383 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6385 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6390 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6391 assert((argOpers[valArgIndx]->isReg() ||
6392 argOpers[valArgIndx]->isImm()) &&
6394 if (argOpers[valArgIndx]->isReg())
6395 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6397 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6399 (*MIB).addOperand(*argOpers[valArgIndx]);
6401 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6404 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6405 for (int i=0; i <= lastAddrIndx; ++i)
6406 (*MIB).addOperand(*argOpers[i]);
6408 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6409 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6411 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6415 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6417 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6421 // private utility function: 64 bit atomics on 32 bit host.
6423 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
6424 MachineBasicBlock *MBB,
6430 // For the atomic bitwise operator, we generate
6431 // thisMBB (instructions are in pairs, except cmpxchg8b)
6432 // ld t1,t2 = [bitinstr.addr]
6434 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
6435 // op t5, t6 <- out1, out2, [bitinstr.val]
6436 // mov ECX, EBX <- t5, t6
6437 // mov EAX, EDX <- t1, t2
6438 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
6439 // mov t3, t4 <- EAX, EDX
6441 // result in out1, out2
6442 // fallthrough -->nextMBB
6444 const TargetRegisterClass *RC = X86::GR32RegisterClass;
6445 const unsigned LoadOpc = X86::MOV32rm;
6446 const unsigned copyOpc = X86::MOV32rr;
6447 const unsigned NotOpc = X86::NOT32r;
6448 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6449 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6450 MachineFunction::iterator MBBIter = MBB;
6453 /// First build the CFG
6454 MachineFunction *F = MBB->getParent();
6455 MachineBasicBlock *thisMBB = MBB;
6456 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6457 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6458 F->insert(MBBIter, newMBB);
6459 F->insert(MBBIter, nextMBB);
6461 // Move all successors to thisMBB to nextMBB
6462 nextMBB->transferSuccessors(thisMBB);
6464 // Update thisMBB to fall through to newMBB
6465 thisMBB->addSuccessor(newMBB);
6467 // newMBB jumps to itself and fall through to nextMBB
6468 newMBB->addSuccessor(nextMBB);
6469 newMBB->addSuccessor(newMBB);
6471 // Insert instructions into newMBB based on incoming instruction
6472 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
6473 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
6474 MachineOperand& dest1Oper = bInstr->getOperand(0);
6475 MachineOperand& dest2Oper = bInstr->getOperand(1);
6476 MachineOperand* argOpers[6];
6477 for (int i=0; i < 6; ++i)
6478 argOpers[i] = &bInstr->getOperand(i+2);
6480 // x86 address has 4 operands: base, index, scale, and displacement
6481 int lastAddrIndx = 3; // [0,3]
6483 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6484 MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
6485 for (int i=0; i <= lastAddrIndx; ++i)
6486 (*MIB).addOperand(*argOpers[i]);
6487 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6488 MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
6489 // add 4 to displacement. getImm verifies it's immediate.
6490 for (int i=0; i <= lastAddrIndx-1; ++i)
6491 (*MIB).addOperand(*argOpers[i]);
6492 MachineOperand newOp3 = MachineOperand::CreateImm(argOpers[3]->getImm()+4);
6493 (*MIB).addOperand(newOp3);
6495 // t3/4 are defined later, at the bottom of the loop
6496 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
6497 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
6498 BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
6499 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
6500 BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
6501 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
6503 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
6504 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
6506 MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
6507 MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
6513 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
6515 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
6516 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
6517 if (argOpers[4]->isReg())
6518 MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
6520 MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
6522 (*MIB).addOperand(*argOpers[4]);
6523 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
6524 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
6525 if (argOpers[5]->isReg())
6526 MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
6528 MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
6530 (*MIB).addOperand(*argOpers[5]);
6532 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
6534 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
6537 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
6539 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
6542 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
6543 for (int i=0; i <= lastAddrIndx; ++i)
6544 (*MIB).addOperand(*argOpers[i]);
6546 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6547 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6549 MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
6550 MIB.addReg(X86::EAX);
6551 MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
6552 MIB.addReg(X86::EDX);
6555 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6557 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6561 // private utility function
6563 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6564 MachineBasicBlock *MBB,
6566 // For the atomic min/max operator, we generate
6569 // ld t1 = [min/max.addr]
6570 // mov t2 = [min/max.val]
6572 // cmov[cond] t2 = t1
6574 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6576 // fallthrough -->nextMBB
6578 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6579 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6580 MachineFunction::iterator MBBIter = MBB;
6583 /// First build the CFG
6584 MachineFunction *F = MBB->getParent();
6585 MachineBasicBlock *thisMBB = MBB;
6586 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6587 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6588 F->insert(MBBIter, newMBB);
6589 F->insert(MBBIter, nextMBB);
6591 // Move all successors to thisMBB to nextMBB
6592 nextMBB->transferSuccessors(thisMBB);
6594 // Update thisMBB to fall through to newMBB
6595 thisMBB->addSuccessor(newMBB);
6597 // newMBB jumps to newMBB and fall through to nextMBB
6598 newMBB->addSuccessor(nextMBB);
6599 newMBB->addSuccessor(newMBB);
6601 // Insert instructions into newMBB based on incoming instruction
6602 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6603 MachineOperand& destOper = mInstr->getOperand(0);
6604 MachineOperand* argOpers[6];
6605 int numArgs = mInstr->getNumOperands() - 1;
6606 for (int i=0; i < numArgs; ++i)
6607 argOpers[i] = &mInstr->getOperand(i+1);
6609 // x86 address has 4 operands: base, index, scale, and displacement
6610 int lastAddrIndx = 3; // [0,3]
6613 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6614 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6615 for (int i=0; i <= lastAddrIndx; ++i)
6616 (*MIB).addOperand(*argOpers[i]);
6618 // We only support register and immediate values
6619 assert((argOpers[valArgIndx]->isReg() ||
6620 argOpers[valArgIndx]->isImm()) &&
6623 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6624 if (argOpers[valArgIndx]->isReg())
6625 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6627 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6628 (*MIB).addOperand(*argOpers[valArgIndx]);
6630 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6633 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6638 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6639 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6643 // Cmp and exchange if none has modified the memory location
6644 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6645 for (int i=0; i <= lastAddrIndx; ++i)
6646 (*MIB).addOperand(*argOpers[i]);
6648 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6649 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6651 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6652 MIB.addReg(X86::EAX);
6655 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6657 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
6663 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6664 MachineBasicBlock *BB) {
6665 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6666 switch (MI->getOpcode()) {
6667 default: assert(false && "Unexpected instr type to insert");
6668 case X86::CMOV_FR32:
6669 case X86::CMOV_FR64:
6670 case X86::CMOV_V4F32:
6671 case X86::CMOV_V2F64:
6672 case X86::CMOV_V2I64: {
6673 // To "insert" a SELECT_CC instruction, we actually have to insert the
6674 // diamond control-flow pattern. The incoming instruction knows the
6675 // destination vreg to set, the condition code register to branch on, the
6676 // true/false values to select between, and a branch opcode to use.
6677 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6678 MachineFunction::iterator It = BB;
6684 // cmpTY ccX, r1, r2
6686 // fallthrough --> copy0MBB
6687 MachineBasicBlock *thisMBB = BB;
6688 MachineFunction *F = BB->getParent();
6689 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6690 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6692 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6693 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6694 F->insert(It, copy0MBB);
6695 F->insert(It, sinkMBB);
6696 // Update machine-CFG edges by transferring all successors of the current
6697 // block to the new block which will contain the Phi node for the select.
6698 sinkMBB->transferSuccessors(BB);
6700 // Add the true and fallthrough blocks as its successors.
6701 BB->addSuccessor(copy0MBB);
6702 BB->addSuccessor(sinkMBB);
6705 // %FalseValue = ...
6706 // # fallthrough to sinkMBB
6709 // Update machine-CFG edges
6710 BB->addSuccessor(sinkMBB);
6713 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6716 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6717 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6718 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6720 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6724 case X86::FP32_TO_INT16_IN_MEM:
6725 case X86::FP32_TO_INT32_IN_MEM:
6726 case X86::FP32_TO_INT64_IN_MEM:
6727 case X86::FP64_TO_INT16_IN_MEM:
6728 case X86::FP64_TO_INT32_IN_MEM:
6729 case X86::FP64_TO_INT64_IN_MEM:
6730 case X86::FP80_TO_INT16_IN_MEM:
6731 case X86::FP80_TO_INT32_IN_MEM:
6732 case X86::FP80_TO_INT64_IN_MEM: {
6733 // Change the floating point control register to use "round towards zero"
6734 // mode when truncating to an integer value.
6735 MachineFunction *F = BB->getParent();
6736 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6737 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6739 // Load the old value of the high byte of the control word...
6741 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6742 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6744 // Set the high part to be round to zero...
6745 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6748 // Reload the modified control word now...
6749 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6751 // Restore the memory image of control word to original value
6752 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6755 // Get the X86 opcode to use.
6757 switch (MI->getOpcode()) {
6758 default: assert(0 && "illegal opcode!");
6759 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6760 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6761 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6762 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6763 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6764 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6765 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6766 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6767 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6771 MachineOperand &Op = MI->getOperand(0);
6773 AM.BaseType = X86AddressMode::RegBase;
6774 AM.Base.Reg = Op.getReg();
6776 AM.BaseType = X86AddressMode::FrameIndexBase;
6777 AM.Base.FrameIndex = Op.getIndex();
6779 Op = MI->getOperand(1);
6781 AM.Scale = Op.getImm();
6782 Op = MI->getOperand(2);
6784 AM.IndexReg = Op.getImm();
6785 Op = MI->getOperand(3);
6786 if (Op.isGlobal()) {
6787 AM.GV = Op.getGlobal();
6789 AM.Disp = Op.getImm();
6791 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6792 .addReg(MI->getOperand(4).getReg());
6794 // Reload the original control word now.
6795 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6797 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6800 case X86::ATOMAND32:
6801 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6802 X86::AND32ri, X86::MOV32rm,
6803 X86::LCMPXCHG32, X86::MOV32rr,
6804 X86::NOT32r, X86::EAX,
6805 X86::GR32RegisterClass);
6807 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6808 X86::OR32ri, X86::MOV32rm,
6809 X86::LCMPXCHG32, X86::MOV32rr,
6810 X86::NOT32r, X86::EAX,
6811 X86::GR32RegisterClass);
6812 case X86::ATOMXOR32:
6813 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6814 X86::XOR32ri, X86::MOV32rm,
6815 X86::LCMPXCHG32, X86::MOV32rr,
6816 X86::NOT32r, X86::EAX,
6817 X86::GR32RegisterClass);
6818 case X86::ATOMNAND32:
6819 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6820 X86::AND32ri, X86::MOV32rm,
6821 X86::LCMPXCHG32, X86::MOV32rr,
6822 X86::NOT32r, X86::EAX,
6823 X86::GR32RegisterClass, true);
6824 case X86::ATOMMIN32:
6825 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6826 case X86::ATOMMAX32:
6827 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6828 case X86::ATOMUMIN32:
6829 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6830 case X86::ATOMUMAX32:
6831 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6833 case X86::ATOMAND16:
6834 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6835 X86::AND16ri, X86::MOV16rm,
6836 X86::LCMPXCHG16, X86::MOV16rr,
6837 X86::NOT16r, X86::AX,
6838 X86::GR16RegisterClass);
6840 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
6841 X86::OR16ri, X86::MOV16rm,
6842 X86::LCMPXCHG16, X86::MOV16rr,
6843 X86::NOT16r, X86::AX,
6844 X86::GR16RegisterClass);
6845 case X86::ATOMXOR16:
6846 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
6847 X86::XOR16ri, X86::MOV16rm,
6848 X86::LCMPXCHG16, X86::MOV16rr,
6849 X86::NOT16r, X86::AX,
6850 X86::GR16RegisterClass);
6851 case X86::ATOMNAND16:
6852 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6853 X86::AND16ri, X86::MOV16rm,
6854 X86::LCMPXCHG16, X86::MOV16rr,
6855 X86::NOT16r, X86::AX,
6856 X86::GR16RegisterClass, true);
6857 case X86::ATOMMIN16:
6858 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
6859 case X86::ATOMMAX16:
6860 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
6861 case X86::ATOMUMIN16:
6862 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
6863 case X86::ATOMUMAX16:
6864 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
6867 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6868 X86::AND8ri, X86::MOV8rm,
6869 X86::LCMPXCHG8, X86::MOV8rr,
6870 X86::NOT8r, X86::AL,
6871 X86::GR8RegisterClass);
6873 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
6874 X86::OR8ri, X86::MOV8rm,
6875 X86::LCMPXCHG8, X86::MOV8rr,
6876 X86::NOT8r, X86::AL,
6877 X86::GR8RegisterClass);
6879 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
6880 X86::XOR8ri, X86::MOV8rm,
6881 X86::LCMPXCHG8, X86::MOV8rr,
6882 X86::NOT8r, X86::AL,
6883 X86::GR8RegisterClass);
6884 case X86::ATOMNAND8:
6885 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6886 X86::AND8ri, X86::MOV8rm,
6887 X86::LCMPXCHG8, X86::MOV8rr,
6888 X86::NOT8r, X86::AL,
6889 X86::GR8RegisterClass, true);
6890 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
6891 // This group is for 64-bit host.
6892 case X86::ATOMAND64:
6893 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6894 X86::AND64ri32, X86::MOV64rm,
6895 X86::LCMPXCHG64, X86::MOV64rr,
6896 X86::NOT64r, X86::RAX,
6897 X86::GR64RegisterClass);
6899 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
6900 X86::OR64ri32, X86::MOV64rm,
6901 X86::LCMPXCHG64, X86::MOV64rr,
6902 X86::NOT64r, X86::RAX,
6903 X86::GR64RegisterClass);
6904 case X86::ATOMXOR64:
6905 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
6906 X86::XOR64ri32, X86::MOV64rm,
6907 X86::LCMPXCHG64, X86::MOV64rr,
6908 X86::NOT64r, X86::RAX,
6909 X86::GR64RegisterClass);
6910 case X86::ATOMNAND64:
6911 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6912 X86::AND64ri32, X86::MOV64rm,
6913 X86::LCMPXCHG64, X86::MOV64rr,
6914 X86::NOT64r, X86::RAX,
6915 X86::GR64RegisterClass, true);
6916 case X86::ATOMMIN64:
6917 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
6918 case X86::ATOMMAX64:
6919 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
6920 case X86::ATOMUMIN64:
6921 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
6922 case X86::ATOMUMAX64:
6923 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
6925 // This group does 64-bit operations on a 32-bit host.
6926 case X86::ATOMAND6432:
6927 return EmitAtomicBit6432WithCustomInserter(MI, BB,
6928 X86::AND32rr, X86::AND32rr,
6929 X86::AND32ri, X86::AND32ri,
6931 case X86::ATOMOR6432:
6932 return EmitAtomicBit6432WithCustomInserter(MI, BB,
6933 X86::OR32rr, X86::OR32rr,
6934 X86::OR32ri, X86::OR32ri,
6936 case X86::ATOMXOR6432:
6937 return EmitAtomicBit6432WithCustomInserter(MI, BB,
6938 X86::XOR32rr, X86::XOR32rr,
6939 X86::XOR32ri, X86::XOR32ri,
6941 case X86::ATOMNAND6432:
6942 return EmitAtomicBit6432WithCustomInserter(MI, BB,
6943 X86::AND32rr, X86::AND32rr,
6944 X86::AND32ri, X86::AND32ri,
6947 case X86::ATOMADD6432:
6948 return EmitAtomicBit6432WithCustomInserter(MI, BB,
6949 X86::ADD32rr, X86::ADC32rr,
6950 X86::ADD32ri, X86::ADC32ri,
6953 case X86::ATOMSUB6432:
6954 return EmitAtomicBit6432WithCustomInserter(MI, BB,
6955 X86::SUB32rr, X86::SBB32rr,
6956 X86::SUB32ri, X86::SBB32ri,
6961 //===----------------------------------------------------------------------===//
6962 // X86 Optimization Hooks
6963 //===----------------------------------------------------------------------===//
6965 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6969 const SelectionDAG &DAG,
6970 unsigned Depth) const {
6971 unsigned Opc = Op.getOpcode();
6972 assert((Opc >= ISD::BUILTIN_OP_END ||
6973 Opc == ISD::INTRINSIC_WO_CHAIN ||
6974 Opc == ISD::INTRINSIC_W_CHAIN ||
6975 Opc == ISD::INTRINSIC_VOID) &&
6976 "Should use MaskedValueIsZero if you don't know whether Op"
6977 " is a target node!");
6979 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6983 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6984 Mask.getBitWidth() - 1);
6989 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6990 /// node is a GlobalAddress + offset.
6991 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6992 GlobalValue* &GA, int64_t &Offset) const{
6993 if (N->getOpcode() == X86ISD::Wrapper) {
6994 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6995 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6999 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7002 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7003 const TargetLowering &TLI) {
7006 if (TLI.isGAPlusOffset(Base, GV, Offset))
7007 return (GV->getAlignment() >= N && (Offset % N) == 0);
7008 // DAG combine handles the stack object case.
7012 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7013 unsigned NumElems, MVT EVT,
7015 SelectionDAG &DAG, MachineFrameInfo *MFI,
7016 const TargetLowering &TLI) {
7018 for (unsigned i = 0; i < NumElems; ++i) {
7019 SDValue Idx = PermMask.getOperand(i);
7020 if (Idx.getOpcode() == ISD::UNDEF) {
7026 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7027 if (!Elt.getNode() ||
7028 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7031 Base = Elt.getNode();
7032 if (Base->getOpcode() == ISD::UNDEF)
7036 if (Elt.getOpcode() == ISD::UNDEF)
7039 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7040 EVT.getSizeInBits()/8, i, MFI))
7046 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7047 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7048 /// if the load addresses are consecutive, non-overlapping, and in the right
7050 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7051 const TargetLowering &TLI) {
7052 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7053 MVT VT = N->getValueType(0);
7054 MVT EVT = VT.getVectorElementType();
7055 SDValue PermMask = N->getOperand(2);
7056 unsigned NumElems = PermMask.getNumOperands();
7057 SDNode *Base = NULL;
7058 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7062 LoadSDNode *LD = cast<LoadSDNode>(Base);
7063 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7064 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7065 LD->getSrcValueOffset(), LD->isVolatile());
7066 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7067 LD->getSrcValueOffset(), LD->isVolatile(),
7068 LD->getAlignment());
7071 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7072 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7073 const X86Subtarget *Subtarget,
7074 const TargetLowering &TLI) {
7075 unsigned NumOps = N->getNumOperands();
7077 // Ignore single operand BUILD_VECTOR.
7081 MVT VT = N->getValueType(0);
7082 MVT EVT = VT.getVectorElementType();
7083 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7084 // We are looking for load i64 and zero extend. We want to transform
7085 // it before legalizer has a chance to expand it. Also look for i64
7086 // BUILD_PAIR bit casted to f64.
7088 // This must be an insertion into a zero vector.
7089 SDValue HighElt = N->getOperand(1);
7090 if (!isZeroNode(HighElt))
7093 // Value must be a load.
7094 SDNode *Base = N->getOperand(0).getNode();
7095 if (!isa<LoadSDNode>(Base)) {
7096 if (Base->getOpcode() != ISD::BIT_CONVERT)
7098 Base = Base->getOperand(0).getNode();
7099 if (!isa<LoadSDNode>(Base))
7103 // Transform it into VZEXT_LOAD addr.
7104 LoadSDNode *LD = cast<LoadSDNode>(Base);
7106 // Load must not be an extload.
7107 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7110 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7111 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7112 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7113 DAG.ReplaceAllUsesOfValueWith(SDValue(Base, 1), ResNode.getValue(1));
7117 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7118 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7119 const X86Subtarget *Subtarget) {
7120 SDValue Cond = N->getOperand(0);
7122 // If we have SSE[12] support, try to form min/max nodes.
7123 if (Subtarget->hasSSE2() &&
7124 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7125 if (Cond.getOpcode() == ISD::SETCC) {
7126 // Get the LHS/RHS of the select.
7127 SDValue LHS = N->getOperand(1);
7128 SDValue RHS = N->getOperand(2);
7129 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7131 unsigned Opcode = 0;
7132 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7135 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7138 if (!UnsafeFPMath) break;
7140 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7142 Opcode = X86ISD::FMIN;
7145 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7148 if (!UnsafeFPMath) break;
7150 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7152 Opcode = X86ISD::FMAX;
7155 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7158 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7161 if (!UnsafeFPMath) break;
7163 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7165 Opcode = X86ISD::FMIN;
7168 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7171 if (!UnsafeFPMath) break;
7173 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7175 Opcode = X86ISD::FMAX;
7181 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7189 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7190 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7191 const X86Subtarget *Subtarget) {
7192 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7193 // the FP state in cases where an emms may be missing.
7194 // A preferable solution to the general problem is to figure out the right
7195 // places to insert EMMS. This qualifies as a quick hack.
7196 StoreSDNode *St = cast<StoreSDNode>(N);
7197 if (St->getValue().getValueType().isVector() &&
7198 St->getValue().getValueType().getSizeInBits() == 64 &&
7199 isa<LoadSDNode>(St->getValue()) &&
7200 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7201 St->getChain().hasOneUse() && !St->isVolatile()) {
7202 SDNode* LdVal = St->getValue().getNode();
7204 int TokenFactorIndex = -1;
7205 SmallVector<SDValue, 8> Ops;
7206 SDNode* ChainVal = St->getChain().getNode();
7207 // Must be a store of a load. We currently handle two cases: the load
7208 // is a direct child, and it's under an intervening TokenFactor. It is
7209 // possible to dig deeper under nested TokenFactors.
7210 if (ChainVal == LdVal)
7211 Ld = cast<LoadSDNode>(St->getChain());
7212 else if (St->getValue().hasOneUse() &&
7213 ChainVal->getOpcode() == ISD::TokenFactor) {
7214 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7215 if (ChainVal->getOperand(i).getNode() == LdVal) {
7216 TokenFactorIndex = i;
7217 Ld = cast<LoadSDNode>(St->getValue());
7219 Ops.push_back(ChainVal->getOperand(i));
7223 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7224 if (Subtarget->is64Bit()) {
7225 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
7226 Ld->getBasePtr(), Ld->getSrcValue(),
7227 Ld->getSrcValueOffset(), Ld->isVolatile(),
7228 Ld->getAlignment());
7229 SDValue NewChain = NewLd.getValue(1);
7230 if (TokenFactorIndex != -1) {
7231 Ops.push_back(NewChain);
7232 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7235 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7236 St->getSrcValue(), St->getSrcValueOffset(),
7237 St->isVolatile(), St->getAlignment());
7240 // Otherwise, lower to two 32-bit copies.
7241 SDValue LoAddr = Ld->getBasePtr();
7242 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7243 DAG.getConstant(4, MVT::i32));
7245 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7246 Ld->getSrcValue(), Ld->getSrcValueOffset(),
7247 Ld->isVolatile(), Ld->getAlignment());
7248 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7249 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7251 MinAlign(Ld->getAlignment(), 4));
7253 SDValue NewChain = LoLd.getValue(1);
7254 if (TokenFactorIndex != -1) {
7255 Ops.push_back(LoLd);
7256 Ops.push_back(HiLd);
7257 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7261 LoAddr = St->getBasePtr();
7262 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7263 DAG.getConstant(4, MVT::i32));
7265 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7266 St->getSrcValue(), St->getSrcValueOffset(),
7267 St->isVolatile(), St->getAlignment());
7268 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7270 St->getSrcValueOffset() + 4,
7272 MinAlign(St->getAlignment(), 4));
7273 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7279 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7280 /// X86ISD::FXOR nodes.
7281 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7282 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7283 // F[X]OR(0.0, x) -> x
7284 // F[X]OR(x, 0.0) -> x
7285 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7286 if (C->getValueAPF().isPosZero())
7287 return N->getOperand(1);
7288 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7289 if (C->getValueAPF().isPosZero())
7290 return N->getOperand(0);
7294 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7295 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7296 // FAND(0.0, x) -> 0.0
7297 // FAND(x, 0.0) -> 0.0
7298 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7299 if (C->getValueAPF().isPosZero())
7300 return N->getOperand(0);
7301 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7302 if (C->getValueAPF().isPosZero())
7303 return N->getOperand(1);
7308 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7309 DAGCombinerInfo &DCI) const {
7310 SelectionDAG &DAG = DCI.DAG;
7311 switch (N->getOpcode()) {
7313 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7314 case ISD::BUILD_VECTOR:
7315 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7316 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
7317 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
7319 case X86ISD::FOR: return PerformFORCombine(N, DAG);
7320 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
7326 //===----------------------------------------------------------------------===//
7327 // X86 Inline Assembly Support
7328 //===----------------------------------------------------------------------===//
7330 /// getConstraintType - Given a constraint letter, return the type of
7331 /// constraint it is for this target.
7332 X86TargetLowering::ConstraintType
7333 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7334 if (Constraint.size() == 1) {
7335 switch (Constraint[0]) {
7346 return C_RegisterClass;
7351 return TargetLowering::getConstraintType(Constraint);
7354 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7355 /// with another that has more specific requirements based on the type of the
7356 /// corresponding operand.
7357 const char *X86TargetLowering::
7358 LowerXConstraint(MVT ConstraintVT) const {
7359 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7360 // 'f' like normal targets.
7361 if (ConstraintVT.isFloatingPoint()) {
7362 if (Subtarget->hasSSE2())
7364 if (Subtarget->hasSSE1())
7368 return TargetLowering::LowerXConstraint(ConstraintVT);
7371 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7372 /// vector. If it is invalid, don't add anything to Ops.
7373 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7376 std::vector<SDValue>&Ops,
7377 SelectionDAG &DAG) const {
7378 SDValue Result(0, 0);
7380 switch (Constraint) {
7383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7384 if (C->getZExtValue() <= 31) {
7385 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7392 if (C->getZExtValue() <= 63) {
7393 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7399 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7400 if (C->getZExtValue() <= 255) {
7401 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7407 // Literal immediates are always ok.
7408 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7409 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7413 // If we are in non-pic codegen mode, we allow the address of a global (with
7414 // an optional displacement) to be used with 'i'.
7415 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7418 // Match either (GA) or (GA+C)
7420 Offset = GA->getOffset();
7421 } else if (Op.getOpcode() == ISD::ADD) {
7422 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7423 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7425 Offset = GA->getOffset()+C->getZExtValue();
7427 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7428 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7430 Offset = GA->getOffset()+C->getZExtValue();
7438 Op = LowerGlobalAddress(GA->getGlobal(), DAG);
7440 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7446 // Otherwise, not valid for this mode.
7451 if (Result.getNode()) {
7452 Ops.push_back(Result);
7455 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
7459 std::vector<unsigned> X86TargetLowering::
7460 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7462 if (Constraint.size() == 1) {
7463 // FIXME: not handling fp-stack yet!
7464 switch (Constraint[0]) { // GCC X86 Constraint Letters
7465 default: break; // Unknown constraint letter
7466 case 'A': // EAX/EDX
7467 if (VT == MVT::i32 || VT == MVT::i64)
7468 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7470 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
7473 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7474 else if (VT == MVT::i16)
7475 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7476 else if (VT == MVT::i8)
7477 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7478 else if (VT == MVT::i64)
7479 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7484 return std::vector<unsigned>();
7487 std::pair<unsigned, const TargetRegisterClass*>
7488 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7490 // First, see if this is a constraint that directly corresponds to an LLVM
7492 if (Constraint.size() == 1) {
7493 // GCC Constraint Letters
7494 switch (Constraint[0]) {
7496 case 'r': // GENERAL_REGS
7497 case 'R': // LEGACY_REGS
7498 case 'l': // INDEX_REGS
7499 if (VT == MVT::i64 && Subtarget->is64Bit())
7500 return std::make_pair(0U, X86::GR64RegisterClass);
7502 return std::make_pair(0U, X86::GR32RegisterClass);
7503 else if (VT == MVT::i16)
7504 return std::make_pair(0U, X86::GR16RegisterClass);
7505 else if (VT == MVT::i8)
7506 return std::make_pair(0U, X86::GR8RegisterClass);
7508 case 'f': // FP Stack registers.
7509 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7510 // value to the correct fpstack register class.
7511 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7512 return std::make_pair(0U, X86::RFP32RegisterClass);
7513 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7514 return std::make_pair(0U, X86::RFP64RegisterClass);
7515 return std::make_pair(0U, X86::RFP80RegisterClass);
7516 case 'y': // MMX_REGS if MMX allowed.
7517 if (!Subtarget->hasMMX()) break;
7518 return std::make_pair(0U, X86::VR64RegisterClass);
7520 case 'Y': // SSE_REGS if SSE2 allowed
7521 if (!Subtarget->hasSSE2()) break;
7523 case 'x': // SSE_REGS if SSE1 allowed
7524 if (!Subtarget->hasSSE1()) break;
7526 switch (VT.getSimpleVT()) {
7528 // Scalar SSE types.
7531 return std::make_pair(0U, X86::FR32RegisterClass);
7534 return std::make_pair(0U, X86::FR64RegisterClass);
7542 return std::make_pair(0U, X86::VR128RegisterClass);
7548 // Use the default implementation in TargetLowering to convert the register
7549 // constraint into a member of a register class.
7550 std::pair<unsigned, const TargetRegisterClass*> Res;
7551 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7553 // Not found as a standard register?
7554 if (Res.second == 0) {
7555 // GCC calls "st(0)" just plain "st".
7556 if (StringsEqualNoCase("{st}", Constraint)) {
7557 Res.first = X86::ST0;
7558 Res.second = X86::RFP80RegisterClass;
7564 // Otherwise, check to see if this is a register class of the wrong value
7565 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7566 // turn into {ax},{dx}.
7567 if (Res.second->hasType(VT))
7568 return Res; // Correct type already, nothing to do.
7570 // All of the single-register GCC register classes map their values onto
7571 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
7572 // really want an 8-bit or 32-bit register, map to the appropriate register
7573 // class and return the appropriate register.
7574 if (Res.second == X86::GR16RegisterClass) {
7575 if (VT == MVT::i8) {
7576 unsigned DestReg = 0;
7577 switch (Res.first) {
7579 case X86::AX: DestReg = X86::AL; break;
7580 case X86::DX: DestReg = X86::DL; break;
7581 case X86::CX: DestReg = X86::CL; break;
7582 case X86::BX: DestReg = X86::BL; break;
7585 Res.first = DestReg;
7586 Res.second = Res.second = X86::GR8RegisterClass;
7588 } else if (VT == MVT::i32) {
7589 unsigned DestReg = 0;
7590 switch (Res.first) {
7592 case X86::AX: DestReg = X86::EAX; break;
7593 case X86::DX: DestReg = X86::EDX; break;
7594 case X86::CX: DestReg = X86::ECX; break;
7595 case X86::BX: DestReg = X86::EBX; break;
7596 case X86::SI: DestReg = X86::ESI; break;
7597 case X86::DI: DestReg = X86::EDI; break;
7598 case X86::BP: DestReg = X86::EBP; break;
7599 case X86::SP: DestReg = X86::ESP; break;
7602 Res.first = DestReg;
7603 Res.second = Res.second = X86::GR32RegisterClass;
7605 } else if (VT == MVT::i64) {
7606 unsigned DestReg = 0;
7607 switch (Res.first) {
7609 case X86::AX: DestReg = X86::RAX; break;
7610 case X86::DX: DestReg = X86::RDX; break;
7611 case X86::CX: DestReg = X86::RCX; break;
7612 case X86::BX: DestReg = X86::RBX; break;
7613 case X86::SI: DestReg = X86::RSI; break;
7614 case X86::DI: DestReg = X86::RDI; break;
7615 case X86::BP: DestReg = X86::RBP; break;
7616 case X86::SP: DestReg = X86::RSP; break;
7619 Res.first = DestReg;
7620 Res.second = Res.second = X86::GR64RegisterClass;
7623 } else if (Res.second == X86::FR32RegisterClass ||
7624 Res.second == X86::FR64RegisterClass ||
7625 Res.second == X86::VR128RegisterClass) {
7626 // Handle references to XMM physical registers that got mapped into the
7627 // wrong class. This can happen with constraints like {xmm0} where the
7628 // target independent register mapper will just pick the first match it can
7629 // find, ignoring the required type.
7631 Res.second = X86::FR32RegisterClass;
7632 else if (VT == MVT::f64)
7633 Res.second = X86::FR64RegisterClass;
7634 else if (X86::VR128RegisterClass->hasType(VT))
7635 Res.second = X86::VR128RegisterClass;