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/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/StringExtras.h"
44 // Forward declarations.
45 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
47 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
48 : TargetLowering(TM) {
49 Subtarget = &TM.getSubtarget<X86Subtarget>();
50 X86ScalarSSEf64 = Subtarget->hasSSE2();
51 X86ScalarSSEf32 = Subtarget->hasSSE1();
52 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
56 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 if (!Subtarget->is64Bit())
263 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
266 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
267 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
269 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
270 if (Subtarget->is64Bit())
271 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
272 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
273 if (Subtarget->is64Bit()) {
274 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
275 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
276 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
277 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
279 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
280 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
281 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
282 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
283 if (Subtarget->is64Bit()) {
284 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
285 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
286 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
289 if (Subtarget->hasSSE1())
290 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
292 if (!Subtarget->hasSSE2())
293 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
295 // Expand certain atomics
296 setOperationAction(ISD::ATOMIC_LCS , MVT::i8, Custom);
297 setOperationAction(ISD::ATOMIC_LCS , MVT::i16, Custom);
298 setOperationAction(ISD::ATOMIC_LCS , MVT::i32, Custom);
299 setOperationAction(ISD::ATOMIC_LCS , MVT::i64, Custom);
300 setOperationAction(ISD::ATOMIC_LSS , MVT::i32, Expand);
302 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
303 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
304 // FIXME - use subtarget debug flags
305 if (!Subtarget->isTargetDarwin() &&
306 !Subtarget->isTargetELF() &&
307 !Subtarget->isTargetCygMing())
308 setOperationAction(ISD::LABEL, MVT::Other, Expand);
310 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
311 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
312 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
313 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
314 if (Subtarget->is64Bit()) {
316 setExceptionPointerRegister(X86::RAX);
317 setExceptionSelectorRegister(X86::RDX);
319 setExceptionPointerRegister(X86::EAX);
320 setExceptionSelectorRegister(X86::EDX);
322 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
324 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
326 setOperationAction(ISD::TRAP, MVT::Other, Legal);
328 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
329 setOperationAction(ISD::VASTART , MVT::Other, Custom);
330 setOperationAction(ISD::VAEND , MVT::Other, Expand);
331 if (Subtarget->is64Bit()) {
332 setOperationAction(ISD::VAARG , MVT::Other, Custom);
333 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
335 setOperationAction(ISD::VAARG , MVT::Other, Expand);
336 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
339 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
340 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
341 if (Subtarget->is64Bit())
342 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
343 if (Subtarget->isTargetCygMing())
344 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
346 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
348 if (X86ScalarSSEf64) {
349 // f32 and f64 use SSE.
350 // Set up the FP register classes.
351 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
352 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
354 // Use ANDPD to simulate FABS.
355 setOperationAction(ISD::FABS , MVT::f64, Custom);
356 setOperationAction(ISD::FABS , MVT::f32, Custom);
358 // Use XORP to simulate FNEG.
359 setOperationAction(ISD::FNEG , MVT::f64, Custom);
360 setOperationAction(ISD::FNEG , MVT::f32, Custom);
362 // Use ANDPD and ORPD to simulate FCOPYSIGN.
363 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
364 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
366 // We don't support sin/cos/fmod
367 setOperationAction(ISD::FSIN , MVT::f64, Expand);
368 setOperationAction(ISD::FCOS , MVT::f64, Expand);
369 setOperationAction(ISD::FSIN , MVT::f32, Expand);
370 setOperationAction(ISD::FCOS , MVT::f32, Expand);
372 // Expand FP immediates into loads from the stack, except for the special
374 addLegalFPImmediate(APFloat(+0.0)); // xorpd
375 addLegalFPImmediate(APFloat(+0.0f)); // xorps
377 // Floating truncations from f80 and extensions to f80 go through memory.
378 // If optimizing, we lie about this though and handle it in
379 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
381 setConvertAction(MVT::f32, MVT::f80, Expand);
382 setConvertAction(MVT::f64, MVT::f80, Expand);
383 setConvertAction(MVT::f80, MVT::f32, Expand);
384 setConvertAction(MVT::f80, MVT::f64, Expand);
386 } else if (X86ScalarSSEf32) {
387 // Use SSE for f32, x87 for f64.
388 // Set up the FP register classes.
389 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
390 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
392 // Use ANDPS to simulate FABS.
393 setOperationAction(ISD::FABS , MVT::f32, Custom);
395 // Use XORP to simulate FNEG.
396 setOperationAction(ISD::FNEG , MVT::f32, Custom);
398 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
400 // Use ANDPS and ORPS to simulate FCOPYSIGN.
401 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
402 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
404 // We don't support sin/cos/fmod
405 setOperationAction(ISD::FSIN , MVT::f32, Expand);
406 setOperationAction(ISD::FCOS , MVT::f32, Expand);
408 // Special cases we handle for FP constants.
409 addLegalFPImmediate(APFloat(+0.0f)); // xorps
410 addLegalFPImmediate(APFloat(+0.0)); // FLD0
411 addLegalFPImmediate(APFloat(+1.0)); // FLD1
412 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
413 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
415 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
416 // this though and handle it in InstructionSelectPreprocess so that
417 // dagcombine2 can hack on these.
419 setConvertAction(MVT::f32, MVT::f64, Expand);
420 setConvertAction(MVT::f32, MVT::f80, Expand);
421 setConvertAction(MVT::f80, MVT::f32, Expand);
422 setConvertAction(MVT::f64, MVT::f32, Expand);
423 // And x87->x87 truncations also.
424 setConvertAction(MVT::f80, MVT::f64, Expand);
428 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
429 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
432 // f32 and f64 in x87.
433 // Set up the FP register classes.
434 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
435 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
437 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
438 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
440 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
442 // Floating truncations go through memory. If optimizing, we lie about
443 // this though and handle it in InstructionSelectPreprocess so that
444 // dagcombine2 can hack on these.
446 setConvertAction(MVT::f80, MVT::f32, Expand);
447 setConvertAction(MVT::f64, MVT::f32, Expand);
448 setConvertAction(MVT::f80, MVT::f64, Expand);
452 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
453 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
455 addLegalFPImmediate(APFloat(+0.0)); // FLD0
456 addLegalFPImmediate(APFloat(+1.0)); // FLD1
457 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
458 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
459 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
460 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
461 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
462 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
465 // Long double always uses X87.
466 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
467 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
468 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
470 APFloat TmpFlt(+0.0);
471 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
472 addLegalFPImmediate(TmpFlt); // FLD0
474 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
475 APFloat TmpFlt2(+1.0);
476 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
477 addLegalFPImmediate(TmpFlt2); // FLD1
478 TmpFlt2.changeSign();
479 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
483 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
484 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
487 // Always use a library call for pow.
488 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
489 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
490 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
492 // First set operation action for all vector types to expand. Then we
493 // will selectively turn on ones that can be effectively codegen'd.
494 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
495 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
496 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
525 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
526 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
527 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
528 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
529 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
530 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
531 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
532 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
533 setOperationAction(ISD::VSETCC, (MVT::ValueType)VT, Expand);
536 if (Subtarget->hasMMX()) {
537 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
538 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
539 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
540 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
542 // FIXME: add MMX packed arithmetics
544 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
545 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
546 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
547 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
549 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
550 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
551 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
552 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
554 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
555 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
557 setOperationAction(ISD::AND, MVT::v8i8, Promote);
558 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
559 setOperationAction(ISD::AND, MVT::v4i16, Promote);
560 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
561 setOperationAction(ISD::AND, MVT::v2i32, Promote);
562 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
563 setOperationAction(ISD::AND, MVT::v1i64, Legal);
565 setOperationAction(ISD::OR, MVT::v8i8, Promote);
566 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
567 setOperationAction(ISD::OR, MVT::v4i16, Promote);
568 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
569 setOperationAction(ISD::OR, MVT::v2i32, Promote);
570 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
571 setOperationAction(ISD::OR, MVT::v1i64, Legal);
573 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
574 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
575 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
576 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
577 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
578 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
579 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
581 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
582 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
583 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
584 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
585 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
586 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
587 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
589 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
590 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
591 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
592 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
594 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
595 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
596 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
597 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
599 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
600 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
601 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
604 if (Subtarget->hasSSE1()) {
605 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
607 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
608 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
609 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
610 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
611 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
612 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
613 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
614 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
615 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
616 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
617 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
618 setOperationAction(ISD::VSETCC, MVT::v4f32, Legal);
621 if (Subtarget->hasSSE2()) {
622 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
623 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
624 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
625 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
626 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
628 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
629 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
630 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
631 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
632 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
633 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
634 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
635 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
636 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
637 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
638 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
639 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
640 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
641 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
642 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
644 setOperationAction(ISD::VSETCC, MVT::v2f64, Legal);
645 setOperationAction(ISD::VSETCC, MVT::v16i8, Legal);
646 setOperationAction(ISD::VSETCC, MVT::v8i16, Legal);
647 setOperationAction(ISD::VSETCC, MVT::v4i32, Legal);
648 setOperationAction(ISD::VSETCC, MVT::v2i64, Legal);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
652 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
653 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
654 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
656 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
657 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
658 // Do not attempt to custom lower non-power-of-2 vectors
659 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
661 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
662 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
665 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
666 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
669 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
670 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
671 if (Subtarget->is64Bit()) {
672 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
673 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
676 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
677 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
678 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
679 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
680 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
681 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
682 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
683 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
684 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
685 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
686 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
687 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
690 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
692 // Custom lower v2i64 and v2f64 selects.
693 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
694 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
695 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
696 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
700 if (Subtarget->hasSSE41()) {
701 // FIXME: Do we need to handle scalar-to-vector here?
702 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
703 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
705 // i8 and i16 vectors are custom , because the source register and source
706 // source memory operand types are not the same width. f32 vectors are
707 // custom since the immediate controlling the insert encodes additional
709 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
710 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
712 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
717 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
719 if (Subtarget->is64Bit()) {
720 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
721 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
725 // We want to custom lower some of our intrinsics.
726 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
728 // We have target-specific dag combine patterns for the following nodes:
729 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
730 setTargetDAGCombine(ISD::BUILD_VECTOR);
731 setTargetDAGCombine(ISD::SELECT);
732 setTargetDAGCombine(ISD::STORE);
734 computeRegisterProperties();
736 // FIXME: These should be based on subtarget info. Plus, the values should
737 // be smaller when we are in optimizing for size mode.
738 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
739 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
740 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
741 allowUnalignedMemoryAccesses = true; // x86 supports it!
742 setPrefLoopAlignment(16);
747 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
752 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
753 /// the desired ByVal argument alignment.
754 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
757 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
758 if (VTy->getBitWidth() == 128)
760 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
761 unsigned EltAlign = 0;
762 getMaxByValAlign(ATy->getElementType(), EltAlign);
763 if (EltAlign > MaxAlign)
765 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
766 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
767 unsigned EltAlign = 0;
768 getMaxByValAlign(STy->getElementType(i), EltAlign);
769 if (EltAlign > MaxAlign)
778 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
779 /// function arguments in the caller parameter area. For X86, aggregates
780 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
781 /// are at 4-byte boundaries.
782 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
783 if (Subtarget->is64Bit())
784 return getTargetData()->getABITypeAlignment(Ty);
786 if (Subtarget->hasSSE1())
787 getMaxByValAlign(Ty, Align);
791 /// getOptimalMemOpType - Returns the target specific optimal type for load
792 /// and store operations as a result of memset, memcpy, and memmove
793 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
796 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
797 bool isSrcConst, bool isSrcStr) const {
798 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
800 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
802 if (Subtarget->is64Bit() && Size >= 8)
808 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
810 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
811 SelectionDAG &DAG) const {
812 if (usesGlobalOffsetTable())
813 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
814 if (!Subtarget->isPICStyleRIPRel())
815 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
819 //===----------------------------------------------------------------------===//
820 // Return Value Calling Convention Implementation
821 //===----------------------------------------------------------------------===//
823 #include "X86GenCallingConv.inc"
825 /// LowerRET - Lower an ISD::RET node.
826 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
827 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
829 SmallVector<CCValAssign, 16> RVLocs;
830 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
831 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
832 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
833 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
835 // If this is the first return lowered for this function, add the regs to the
836 // liveout set for the function.
837 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
838 for (unsigned i = 0; i != RVLocs.size(); ++i)
839 if (RVLocs[i].isRegLoc())
840 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
842 SDOperand Chain = Op.getOperand(0);
844 // Handle tail call return.
845 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
846 if (Chain.getOpcode() == X86ISD::TAILCALL) {
847 SDOperand TailCall = Chain;
848 SDOperand TargetAddress = TailCall.getOperand(1);
849 SDOperand StackAdjustment = TailCall.getOperand(2);
850 assert(((TargetAddress.getOpcode() == ISD::Register &&
851 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
852 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
853 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
854 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
855 "Expecting an global address, external symbol, or register");
856 assert(StackAdjustment.getOpcode() == ISD::Constant &&
857 "Expecting a const value");
859 SmallVector<SDOperand,8> Operands;
860 Operands.push_back(Chain.getOperand(0));
861 Operands.push_back(TargetAddress);
862 Operands.push_back(StackAdjustment);
863 // Copy registers used by the call. Last operand is a flag so it is not
865 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
866 Operands.push_back(Chain.getOperand(i));
868 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
875 SmallVector<SDOperand, 6> RetOps;
876 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
877 // Operand #1 = Bytes To Pop
878 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
880 // Copy the result values into the output registers.
881 for (unsigned i = 0; i != RVLocs.size(); ++i) {
882 CCValAssign &VA = RVLocs[i];
883 assert(VA.isRegLoc() && "Can only return in registers!");
884 SDOperand ValToCopy = Op.getOperand(i*2+1);
886 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
887 // the RET instruction and handled by the FP Stackifier.
888 if (RVLocs[i].getLocReg() == X86::ST0 ||
889 RVLocs[i].getLocReg() == X86::ST1) {
890 // If this is a copy from an xmm register to ST(0), use an FPExtend to
891 // change the value to the FP stack register class.
892 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
893 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
894 RetOps.push_back(ValToCopy);
895 // Don't emit a copytoreg.
899 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
900 Flag = Chain.getValue(1);
903 // The x86-64 ABI for returning structs by value requires that we copy
904 // the sret argument into %rax for the return. We saved the argument into
905 // a virtual register in the entry block, so now we copy the value out
907 if (Subtarget->is64Bit() &&
908 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
909 MachineFunction &MF = DAG.getMachineFunction();
910 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
911 unsigned Reg = FuncInfo->getSRetReturnReg();
913 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
914 FuncInfo->setSRetReturnReg(Reg);
916 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
918 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
919 Flag = Chain.getValue(1);
922 RetOps[0] = Chain; // Update chain.
924 // Add the flag if we have it.
926 RetOps.push_back(Flag);
928 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
932 /// LowerCallResult - Lower the result values of an ISD::CALL into the
933 /// appropriate copies out of appropriate physical registers. This assumes that
934 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
935 /// being lowered. The returns a SDNode with the same number of values as the
937 SDNode *X86TargetLowering::
938 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
939 unsigned CallingConv, SelectionDAG &DAG) {
941 // Assign locations to each value returned by this call.
942 SmallVector<CCValAssign, 16> RVLocs;
943 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
944 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
945 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
947 SmallVector<SDOperand, 8> ResultVals;
949 // Copy all of the result registers out of their specified physreg.
950 for (unsigned i = 0; i != RVLocs.size(); ++i) {
951 MVT::ValueType CopyVT = RVLocs[i].getValVT();
953 // If this is a call to a function that returns an fp value on the floating
954 // point stack, but where we prefer to use the value in xmm registers, copy
955 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
956 if (RVLocs[i].getLocReg() == X86::ST0 &&
957 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
961 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
962 CopyVT, InFlag).getValue(1);
963 SDOperand Val = Chain.getValue(0);
964 InFlag = Chain.getValue(2);
966 if (CopyVT != RVLocs[i].getValVT()) {
967 // Round the F80 the right size, which also moves to the appropriate xmm
969 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
970 // This truncation won't change the value.
971 DAG.getIntPtrConstant(1));
974 ResultVals.push_back(Val);
977 // Merge everything together with a MERGE_VALUES node.
978 ResultVals.push_back(Chain);
979 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
980 &ResultVals[0], ResultVals.size()).Val;
984 //===----------------------------------------------------------------------===//
985 // C & StdCall & Fast Calling Convention implementation
986 //===----------------------------------------------------------------------===//
987 // StdCall calling convention seems to be standard for many Windows' API
988 // routines and around. It differs from C calling convention just a little:
989 // callee should clean up the stack, not caller. Symbols should be also
990 // decorated in some fancy way :) It doesn't support any vector arguments.
991 // For info on fast calling convention see Fast Calling Convention (tail call)
992 // implementation LowerX86_32FastCCCallTo.
994 /// AddLiveIn - This helper function adds the specified physical register to the
995 /// MachineFunction as a live in value. It also creates a corresponding virtual
997 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
998 const TargetRegisterClass *RC) {
999 assert(RC->contains(PReg) && "Not the correct regclass!");
1000 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1001 MF.getRegInfo().addLiveIn(PReg, VReg);
1005 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1007 static bool CallIsStructReturn(SDOperand Op) {
1008 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1012 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
1015 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1016 /// return semantics.
1017 static bool ArgsAreStructReturn(SDOperand Op) {
1018 unsigned NumArgs = Op.Val->getNumValues() - 1;
1022 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1025 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1026 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1028 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1029 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1033 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1036 case CallingConv::X86_StdCall:
1037 return !Subtarget->is64Bit();
1038 case CallingConv::X86_FastCall:
1039 return !Subtarget->is64Bit();
1040 case CallingConv::Fast:
1041 return PerformTailCallOpt;
1045 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1046 /// FORMAL_ARGUMENTS node.
1047 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1048 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1050 if (Subtarget->is64Bit()) {
1051 if (Subtarget->isTargetWin64())
1052 return CC_X86_Win64_C;
1054 if (CC == CallingConv::Fast && PerformTailCallOpt)
1055 return CC_X86_64_TailCall;
1061 if (CC == CallingConv::X86_FastCall)
1062 return CC_X86_32_FastCall;
1063 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1064 return CC_X86_32_TailCall;
1069 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1070 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1072 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1073 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1074 if (CC == CallingConv::X86_FastCall)
1076 else if (CC == CallingConv::X86_StdCall)
1082 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1083 /// in a register before calling.
1084 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1085 return !IsTailCall && !Is64Bit &&
1086 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1087 Subtarget->isPICStyleGOT();
1090 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1091 /// address to be loaded in a register.
1093 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1094 return !Is64Bit && IsTailCall &&
1095 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1096 Subtarget->isPICStyleGOT();
1099 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1100 /// by "Src" to address "Dst" with size and alignment information specified by
1101 /// the specific parameter attribute. The copy will be passed as a byval
1102 /// function parameter.
1104 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1105 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1106 SDOperand SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1107 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1108 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1111 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1112 const CCValAssign &VA,
1113 MachineFrameInfo *MFI,
1115 SDOperand Root, unsigned i) {
1116 // Create the nodes corresponding to a load from this parameter slot.
1117 ISD::ArgFlagsTy Flags =
1118 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1119 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1120 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1122 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1123 // changed with more analysis.
1124 // In case of tail call optimization mark all arguments mutable. Since they
1125 // could be overwritten by lowering of arguments in case of a tail call.
1126 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1127 VA.getLocMemOffset(), isImmutable);
1128 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1129 if (Flags.isByVal())
1131 return DAG.getLoad(VA.getValVT(), Root, FIN,
1132 PseudoSourceValue::getFixedStack(), FI);
1136 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1137 MachineFunction &MF = DAG.getMachineFunction();
1138 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1140 const Function* Fn = MF.getFunction();
1141 if (Fn->hasExternalLinkage() &&
1142 Subtarget->isTargetCygMing() &&
1143 Fn->getName() == "main")
1144 FuncInfo->setForceFramePointer(true);
1146 // Decorate the function name.
1147 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1149 MachineFrameInfo *MFI = MF.getFrameInfo();
1150 SDOperand Root = Op.getOperand(0);
1151 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1152 unsigned CC = MF.getFunction()->getCallingConv();
1153 bool Is64Bit = Subtarget->is64Bit();
1154 bool IsWin64 = Subtarget->isTargetWin64();
1156 assert(!(isVarArg && CC == CallingConv::Fast) &&
1157 "Var args not supported with calling convention fastcc");
1159 // Assign locations to all of the incoming arguments.
1160 SmallVector<CCValAssign, 16> ArgLocs;
1161 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1162 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1164 SmallVector<SDOperand, 8> ArgValues;
1165 unsigned LastVal = ~0U;
1166 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1167 CCValAssign &VA = ArgLocs[i];
1168 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1170 assert(VA.getValNo() != LastVal &&
1171 "Don't support value assigned to multiple locs yet");
1172 LastVal = VA.getValNo();
1174 if (VA.isRegLoc()) {
1175 MVT::ValueType RegVT = VA.getLocVT();
1176 TargetRegisterClass *RC;
1177 if (RegVT == MVT::i32)
1178 RC = X86::GR32RegisterClass;
1179 else if (Is64Bit && RegVT == MVT::i64)
1180 RC = X86::GR64RegisterClass;
1181 else if (RegVT == MVT::f32)
1182 RC = X86::FR32RegisterClass;
1183 else if (RegVT == MVT::f64)
1184 RC = X86::FR64RegisterClass;
1185 else if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 128)
1186 RC = X86::VR128RegisterClass;
1187 else if (MVT::isVector(RegVT)) {
1188 assert(MVT::getSizeInBits(RegVT) == 64);
1190 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1192 // Darwin calling convention passes MMX values in either GPRs or
1193 // XMMs in x86-64. Other targets pass them in memory.
1194 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1195 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1198 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1203 assert(0 && "Unknown argument type!");
1206 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1207 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1209 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1210 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1212 if (VA.getLocInfo() == CCValAssign::SExt)
1213 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1214 DAG.getValueType(VA.getValVT()));
1215 else if (VA.getLocInfo() == CCValAssign::ZExt)
1216 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1217 DAG.getValueType(VA.getValVT()));
1219 if (VA.getLocInfo() != CCValAssign::Full)
1220 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1222 // Handle MMX values passed in GPRs.
1223 if (Is64Bit && RegVT != VA.getLocVT()) {
1224 if (MVT::getSizeInBits(RegVT) == 64 && RC == X86::GR64RegisterClass)
1225 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1226 else if (RC == X86::VR128RegisterClass) {
1227 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1228 DAG.getConstant(0, MVT::i64));
1229 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1233 ArgValues.push_back(ArgValue);
1235 assert(VA.isMemLoc());
1236 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1240 // The x86-64 ABI for returning structs by value requires that we copy
1241 // the sret argument into %rax for the return. Save the argument into
1242 // a virtual register so that we can access it from the return points.
1243 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1244 MachineFunction &MF = DAG.getMachineFunction();
1245 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246 unsigned Reg = FuncInfo->getSRetReturnReg();
1248 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1249 FuncInfo->setSRetReturnReg(Reg);
1251 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1252 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1255 unsigned StackSize = CCInfo.getNextStackOffset();
1256 // align stack specially for tail calls
1257 if (CC == CallingConv::Fast)
1258 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1260 // If the function takes variable number of arguments, make a frame index for
1261 // the start of the first vararg value... for expansion of llvm.va_start.
1263 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1264 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1267 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1269 // FIXME: We should really autogenerate these arrays
1270 static const unsigned GPR64ArgRegsWin64[] = {
1271 X86::RCX, X86::RDX, X86::R8, X86::R9
1273 static const unsigned XMMArgRegsWin64[] = {
1274 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1276 static const unsigned GPR64ArgRegs64Bit[] = {
1277 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1279 static const unsigned XMMArgRegs64Bit[] = {
1280 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1281 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1283 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1286 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1287 GPR64ArgRegs = GPR64ArgRegsWin64;
1288 XMMArgRegs = XMMArgRegsWin64;
1290 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1291 GPR64ArgRegs = GPR64ArgRegs64Bit;
1292 XMMArgRegs = XMMArgRegs64Bit;
1294 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1296 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1299 // For X86-64, if there are vararg parameters that are passed via
1300 // registers, then we must store them to their spots on the stack so they
1301 // may be loaded by deferencing the result of va_next.
1302 VarArgsGPOffset = NumIntRegs * 8;
1303 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1304 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1305 TotalNumXMMRegs * 16, 16);
1307 // Store the integer parameter registers.
1308 SmallVector<SDOperand, 8> MemOps;
1309 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1310 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1311 DAG.getIntPtrConstant(VarArgsGPOffset));
1312 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1313 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1314 X86::GR64RegisterClass);
1315 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1317 DAG.getStore(Val.getValue(1), Val, FIN,
1318 PseudoSourceValue::getFixedStack(),
1320 MemOps.push_back(Store);
1321 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1322 DAG.getIntPtrConstant(8));
1325 // Now store the XMM (fp + vector) parameter registers.
1326 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1327 DAG.getIntPtrConstant(VarArgsFPOffset));
1328 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1329 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1330 X86::VR128RegisterClass);
1331 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1333 DAG.getStore(Val.getValue(1), Val, FIN,
1334 PseudoSourceValue::getFixedStack(),
1336 MemOps.push_back(Store);
1337 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1338 DAG.getIntPtrConstant(16));
1340 if (!MemOps.empty())
1341 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1342 &MemOps[0], MemOps.size());
1346 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1347 // arguments and the arguments after the retaddr has been pushed are
1349 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1350 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1351 (StackSize & 7) == 0)
1354 ArgValues.push_back(Root);
1356 // Some CCs need callee pop.
1357 if (IsCalleePop(Op)) {
1358 BytesToPopOnReturn = StackSize; // Callee pops everything.
1359 BytesCallerReserves = 0;
1361 BytesToPopOnReturn = 0; // Callee pops nothing.
1362 // If this is an sret function, the return should pop the hidden pointer.
1363 if (!Is64Bit && ArgsAreStructReturn(Op))
1364 BytesToPopOnReturn = 4;
1365 BytesCallerReserves = StackSize;
1369 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1370 if (CC == CallingConv::X86_FastCall)
1371 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1374 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1376 // Return the new list of results.
1377 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1378 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1382 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1383 const SDOperand &StackPtr,
1384 const CCValAssign &VA,
1387 unsigned LocMemOffset = VA.getLocMemOffset();
1388 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1389 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1390 ISD::ArgFlagsTy Flags =
1391 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1392 if (Flags.isByVal()) {
1393 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1395 return DAG.getStore(Chain, Arg, PtrOff,
1396 PseudoSourceValue::getStack(), LocMemOffset);
1399 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1400 /// optimization is performed and it is required.
1402 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1403 SDOperand &OutRetAddr,
1408 if (!IsTailCall || FPDiff==0) return Chain;
1410 // Adjust the Return address stack slot.
1411 MVT::ValueType VT = getPointerTy();
1412 OutRetAddr = getReturnAddressFrameIndex(DAG);
1413 // Load the "old" Return address.
1414 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1415 return SDOperand(OutRetAddr.Val, 1);
1418 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1419 /// optimization is performed and it is required (FPDiff!=0).
1421 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1422 SDOperand Chain, SDOperand RetAddrFrIdx,
1423 bool Is64Bit, int FPDiff) {
1424 // Store the return address to the appropriate stack slot.
1425 if (!FPDiff) return Chain;
1426 // Calculate the new stack slot for the return address.
1427 int SlotSize = Is64Bit ? 8 : 4;
1428 int NewReturnAddrFI =
1429 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1430 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1431 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1432 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1433 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1437 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1438 MachineFunction &MF = DAG.getMachineFunction();
1439 SDOperand Chain = Op.getOperand(0);
1440 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1441 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1442 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1443 && CC == CallingConv::Fast && PerformTailCallOpt;
1444 SDOperand Callee = Op.getOperand(4);
1445 bool Is64Bit = Subtarget->is64Bit();
1446 bool IsStructRet = CallIsStructReturn(Op);
1448 assert(!(isVarArg && CC == CallingConv::Fast) &&
1449 "Var args not supported with calling convention fastcc");
1451 // Analyze operands of the call, assigning locations to each operand.
1452 SmallVector<CCValAssign, 16> ArgLocs;
1453 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1454 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1456 // Get a count of how many bytes are to be pushed on the stack.
1457 unsigned NumBytes = CCInfo.getNextStackOffset();
1458 if (CC == CallingConv::Fast)
1459 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1461 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1462 // arguments and the arguments after the retaddr has been pushed are aligned.
1463 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1464 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1465 (NumBytes & 7) == 0)
1470 // Lower arguments at fp - stackoffset + fpdiff.
1471 unsigned NumBytesCallerPushed =
1472 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1473 FPDiff = NumBytesCallerPushed - NumBytes;
1475 // Set the delta of movement of the returnaddr stackslot.
1476 // But only set if delta is greater than previous delta.
1477 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1478 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1481 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1483 SDOperand RetAddrFrIdx;
1484 // Load return adress for tail calls.
1485 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1488 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1489 SmallVector<SDOperand, 8> MemOpChains;
1492 // Walk the register/memloc assignments, inserting copies/loads. In the case
1493 // of tail call optimization arguments are handle later.
1494 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1495 CCValAssign &VA = ArgLocs[i];
1496 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1497 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1498 getArgFlags().isByVal();
1500 // Promote the value if needed.
1501 switch (VA.getLocInfo()) {
1502 default: assert(0 && "Unknown loc info!");
1503 case CCValAssign::Full: break;
1504 case CCValAssign::SExt:
1505 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1507 case CCValAssign::ZExt:
1508 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1510 case CCValAssign::AExt:
1511 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1515 if (VA.isRegLoc()) {
1517 MVT::ValueType RegVT = VA.getLocVT();
1518 if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 64)
1519 switch (VA.getLocReg()) {
1522 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1524 // Special case: passing MMX values in GPR registers.
1525 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1528 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1529 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1530 // Special case: passing MMX values in XMM registers.
1531 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1532 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1533 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1534 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1535 getMOVLMask(2, DAG));
1540 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1542 if (!IsTailCall || (IsTailCall && isByVal)) {
1543 assert(VA.isMemLoc());
1544 if (StackPtr.Val == 0)
1545 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1547 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1553 if (!MemOpChains.empty())
1554 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1555 &MemOpChains[0], MemOpChains.size());
1557 // Build a sequence of copy-to-reg nodes chained together with token chain
1558 // and flag operands which copy the outgoing args into registers.
1560 // Tail call byval lowering might overwrite argument registers so in case of
1561 // tail call optimization the copies to registers are lowered later.
1563 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1564 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1566 InFlag = Chain.getValue(1);
1569 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1571 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1572 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1573 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1575 InFlag = Chain.getValue(1);
1577 // If we are tail calling and generating PIC/GOT style code load the address
1578 // of the callee into ecx. The value in ecx is used as target of the tail
1579 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1580 // calls on PIC/GOT architectures. Normally we would just put the address of
1581 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1582 // restored (since ebx is callee saved) before jumping to the target@PLT.
1583 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1584 // Note: The actual moving to ecx is done further down.
1585 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1586 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1587 !G->getGlobal()->hasProtectedVisibility())
1588 Callee = LowerGlobalAddress(Callee, DAG);
1589 else if (isa<ExternalSymbolSDNode>(Callee))
1590 Callee = LowerExternalSymbol(Callee,DAG);
1593 if (Is64Bit && isVarArg) {
1594 // From AMD64 ABI document:
1595 // For calls that may call functions that use varargs or stdargs
1596 // (prototype-less calls or calls to functions containing ellipsis (...) in
1597 // the declaration) %al is used as hidden argument to specify the number
1598 // of SSE registers used. The contents of %al do not need to match exactly
1599 // the number of registers, but must be an ubound on the number of SSE
1600 // registers used and is in the range 0 - 8 inclusive.
1602 // FIXME: Verify this on Win64
1603 // Count the number of XMM registers allocated.
1604 static const unsigned XMMArgRegs[] = {
1605 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1606 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1608 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1610 Chain = DAG.getCopyToReg(Chain, X86::AL,
1611 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1612 InFlag = Chain.getValue(1);
1616 // For tail calls lower the arguments to the 'real' stack slot.
1618 SmallVector<SDOperand, 8> MemOpChains2;
1621 // Do not flag preceeding copytoreg stuff together with the following stuff.
1622 InFlag = SDOperand();
1623 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1624 CCValAssign &VA = ArgLocs[i];
1625 if (!VA.isRegLoc()) {
1626 assert(VA.isMemLoc());
1627 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1628 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1629 ISD::ArgFlagsTy Flags =
1630 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1631 // Create frame index.
1632 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1633 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1634 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1635 FIN = DAG.getFrameIndex(FI, getPointerTy());
1637 if (Flags.isByVal()) {
1638 // Copy relative to framepointer.
1639 SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1640 if (StackPtr.Val == 0)
1641 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1642 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1644 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1647 // Store relative to framepointer.
1648 MemOpChains2.push_back(
1649 DAG.getStore(Chain, Arg, FIN,
1650 PseudoSourceValue::getFixedStack(), FI));
1655 if (!MemOpChains2.empty())
1656 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1657 &MemOpChains2[0], MemOpChains2.size());
1659 // Copy arguments to their registers.
1660 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1661 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1663 InFlag = Chain.getValue(1);
1665 InFlag =SDOperand();
1667 // Store the return address to the appropriate stack slot.
1668 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1672 // If the callee is a GlobalAddress node (quite common, every direct call is)
1673 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1674 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1675 // We should use extra load for direct calls to dllimported functions in
1677 if ((IsTailCall || !Is64Bit ||
1678 getTargetMachine().getCodeModel() != CodeModel::Large)
1679 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1680 getTargetMachine(), true))
1681 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1682 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1683 if (IsTailCall || !Is64Bit ||
1684 getTargetMachine().getCodeModel() != CodeModel::Large)
1685 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1686 } else if (IsTailCall) {
1687 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1689 Chain = DAG.getCopyToReg(Chain,
1690 DAG.getRegister(Opc, getPointerTy()),
1692 Callee = DAG.getRegister(Opc, getPointerTy());
1693 // Add register as live out.
1694 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1697 // Returns a chain & a flag for retval copy to use.
1698 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1699 SmallVector<SDOperand, 8> Ops;
1702 Ops.push_back(Chain);
1703 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1704 Ops.push_back(DAG.getIntPtrConstant(0));
1706 Ops.push_back(InFlag);
1707 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1708 InFlag = Chain.getValue(1);
1710 // Returns a chain & a flag for retval copy to use.
1711 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1715 Ops.push_back(Chain);
1716 Ops.push_back(Callee);
1719 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1721 // Add argument registers to the end of the list so that they are known live
1723 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1724 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1725 RegsToPass[i].second.getValueType()));
1727 // Add an implicit use GOT pointer in EBX.
1728 if (!IsTailCall && !Is64Bit &&
1729 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1730 Subtarget->isPICStyleGOT())
1731 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1733 // Add an implicit use of AL for x86 vararg functions.
1734 if (Is64Bit && isVarArg)
1735 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1738 Ops.push_back(InFlag);
1741 assert(InFlag.Val &&
1742 "Flag must be set. Depend on flag being set in LowerRET");
1743 Chain = DAG.getNode(X86ISD::TAILCALL,
1744 Op.Val->getVTList(), &Ops[0], Ops.size());
1746 return SDOperand(Chain.Val, Op.ResNo);
1749 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1750 InFlag = Chain.getValue(1);
1752 // Create the CALLSEQ_END node.
1753 unsigned NumBytesForCalleeToPush;
1754 if (IsCalleePop(Op))
1755 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1756 else if (!Is64Bit && IsStructRet)
1757 // If this is is a call to a struct-return function, the callee
1758 // pops the hidden struct pointer, so we have to push it back.
1759 // This is common for Darwin/X86, Linux & Mingw32 targets.
1760 NumBytesForCalleeToPush = 4;
1762 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1764 // Returns a flag for retval copy to use.
1765 Chain = DAG.getCALLSEQ_END(Chain,
1766 DAG.getIntPtrConstant(NumBytes),
1767 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1769 InFlag = Chain.getValue(1);
1771 // Handle result values, copying them out of physregs into vregs that we
1773 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1777 //===----------------------------------------------------------------------===//
1778 // Fast Calling Convention (tail call) implementation
1779 //===----------------------------------------------------------------------===//
1781 // Like std call, callee cleans arguments, convention except that ECX is
1782 // reserved for storing the tail called function address. Only 2 registers are
1783 // free for argument passing (inreg). Tail call optimization is performed
1785 // * tailcallopt is enabled
1786 // * caller/callee are fastcc
1787 // On X86_64 architecture with GOT-style position independent code only local
1788 // (within module) calls are supported at the moment.
1789 // To keep the stack aligned according to platform abi the function
1790 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1791 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1792 // If a tail called function callee has more arguments than the caller the
1793 // caller needs to make sure that there is room to move the RETADDR to. This is
1794 // achieved by reserving an area the size of the argument delta right after the
1795 // original REtADDR, but before the saved framepointer or the spilled registers
1796 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1808 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1809 /// for a 16 byte align requirement.
1810 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1811 SelectionDAG& DAG) {
1812 if (PerformTailCallOpt) {
1813 MachineFunction &MF = DAG.getMachineFunction();
1814 const TargetMachine &TM = MF.getTarget();
1815 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1816 unsigned StackAlignment = TFI.getStackAlignment();
1817 uint64_t AlignMask = StackAlignment - 1;
1818 int64_t Offset = StackSize;
1819 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1820 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1821 // Number smaller than 12 so just add the difference.
1822 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1824 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1825 Offset = ((~AlignMask) & Offset) + StackAlignment +
1826 (StackAlignment-SlotSize);
1833 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1834 /// following the call is a return. A function is eligible if caller/callee
1835 /// calling conventions match, currently only fastcc supports tail calls, and
1836 /// the function CALL is immediatly followed by a RET.
1837 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1839 SelectionDAG& DAG) const {
1840 if (!PerformTailCallOpt)
1843 if (CheckTailCallReturnConstraints(Call, Ret)) {
1844 MachineFunction &MF = DAG.getMachineFunction();
1845 unsigned CallerCC = MF.getFunction()->getCallingConv();
1846 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1847 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1848 SDOperand Callee = Call.getOperand(4);
1849 // On x86/32Bit PIC/GOT tail calls are supported.
1850 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1851 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1854 // Can only do local tail calls (in same module, hidden or protected) on
1855 // x86_64 PIC/GOT at the moment.
1856 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1857 return G->getGlobal()->hasHiddenVisibility()
1858 || G->getGlobal()->hasProtectedVisibility();
1865 //===----------------------------------------------------------------------===//
1866 // Other Lowering Hooks
1867 //===----------------------------------------------------------------------===//
1870 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1871 MachineFunction &MF = DAG.getMachineFunction();
1872 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1873 int ReturnAddrIndex = FuncInfo->getRAIndex();
1875 if (ReturnAddrIndex == 0) {
1876 // Set up a frame object for the return address.
1877 if (Subtarget->is64Bit())
1878 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1880 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1882 FuncInfo->setRAIndex(ReturnAddrIndex);
1885 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1890 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1891 /// specific condition code. It returns a false if it cannot do a direct
1892 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1894 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1895 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1896 SelectionDAG &DAG) {
1897 X86CC = X86::COND_INVALID;
1899 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1900 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1901 // X > -1 -> X == 0, jump !sign.
1902 RHS = DAG.getConstant(0, RHS.getValueType());
1903 X86CC = X86::COND_NS;
1905 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1906 // X < 0 -> X == 0, jump on sign.
1907 X86CC = X86::COND_S;
1909 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1911 RHS = DAG.getConstant(0, RHS.getValueType());
1912 X86CC = X86::COND_LE;
1917 switch (SetCCOpcode) {
1919 case ISD::SETEQ: X86CC = X86::COND_E; break;
1920 case ISD::SETGT: X86CC = X86::COND_G; break;
1921 case ISD::SETGE: X86CC = X86::COND_GE; break;
1922 case ISD::SETLT: X86CC = X86::COND_L; break;
1923 case ISD::SETLE: X86CC = X86::COND_LE; break;
1924 case ISD::SETNE: X86CC = X86::COND_NE; break;
1925 case ISD::SETULT: X86CC = X86::COND_B; break;
1926 case ISD::SETUGT: X86CC = X86::COND_A; break;
1927 case ISD::SETULE: X86CC = X86::COND_BE; break;
1928 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1931 // On a floating point condition, the flags are set as follows:
1933 // 0 | 0 | 0 | X > Y
1934 // 0 | 0 | 1 | X < Y
1935 // 1 | 0 | 0 | X == Y
1936 // 1 | 1 | 1 | unordered
1938 switch (SetCCOpcode) {
1941 case ISD::SETEQ: X86CC = X86::COND_E; break;
1942 case ISD::SETOLT: Flip = true; // Fallthrough
1944 case ISD::SETGT: X86CC = X86::COND_A; break;
1945 case ISD::SETOLE: Flip = true; // Fallthrough
1947 case ISD::SETGE: X86CC = X86::COND_AE; break;
1948 case ISD::SETUGT: Flip = true; // Fallthrough
1950 case ISD::SETLT: X86CC = X86::COND_B; break;
1951 case ISD::SETUGE: Flip = true; // Fallthrough
1953 case ISD::SETLE: X86CC = X86::COND_BE; break;
1955 case ISD::SETNE: X86CC = X86::COND_NE; break;
1956 case ISD::SETUO: X86CC = X86::COND_P; break;
1957 case ISD::SETO: X86CC = X86::COND_NP; break;
1960 std::swap(LHS, RHS);
1963 return X86CC != X86::COND_INVALID;
1966 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1967 /// code. Current x86 isa includes the following FP cmov instructions:
1968 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1969 static bool hasFPCMov(unsigned X86CC) {
1985 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1986 /// true if Op is undef or if its value falls within the specified range (L, H].
1987 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1988 if (Op.getOpcode() == ISD::UNDEF)
1991 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1992 return (Val >= Low && Val < Hi);
1995 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1996 /// true if Op is undef or if its value equal to the specified value.
1997 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1998 if (Op.getOpcode() == ISD::UNDEF)
2000 return cast<ConstantSDNode>(Op)->getValue() == Val;
2003 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2004 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2005 bool X86::isPSHUFDMask(SDNode *N) {
2006 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2008 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2011 // Check if the value doesn't reference the second vector.
2012 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2013 SDOperand Arg = N->getOperand(i);
2014 if (Arg.getOpcode() == ISD::UNDEF) continue;
2015 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2016 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2023 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2024 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2025 bool X86::isPSHUFHWMask(SDNode *N) {
2026 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2028 if (N->getNumOperands() != 8)
2031 // Lower quadword copied in order.
2032 for (unsigned i = 0; i != 4; ++i) {
2033 SDOperand Arg = N->getOperand(i);
2034 if (Arg.getOpcode() == ISD::UNDEF) continue;
2035 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2036 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2040 // Upper quadword shuffled.
2041 for (unsigned i = 4; i != 8; ++i) {
2042 SDOperand Arg = N->getOperand(i);
2043 if (Arg.getOpcode() == ISD::UNDEF) continue;
2044 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2045 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2046 if (Val < 4 || Val > 7)
2053 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2054 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2055 bool X86::isPSHUFLWMask(SDNode *N) {
2056 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2058 if (N->getNumOperands() != 8)
2061 // Upper quadword copied in order.
2062 for (unsigned i = 4; i != 8; ++i)
2063 if (!isUndefOrEqual(N->getOperand(i), i))
2066 // Lower quadword shuffled.
2067 for (unsigned i = 0; i != 4; ++i)
2068 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2074 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2075 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2076 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2077 if (NumElems != 2 && NumElems != 4) return false;
2079 unsigned Half = NumElems / 2;
2080 for (unsigned i = 0; i < Half; ++i)
2081 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2083 for (unsigned i = Half; i < NumElems; ++i)
2084 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2090 bool X86::isSHUFPMask(SDNode *N) {
2091 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2092 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2095 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2096 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2097 /// half elements to come from vector 1 (which would equal the dest.) and
2098 /// the upper half to come from vector 2.
2099 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2100 if (NumOps != 2 && NumOps != 4) return false;
2102 unsigned Half = NumOps / 2;
2103 for (unsigned i = 0; i < Half; ++i)
2104 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2106 for (unsigned i = Half; i < NumOps; ++i)
2107 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2112 static bool isCommutedSHUFP(SDNode *N) {
2113 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2114 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2117 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2118 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2119 bool X86::isMOVHLPSMask(SDNode *N) {
2120 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2122 if (N->getNumOperands() != 4)
2125 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2126 return isUndefOrEqual(N->getOperand(0), 6) &&
2127 isUndefOrEqual(N->getOperand(1), 7) &&
2128 isUndefOrEqual(N->getOperand(2), 2) &&
2129 isUndefOrEqual(N->getOperand(3), 3);
2132 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2133 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2135 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2136 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2138 if (N->getNumOperands() != 4)
2141 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2142 return isUndefOrEqual(N->getOperand(0), 2) &&
2143 isUndefOrEqual(N->getOperand(1), 3) &&
2144 isUndefOrEqual(N->getOperand(2), 2) &&
2145 isUndefOrEqual(N->getOperand(3), 3);
2148 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2149 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2150 bool X86::isMOVLPMask(SDNode *N) {
2151 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2153 unsigned NumElems = N->getNumOperands();
2154 if (NumElems != 2 && NumElems != 4)
2157 for (unsigned i = 0; i < NumElems/2; ++i)
2158 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2161 for (unsigned i = NumElems/2; i < NumElems; ++i)
2162 if (!isUndefOrEqual(N->getOperand(i), i))
2168 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2169 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2171 bool X86::isMOVHPMask(SDNode *N) {
2172 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2174 unsigned NumElems = N->getNumOperands();
2175 if (NumElems != 2 && NumElems != 4)
2178 for (unsigned i = 0; i < NumElems/2; ++i)
2179 if (!isUndefOrEqual(N->getOperand(i), i))
2182 for (unsigned i = 0; i < NumElems/2; ++i) {
2183 SDOperand Arg = N->getOperand(i + NumElems/2);
2184 if (!isUndefOrEqual(Arg, i + NumElems))
2191 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2192 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2193 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2194 bool V2IsSplat = false) {
2195 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2198 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2199 SDOperand BitI = Elts[i];
2200 SDOperand BitI1 = Elts[i+1];
2201 if (!isUndefOrEqual(BitI, j))
2204 if (isUndefOrEqual(BitI1, NumElts))
2207 if (!isUndefOrEqual(BitI1, j + NumElts))
2215 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2216 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2217 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2220 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2221 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2222 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2223 bool V2IsSplat = false) {
2224 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2227 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2228 SDOperand BitI = Elts[i];
2229 SDOperand BitI1 = Elts[i+1];
2230 if (!isUndefOrEqual(BitI, j + NumElts/2))
2233 if (isUndefOrEqual(BitI1, NumElts))
2236 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2244 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2245 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2246 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2249 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2250 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2252 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2253 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2255 unsigned NumElems = N->getNumOperands();
2256 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2259 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2260 SDOperand BitI = N->getOperand(i);
2261 SDOperand BitI1 = N->getOperand(i+1);
2263 if (!isUndefOrEqual(BitI, j))
2265 if (!isUndefOrEqual(BitI1, j))
2272 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2273 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2275 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2276 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2278 unsigned NumElems = N->getNumOperands();
2279 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2282 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2283 SDOperand BitI = N->getOperand(i);
2284 SDOperand BitI1 = N->getOperand(i + 1);
2286 if (!isUndefOrEqual(BitI, j))
2288 if (!isUndefOrEqual(BitI1, j))
2295 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2296 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2297 /// MOVSD, and MOVD, i.e. setting the lowest element.
2298 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2299 if (NumElts != 2 && NumElts != 4)
2302 if (!isUndefOrEqual(Elts[0], NumElts))
2305 for (unsigned i = 1; i < NumElts; ++i) {
2306 if (!isUndefOrEqual(Elts[i], i))
2313 bool X86::isMOVLMask(SDNode *N) {
2314 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2315 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2318 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2319 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2320 /// element of vector 2 and the other elements to come from vector 1 in order.
2321 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2322 bool V2IsSplat = false,
2323 bool V2IsUndef = false) {
2324 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2327 if (!isUndefOrEqual(Ops[0], 0))
2330 for (unsigned i = 1; i < NumOps; ++i) {
2331 SDOperand Arg = Ops[i];
2332 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2333 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2334 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2341 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2342 bool V2IsUndef = false) {
2343 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2344 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2345 V2IsSplat, V2IsUndef);
2348 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2349 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2350 bool X86::isMOVSHDUPMask(SDNode *N) {
2351 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2353 if (N->getNumOperands() != 4)
2356 // Expect 1, 1, 3, 3
2357 for (unsigned i = 0; i < 2; ++i) {
2358 SDOperand Arg = N->getOperand(i);
2359 if (Arg.getOpcode() == ISD::UNDEF) continue;
2360 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2361 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2362 if (Val != 1) return false;
2366 for (unsigned i = 2; i < 4; ++i) {
2367 SDOperand Arg = N->getOperand(i);
2368 if (Arg.getOpcode() == ISD::UNDEF) continue;
2369 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2370 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2371 if (Val != 3) return false;
2375 // Don't use movshdup if it can be done with a shufps.
2379 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2380 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2381 bool X86::isMOVSLDUPMask(SDNode *N) {
2382 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2384 if (N->getNumOperands() != 4)
2387 // Expect 0, 0, 2, 2
2388 for (unsigned i = 0; i < 2; ++i) {
2389 SDOperand Arg = N->getOperand(i);
2390 if (Arg.getOpcode() == ISD::UNDEF) continue;
2391 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2392 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2393 if (Val != 0) return false;
2397 for (unsigned i = 2; i < 4; ++i) {
2398 SDOperand Arg = N->getOperand(i);
2399 if (Arg.getOpcode() == ISD::UNDEF) continue;
2400 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2401 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2402 if (Val != 2) return false;
2406 // Don't use movshdup if it can be done with a shufps.
2410 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2411 /// specifies a identity operation on the LHS or RHS.
2412 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2413 unsigned NumElems = N->getNumOperands();
2414 for (unsigned i = 0; i < NumElems; ++i)
2415 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2420 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2421 /// a splat of a single element.
2422 static bool isSplatMask(SDNode *N) {
2423 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2425 // This is a splat operation if each element of the permute is the same, and
2426 // if the value doesn't reference the second vector.
2427 unsigned NumElems = N->getNumOperands();
2428 SDOperand ElementBase;
2430 for (; i != NumElems; ++i) {
2431 SDOperand Elt = N->getOperand(i);
2432 if (isa<ConstantSDNode>(Elt)) {
2438 if (!ElementBase.Val)
2441 for (; i != NumElems; ++i) {
2442 SDOperand Arg = N->getOperand(i);
2443 if (Arg.getOpcode() == ISD::UNDEF) continue;
2444 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2445 if (Arg != ElementBase) return false;
2448 // Make sure it is a splat of the first vector operand.
2449 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2452 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2453 /// a splat of a single element and it's a 2 or 4 element mask.
2454 bool X86::isSplatMask(SDNode *N) {
2455 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2457 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2458 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2460 return ::isSplatMask(N);
2463 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2464 /// specifies a splat of zero element.
2465 bool X86::isSplatLoMask(SDNode *N) {
2466 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2468 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2469 if (!isUndefOrEqual(N->getOperand(i), 0))
2474 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2475 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2477 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2478 unsigned NumOperands = N->getNumOperands();
2479 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2481 for (unsigned i = 0; i < NumOperands; ++i) {
2483 SDOperand Arg = N->getOperand(NumOperands-i-1);
2484 if (Arg.getOpcode() != ISD::UNDEF)
2485 Val = cast<ConstantSDNode>(Arg)->getValue();
2486 if (Val >= NumOperands) Val -= NumOperands;
2488 if (i != NumOperands - 1)
2495 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2496 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2498 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2500 // 8 nodes, but we only care about the last 4.
2501 for (unsigned i = 7; i >= 4; --i) {
2503 SDOperand Arg = N->getOperand(i);
2504 if (Arg.getOpcode() != ISD::UNDEF)
2505 Val = cast<ConstantSDNode>(Arg)->getValue();
2514 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2515 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2517 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2519 // 8 nodes, but we only care about the first 4.
2520 for (int i = 3; i >= 0; --i) {
2522 SDOperand Arg = N->getOperand(i);
2523 if (Arg.getOpcode() != ISD::UNDEF)
2524 Val = cast<ConstantSDNode>(Arg)->getValue();
2533 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2534 /// specifies a 8 element shuffle that can be broken into a pair of
2535 /// PSHUFHW and PSHUFLW.
2536 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2537 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2539 if (N->getNumOperands() != 8)
2542 // Lower quadword shuffled.
2543 for (unsigned i = 0; i != 4; ++i) {
2544 SDOperand Arg = N->getOperand(i);
2545 if (Arg.getOpcode() == ISD::UNDEF) continue;
2546 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2547 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2552 // Upper quadword shuffled.
2553 for (unsigned i = 4; i != 8; ++i) {
2554 SDOperand Arg = N->getOperand(i);
2555 if (Arg.getOpcode() == ISD::UNDEF) continue;
2556 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2557 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2558 if (Val < 4 || Val > 7)
2565 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2566 /// values in ther permute mask.
2567 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2568 SDOperand &V2, SDOperand &Mask,
2569 SelectionDAG &DAG) {
2570 MVT::ValueType VT = Op.getValueType();
2571 MVT::ValueType MaskVT = Mask.getValueType();
2572 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2573 unsigned NumElems = Mask.getNumOperands();
2574 SmallVector<SDOperand, 8> MaskVec;
2576 for (unsigned i = 0; i != NumElems; ++i) {
2577 SDOperand Arg = Mask.getOperand(i);
2578 if (Arg.getOpcode() == ISD::UNDEF) {
2579 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2582 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2583 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2585 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2587 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2591 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2592 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2595 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2596 /// the two vector operands have swapped position.
2598 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2599 MVT::ValueType MaskVT = Mask.getValueType();
2600 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2601 unsigned NumElems = Mask.getNumOperands();
2602 SmallVector<SDOperand, 8> MaskVec;
2603 for (unsigned i = 0; i != NumElems; ++i) {
2604 SDOperand Arg = Mask.getOperand(i);
2605 if (Arg.getOpcode() == ISD::UNDEF) {
2606 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2609 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2610 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2612 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2614 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2616 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2620 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2621 /// match movhlps. The lower half elements should come from upper half of
2622 /// V1 (and in order), and the upper half elements should come from the upper
2623 /// half of V2 (and in order).
2624 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2625 unsigned NumElems = Mask->getNumOperands();
2628 for (unsigned i = 0, e = 2; i != e; ++i)
2629 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2631 for (unsigned i = 2; i != 4; ++i)
2632 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2637 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2638 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2640 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2641 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2642 N = N->getOperand(0).Val;
2643 if (ISD::isNON_EXTLoad(N)) {
2645 *LD = cast<LoadSDNode>(N);
2652 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2653 /// match movlp{s|d}. The lower half elements should come from lower half of
2654 /// V1 (and in order), and the upper half elements should come from the upper
2655 /// half of V2 (and in order). And since V1 will become the source of the
2656 /// MOVLP, it must be either a vector load or a scalar load to vector.
2657 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2658 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2660 // Is V2 is a vector load, don't do this transformation. We will try to use
2661 // load folding shufps op.
2662 if (ISD::isNON_EXTLoad(V2))
2665 unsigned NumElems = Mask->getNumOperands();
2666 if (NumElems != 2 && NumElems != 4)
2668 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2669 if (!isUndefOrEqual(Mask->getOperand(i), i))
2671 for (unsigned i = NumElems/2; i != NumElems; ++i)
2672 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2677 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2679 static bool isSplatVector(SDNode *N) {
2680 if (N->getOpcode() != ISD::BUILD_VECTOR)
2683 SDOperand SplatValue = N->getOperand(0);
2684 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2685 if (N->getOperand(i) != SplatValue)
2690 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2692 static bool isUndefShuffle(SDNode *N) {
2693 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2696 SDOperand V1 = N->getOperand(0);
2697 SDOperand V2 = N->getOperand(1);
2698 SDOperand Mask = N->getOperand(2);
2699 unsigned NumElems = Mask.getNumOperands();
2700 for (unsigned i = 0; i != NumElems; ++i) {
2701 SDOperand Arg = Mask.getOperand(i);
2702 if (Arg.getOpcode() != ISD::UNDEF) {
2703 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2704 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2706 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2713 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2715 static inline bool isZeroNode(SDOperand Elt) {
2716 return ((isa<ConstantSDNode>(Elt) &&
2717 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2718 (isa<ConstantFPSDNode>(Elt) &&
2719 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2722 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2723 /// to an zero vector.
2724 static bool isZeroShuffle(SDNode *N) {
2725 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2728 SDOperand V1 = N->getOperand(0);
2729 SDOperand V2 = N->getOperand(1);
2730 SDOperand Mask = N->getOperand(2);
2731 unsigned NumElems = Mask.getNumOperands();
2732 for (unsigned i = 0; i != NumElems; ++i) {
2733 SDOperand Arg = Mask.getOperand(i);
2734 if (Arg.getOpcode() == ISD::UNDEF)
2737 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2738 if (Idx < NumElems) {
2739 unsigned Opc = V1.Val->getOpcode();
2740 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2742 if (Opc != ISD::BUILD_VECTOR ||
2743 !isZeroNode(V1.Val->getOperand(Idx)))
2745 } else if (Idx >= NumElems) {
2746 unsigned Opc = V2.Val->getOpcode();
2747 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2749 if (Opc != ISD::BUILD_VECTOR ||
2750 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2757 /// getZeroVector - Returns a vector of specified type with all zero elements.
2759 static SDOperand getZeroVector(MVT::ValueType VT, bool HasSSE2,
2760 SelectionDAG &DAG) {
2761 assert(MVT::isVector(VT) && "Expected a vector type");
2763 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2764 // type. This ensures they get CSE'd.
2766 if (MVT::getSizeInBits(VT) == 64) { // MMX
2767 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2768 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2769 } else if (HasSSE2) { // SSE2
2770 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2771 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2773 SDOperand Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2774 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2776 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2779 /// getOnesVector - Returns a vector of specified type with all bits set.
2781 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2782 assert(MVT::isVector(VT) && "Expected a vector type");
2784 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2785 // type. This ensures they get CSE'd.
2786 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2788 if (MVT::getSizeInBits(VT) == 64) // MMX
2789 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2791 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2792 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2796 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2797 /// that point to V2 points to its first element.
2798 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2799 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2801 bool Changed = false;
2802 SmallVector<SDOperand, 8> MaskVec;
2803 unsigned NumElems = Mask.getNumOperands();
2804 for (unsigned i = 0; i != NumElems; ++i) {
2805 SDOperand Arg = Mask.getOperand(i);
2806 if (Arg.getOpcode() != ISD::UNDEF) {
2807 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2808 if (Val > NumElems) {
2809 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2813 MaskVec.push_back(Arg);
2817 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2818 &MaskVec[0], MaskVec.size());
2822 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2823 /// operation of specified width.
2824 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2825 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2826 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2828 SmallVector<SDOperand, 8> MaskVec;
2829 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2830 for (unsigned i = 1; i != NumElems; ++i)
2831 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2832 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2835 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2836 /// of specified width.
2837 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2838 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2839 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2840 SmallVector<SDOperand, 8> MaskVec;
2841 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2842 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2843 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2845 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2848 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2849 /// of specified width.
2850 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2851 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2852 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2853 unsigned Half = NumElems/2;
2854 SmallVector<SDOperand, 8> MaskVec;
2855 for (unsigned i = 0; i != Half; ++i) {
2856 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2857 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2859 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2862 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2863 /// element #0 of a vector with the specified index, leaving the rest of the
2864 /// elements in place.
2865 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2866 SelectionDAG &DAG) {
2867 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2868 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2869 SmallVector<SDOperand, 8> MaskVec;
2870 // Element #0 of the result gets the elt we are replacing.
2871 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2872 for (unsigned i = 1; i != NumElems; ++i)
2873 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2874 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2877 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2878 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2879 MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2880 MVT::ValueType VT = Op.getValueType();
2883 SDOperand V1 = Op.getOperand(0);
2884 SDOperand Mask = Op.getOperand(2);
2885 unsigned NumElems = Mask.getNumOperands();
2886 // Special handling of v4f32 -> v4i32.
2887 if (VT != MVT::v4f32) {
2888 Mask = getUnpacklMask(NumElems, DAG);
2889 while (NumElems > 4) {
2890 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2893 Mask = getZeroVector(MVT::v4i32, true, DAG);
2896 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2897 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2898 DAG.getNode(ISD::UNDEF, PVT), Mask);
2899 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2902 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2903 /// vector of zero or undef vector. This produces a shuffle where the low
2904 /// element of V2 is swizzled into the zero/undef vector, landing at element
2905 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2906 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2907 bool isZero, bool HasSSE2,
2908 SelectionDAG &DAG) {
2909 MVT::ValueType VT = V2.getValueType();
2910 SDOperand V1 = isZero
2911 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2912 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2913 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2914 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2915 SmallVector<SDOperand, 16> MaskVec;
2916 for (unsigned i = 0; i != NumElems; ++i)
2917 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2918 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2920 MaskVec.push_back(DAG.getConstant(i, EVT));
2921 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2922 &MaskVec[0], MaskVec.size());
2923 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2926 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2928 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2929 unsigned NumNonZero, unsigned NumZero,
2930 SelectionDAG &DAG, TargetLowering &TLI) {
2936 for (unsigned i = 0; i < 16; ++i) {
2937 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2938 if (ThisIsNonZero && First) {
2940 V = getZeroVector(MVT::v8i16, true, DAG);
2942 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2947 SDOperand ThisElt(0, 0), LastElt(0, 0);
2948 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2949 if (LastIsNonZero) {
2950 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2952 if (ThisIsNonZero) {
2953 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2954 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2955 ThisElt, DAG.getConstant(8, MVT::i8));
2957 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2962 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2963 DAG.getIntPtrConstant(i/2));
2967 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2970 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2972 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2973 unsigned NumNonZero, unsigned NumZero,
2974 SelectionDAG &DAG, TargetLowering &TLI) {
2980 for (unsigned i = 0; i < 8; ++i) {
2981 bool isNonZero = (NonZeros & (1 << i)) != 0;
2985 V = getZeroVector(MVT::v8i16, true, DAG);
2987 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2990 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2991 DAG.getIntPtrConstant(i));
2999 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3000 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3001 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3002 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3003 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3004 // eliminated on x86-32 hosts.
3005 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3008 if (ISD::isBuildVectorAllOnes(Op.Val))
3009 return getOnesVector(Op.getValueType(), DAG);
3010 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3013 MVT::ValueType VT = Op.getValueType();
3014 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3015 unsigned EVTBits = MVT::getSizeInBits(EVT);
3017 unsigned NumElems = Op.getNumOperands();
3018 unsigned NumZero = 0;
3019 unsigned NumNonZero = 0;
3020 unsigned NonZeros = 0;
3021 bool IsAllConstants = true;
3022 SmallSet<SDOperand, 8> Values;
3023 for (unsigned i = 0; i < NumElems; ++i) {
3024 SDOperand Elt = Op.getOperand(i);
3025 if (Elt.getOpcode() == ISD::UNDEF)
3028 if (Elt.getOpcode() != ISD::Constant &&
3029 Elt.getOpcode() != ISD::ConstantFP)
3030 IsAllConstants = false;
3031 if (isZeroNode(Elt))
3034 NonZeros |= (1 << i);
3039 if (NumNonZero == 0) {
3040 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3041 return DAG.getNode(ISD::UNDEF, VT);
3044 // Special case for single non-zero, non-undef, element.
3045 if (NumNonZero == 1 && NumElems <= 4) {
3046 unsigned Idx = CountTrailingZeros_32(NonZeros);
3047 SDOperand Item = Op.getOperand(Idx);
3049 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3050 // the value are obviously zero, truncate the value to i32 and do the
3051 // insertion that way. Only do this if the value is non-constant or if the
3052 // value is a constant being inserted into element 0. It is cheaper to do
3053 // a constant pool load than it is to do a movd + shuffle.
3054 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3055 (!IsAllConstants || Idx == 0)) {
3056 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3057 // Handle MMX and SSE both.
3058 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3059 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3061 // Truncate the value (which may itself be a constant) to i32, and
3062 // convert it to a vector with movd (S2V+shuffle to zero extend).
3063 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3064 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3065 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3066 Subtarget->hasSSE2(), DAG);
3068 // Now we have our 32-bit value zero extended in the low element of
3069 // a vector. If Idx != 0, swizzle it into place.
3072 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3073 getSwapEltZeroMask(VecElts, Idx, DAG)
3075 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3077 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3081 // If we have a constant or non-constant insertion into the low element of
3082 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3083 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3084 // depending on what the source datatype is. Because we can only get here
3085 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3087 // Don't do this for i64 values on x86-32.
3088 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3089 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3090 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3091 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3092 Subtarget->hasSSE2(), DAG);
3095 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3098 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3099 // is a non-constant being inserted into an element other than the low one,
3100 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3101 // movd/movss) to move this into the low element, then shuffle it into
3103 if (EVTBits == 32) {
3104 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3106 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3107 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3108 Subtarget->hasSSE2(), DAG);
3109 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3110 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3111 SmallVector<SDOperand, 8> MaskVec;
3112 for (unsigned i = 0; i < NumElems; i++)
3113 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3114 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3115 &MaskVec[0], MaskVec.size());
3116 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3117 DAG.getNode(ISD::UNDEF, VT), Mask);
3121 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3122 if (Values.size() == 1)
3125 // A vector full of immediates; various special cases are already
3126 // handled, so this is best done with a single constant-pool load.
3130 // Let legalizer expand 2-wide build_vectors.
3131 if (EVTBits == 64) {
3132 if (NumNonZero == 1) {
3133 // One half is zero or undef.
3134 unsigned Idx = CountTrailingZeros_32(NonZeros);
3135 SDOperand V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3136 Op.getOperand(Idx));
3137 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3138 Subtarget->hasSSE2(), DAG);
3143 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3144 if (EVTBits == 8 && NumElems == 16) {
3145 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3147 if (V.Val) return V;
3150 if (EVTBits == 16 && NumElems == 8) {
3151 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3153 if (V.Val) return V;
3156 // If element VT is == 32 bits, turn it into a number of shuffles.
3157 SmallVector<SDOperand, 8> V;
3159 if (NumElems == 4 && NumZero > 0) {
3160 for (unsigned i = 0; i < 4; ++i) {
3161 bool isZero = !(NonZeros & (1 << i));
3163 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3165 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3168 for (unsigned i = 0; i < 2; ++i) {
3169 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3172 V[i] = V[i*2]; // Must be a zero vector.
3175 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3176 getMOVLMask(NumElems, DAG));
3179 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3180 getMOVLMask(NumElems, DAG));
3183 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3184 getUnpacklMask(NumElems, DAG));
3189 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3190 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3191 SmallVector<SDOperand, 8> MaskVec;
3192 bool Reverse = (NonZeros & 0x3) == 2;
3193 for (unsigned i = 0; i < 2; ++i)
3195 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3197 MaskVec.push_back(DAG.getConstant(i, EVT));
3198 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3199 for (unsigned i = 0; i < 2; ++i)
3201 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3203 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3204 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3205 &MaskVec[0], MaskVec.size());
3206 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3209 if (Values.size() > 2) {
3210 // Expand into a number of unpckl*.
3212 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3213 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3214 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3215 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3216 for (unsigned i = 0; i < NumElems; ++i)
3217 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3219 while (NumElems != 0) {
3220 for (unsigned i = 0; i < NumElems; ++i)
3221 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3232 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3233 SDOperand PermMask, SelectionDAG &DAG,
3234 TargetLowering &TLI) {
3236 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3237 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3238 MVT::ValueType PtrVT = TLI.getPointerTy();
3239 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3240 PermMask.Val->op_end());
3242 // First record which half of which vector the low elements come from.
3243 SmallVector<unsigned, 4> LowQuad(4);
3244 for (unsigned i = 0; i < 4; ++i) {
3245 SDOperand Elt = MaskElts[i];
3246 if (Elt.getOpcode() == ISD::UNDEF)
3248 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3249 int QuadIdx = EltIdx / 4;
3252 int BestLowQuad = -1;
3253 unsigned MaxQuad = 1;
3254 for (unsigned i = 0; i < 4; ++i) {
3255 if (LowQuad[i] > MaxQuad) {
3257 MaxQuad = LowQuad[i];
3261 // Record which half of which vector the high elements come from.
3262 SmallVector<unsigned, 4> HighQuad(4);
3263 for (unsigned i = 4; i < 8; ++i) {
3264 SDOperand Elt = MaskElts[i];
3265 if (Elt.getOpcode() == ISD::UNDEF)
3267 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3268 int QuadIdx = EltIdx / 4;
3269 ++HighQuad[QuadIdx];
3271 int BestHighQuad = -1;
3273 for (unsigned i = 0; i < 4; ++i) {
3274 if (HighQuad[i] > MaxQuad) {
3276 MaxQuad = HighQuad[i];
3280 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3281 if (BestLowQuad != -1 || BestHighQuad != -1) {
3282 // First sort the 4 chunks in order using shufpd.
3283 SmallVector<SDOperand, 8> MaskVec;
3284 if (BestLowQuad != -1)
3285 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3287 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3288 if (BestHighQuad != -1)
3289 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3291 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3292 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3293 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3294 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3295 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3296 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3298 // Now sort high and low parts separately.
3299 BitVector InOrder(8);
3300 if (BestLowQuad != -1) {
3301 // Sort lower half in order using PSHUFLW.
3303 bool AnyOutOrder = false;
3304 for (unsigned i = 0; i != 4; ++i) {
3305 SDOperand Elt = MaskElts[i];
3306 if (Elt.getOpcode() == ISD::UNDEF) {
3307 MaskVec.push_back(Elt);
3310 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3313 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3314 // If this element is in the right place after this shuffle, then
3316 if ((int)(EltIdx / 4) == BestLowQuad)
3321 for (unsigned i = 4; i != 8; ++i)
3322 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3323 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3324 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3328 if (BestHighQuad != -1) {
3329 // Sort high half in order using PSHUFHW if possible.
3331 for (unsigned i = 0; i != 4; ++i)
3332 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3333 bool AnyOutOrder = false;
3334 for (unsigned i = 4; i != 8; ++i) {
3335 SDOperand Elt = MaskElts[i];
3336 if (Elt.getOpcode() == ISD::UNDEF) {
3337 MaskVec.push_back(Elt);
3340 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3343 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3344 // If this element is in the right place after this shuffle, then
3346 if ((int)(EltIdx / 4) == BestHighQuad)
3351 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3352 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3356 // The other elements are put in the right place using pextrw and pinsrw.
3357 for (unsigned i = 0; i != 8; ++i) {
3360 SDOperand Elt = MaskElts[i];
3361 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3364 SDOperand ExtOp = (EltIdx < 8)
3365 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3366 DAG.getConstant(EltIdx, PtrVT))
3367 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3368 DAG.getConstant(EltIdx - 8, PtrVT));
3369 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3370 DAG.getConstant(i, PtrVT));
3375 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3376 ///as few as possible.
3377 // First, let's find out how many elements are already in the right order.
3378 unsigned V1InOrder = 0;
3379 unsigned V1FromV1 = 0;
3380 unsigned V2InOrder = 0;
3381 unsigned V2FromV2 = 0;
3382 SmallVector<SDOperand, 8> V1Elts;
3383 SmallVector<SDOperand, 8> V2Elts;
3384 for (unsigned i = 0; i < 8; ++i) {
3385 SDOperand Elt = MaskElts[i];
3386 if (Elt.getOpcode() == ISD::UNDEF) {
3387 V1Elts.push_back(Elt);
3388 V2Elts.push_back(Elt);
3393 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3395 V1Elts.push_back(Elt);
3396 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3398 } else if (EltIdx == i+8) {
3399 V1Elts.push_back(Elt);
3400 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3402 } else if (EltIdx < 8) {
3403 V1Elts.push_back(Elt);
3406 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3411 if (V2InOrder > V1InOrder) {
3412 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3414 std::swap(V1Elts, V2Elts);
3415 std::swap(V1FromV1, V2FromV2);
3418 if ((V1FromV1 + V1InOrder) != 8) {
3419 // Some elements are from V2.
3421 // If there are elements that are from V1 but out of place,
3422 // then first sort them in place
3423 SmallVector<SDOperand, 8> MaskVec;
3424 for (unsigned i = 0; i < 8; ++i) {
3425 SDOperand Elt = V1Elts[i];
3426 if (Elt.getOpcode() == ISD::UNDEF) {
3427 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3430 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3432 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3434 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3436 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3437 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3441 for (unsigned i = 0; i < 8; ++i) {
3442 SDOperand Elt = V1Elts[i];
3443 if (Elt.getOpcode() == ISD::UNDEF)
3445 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3448 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3449 DAG.getConstant(EltIdx - 8, PtrVT));
3450 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3451 DAG.getConstant(i, PtrVT));
3455 // All elements are from V1.
3457 for (unsigned i = 0; i < 8; ++i) {
3458 SDOperand Elt = V1Elts[i];
3459 if (Elt.getOpcode() == ISD::UNDEF)
3461 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3462 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3463 DAG.getConstant(EltIdx, PtrVT));
3464 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3465 DAG.getConstant(i, PtrVT));
3471 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3472 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3473 /// done when every pair / quad of shuffle mask elements point to elements in
3474 /// the right sequence. e.g.
3475 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3477 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3479 SDOperand PermMask, SelectionDAG &DAG,
3480 TargetLowering &TLI) {
3481 unsigned NumElems = PermMask.getNumOperands();
3482 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3483 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3484 MVT::ValueType NewVT = MaskVT;
3486 case MVT::v4f32: NewVT = MVT::v2f64; break;
3487 case MVT::v4i32: NewVT = MVT::v2i64; break;
3488 case MVT::v8i16: NewVT = MVT::v4i32; break;
3489 case MVT::v16i8: NewVT = MVT::v4i32; break;
3490 default: assert(false && "Unexpected!");
3493 if (NewWidth == 2) {
3494 if (MVT::isInteger(VT))
3499 unsigned Scale = NumElems / NewWidth;
3500 SmallVector<SDOperand, 8> MaskVec;
3501 for (unsigned i = 0; i < NumElems; i += Scale) {
3502 unsigned StartIdx = ~0U;
3503 for (unsigned j = 0; j < Scale; ++j) {
3504 SDOperand Elt = PermMask.getOperand(i+j);
3505 if (Elt.getOpcode() == ISD::UNDEF)
3507 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3508 if (StartIdx == ~0U)
3509 StartIdx = EltIdx - (EltIdx % Scale);
3510 if (EltIdx != StartIdx + j)
3513 if (StartIdx == ~0U)
3514 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3516 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3519 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3520 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3521 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3522 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3523 &MaskVec[0], MaskVec.size()));
3526 /// getVZextMovL - Return a zero-extending vector move low node.
3528 static SDOperand getVZextMovL(MVT::ValueType VT, MVT::ValueType OpVT,
3529 SDOperand SrcOp, SelectionDAG &DAG,
3530 const X86Subtarget *Subtarget) {
3531 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3532 LoadSDNode *LD = NULL;
3533 if (!isScalarLoadToVector(SrcOp.Val, &LD))
3534 LD = dyn_cast<LoadSDNode>(SrcOp);
3536 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3538 MVT::ValueType EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3539 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3540 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3541 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3542 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3544 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3545 return DAG.getNode(ISD::BIT_CONVERT, VT,
3546 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3547 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3548 SrcOp.getOperand(0).getOperand(0))));
3553 return DAG.getNode(ISD::BIT_CONVERT, VT,
3554 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3555 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3559 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3560 SDOperand V1 = Op.getOperand(0);
3561 SDOperand V2 = Op.getOperand(1);
3562 SDOperand PermMask = Op.getOperand(2);
3563 MVT::ValueType VT = Op.getValueType();
3564 unsigned NumElems = PermMask.getNumOperands();
3565 bool isMMX = MVT::getSizeInBits(VT) == 64;
3566 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3567 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3568 bool V1IsSplat = false;
3569 bool V2IsSplat = false;
3571 if (isUndefShuffle(Op.Val))
3572 return DAG.getNode(ISD::UNDEF, VT);
3574 if (isZeroShuffle(Op.Val))
3575 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3577 if (isIdentityMask(PermMask.Val))
3579 else if (isIdentityMask(PermMask.Val, true))
3582 if (isSplatMask(PermMask.Val)) {
3583 if (isMMX || NumElems < 4) return Op;
3584 // Promote it to a v4{if}32 splat.
3585 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3588 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3590 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3591 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3593 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3594 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3595 // FIXME: Figure out a cleaner way to do this.
3596 // Try to make use of movq to zero out the top part.
3597 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3598 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3601 SDOperand NewV1 = NewOp.getOperand(0);
3602 SDOperand NewV2 = NewOp.getOperand(1);
3603 SDOperand NewMask = NewOp.getOperand(2);
3604 if (isCommutedMOVL(NewMask.Val, true, false)) {
3605 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3606 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3609 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3610 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3612 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3613 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3618 if (X86::isMOVLMask(PermMask.Val)) {
3621 if (ISD::isBuildVectorAllZeros(V1.Val))
3622 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3626 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3627 X86::isMOVSLDUPMask(PermMask.Val) ||
3628 X86::isMOVHLPSMask(PermMask.Val) ||
3629 X86::isMOVHPMask(PermMask.Val) ||
3630 X86::isMOVLPMask(PermMask.Val))
3633 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3634 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3635 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3637 bool Commuted = false;
3638 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3639 // 1,1,1,1 -> v8i16 though.
3640 V1IsSplat = isSplatVector(V1.Val);
3641 V2IsSplat = isSplatVector(V2.Val);
3643 // Canonicalize the splat or undef, if present, to be on the RHS.
3644 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3645 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3646 std::swap(V1IsSplat, V2IsSplat);
3647 std::swap(V1IsUndef, V2IsUndef);
3651 // FIXME: Figure out a cleaner way to do this.
3652 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3653 if (V2IsUndef) return V1;
3654 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3656 // V2 is a splat, so the mask may be malformed. That is, it may point
3657 // to any V2 element. The instruction selectior won't like this. Get
3658 // a corrected mask and commute to form a proper MOVS{S|D}.
3659 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3660 if (NewMask.Val != PermMask.Val)
3661 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3666 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3667 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3668 X86::isUNPCKLMask(PermMask.Val) ||
3669 X86::isUNPCKHMask(PermMask.Val))
3673 // Normalize mask so all entries that point to V2 points to its first
3674 // element then try to match unpck{h|l} again. If match, return a
3675 // new vector_shuffle with the corrected mask.
3676 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3677 if (NewMask.Val != PermMask.Val) {
3678 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3679 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3680 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3681 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3682 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3683 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3688 // Normalize the node to match x86 shuffle ops if needed
3689 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3690 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3693 // Commute is back and try unpck* again.
3694 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3695 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3696 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3697 X86::isUNPCKLMask(PermMask.Val) ||
3698 X86::isUNPCKHMask(PermMask.Val))
3702 // Try PSHUF* first, then SHUFP*.
3703 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3704 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3705 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3706 if (V2.getOpcode() != ISD::UNDEF)
3707 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3708 DAG.getNode(ISD::UNDEF, VT), PermMask);
3713 if (Subtarget->hasSSE2() &&
3714 (X86::isPSHUFDMask(PermMask.Val) ||
3715 X86::isPSHUFHWMask(PermMask.Val) ||
3716 X86::isPSHUFLWMask(PermMask.Val))) {
3717 MVT::ValueType RVT = VT;
3718 if (VT == MVT::v4f32) {
3720 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3721 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3722 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3723 } else if (V2.getOpcode() != ISD::UNDEF)
3724 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3725 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3727 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3731 // Binary or unary shufps.
3732 if (X86::isSHUFPMask(PermMask.Val) ||
3733 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3737 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3738 if (VT == MVT::v8i16) {
3739 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3744 // Handle all 4 wide cases with a number of shuffles.
3745 if (NumElems == 4 && !isMMX) {
3746 // Don't do this for MMX.
3747 MVT::ValueType MaskVT = PermMask.getValueType();
3748 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3749 SmallVector<std::pair<int, int>, 8> Locs;
3750 Locs.reserve(NumElems);
3751 SmallVector<SDOperand, 8> Mask1(NumElems,
3752 DAG.getNode(ISD::UNDEF, MaskEVT));
3753 SmallVector<SDOperand, 8> Mask2(NumElems,
3754 DAG.getNode(ISD::UNDEF, MaskEVT));
3757 // If no more than two elements come from either vector. This can be
3758 // implemented with two shuffles. First shuffle gather the elements.
3759 // The second shuffle, which takes the first shuffle as both of its
3760 // vector operands, put the elements into the right order.
3761 for (unsigned i = 0; i != NumElems; ++i) {
3762 SDOperand Elt = PermMask.getOperand(i);
3763 if (Elt.getOpcode() == ISD::UNDEF) {
3764 Locs[i] = std::make_pair(-1, -1);
3766 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3767 if (Val < NumElems) {
3768 Locs[i] = std::make_pair(0, NumLo);
3772 Locs[i] = std::make_pair(1, NumHi);
3773 if (2+NumHi < NumElems)
3774 Mask1[2+NumHi] = Elt;
3779 if (NumLo <= 2 && NumHi <= 2) {
3780 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3781 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3782 &Mask1[0], Mask1.size()));
3783 for (unsigned i = 0; i != NumElems; ++i) {
3784 if (Locs[i].first == -1)
3787 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3788 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3789 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3793 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3794 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3795 &Mask2[0], Mask2.size()));
3798 // Break it into (shuffle shuffle_hi, shuffle_lo).
3800 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3801 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3802 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3803 unsigned MaskIdx = 0;
3805 unsigned HiIdx = NumElems/2;
3806 for (unsigned i = 0; i != NumElems; ++i) {
3807 if (i == NumElems/2) {
3813 SDOperand Elt = PermMask.getOperand(i);
3814 if (Elt.getOpcode() == ISD::UNDEF) {
3815 Locs[i] = std::make_pair(-1, -1);
3816 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3817 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3818 (*MaskPtr)[LoIdx] = Elt;
3821 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3822 (*MaskPtr)[HiIdx] = Elt;
3827 SDOperand LoShuffle =
3828 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3829 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3830 &LoMask[0], LoMask.size()));
3831 SDOperand HiShuffle =
3832 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3833 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3834 &HiMask[0], HiMask.size()));
3835 SmallVector<SDOperand, 8> MaskOps;
3836 for (unsigned i = 0; i != NumElems; ++i) {
3837 if (Locs[i].first == -1) {
3838 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3840 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3841 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3844 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3845 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3846 &MaskOps[0], MaskOps.size()));
3853 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3854 SelectionDAG &DAG) {
3855 MVT::ValueType VT = Op.getValueType();
3856 if (MVT::getSizeInBits(VT) == 8) {
3857 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3858 Op.getOperand(0), Op.getOperand(1));
3859 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3860 DAG.getValueType(VT));
3861 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3862 } else if (MVT::getSizeInBits(VT) == 16) {
3863 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3864 Op.getOperand(0), Op.getOperand(1));
3865 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3866 DAG.getValueType(VT));
3867 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3868 } else if (VT == MVT::f32) {
3869 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3870 // the result back to FR32 register. It's only worth matching if the
3871 // result has a single use which is a store or a bitcast to i32.
3872 if (!Op.hasOneUse())
3874 SDNode *User = Op.Val->use_begin()->getUser();
3875 if (User->getOpcode() != ISD::STORE &&
3876 (User->getOpcode() != ISD::BIT_CONVERT ||
3877 User->getValueType(0) != MVT::i32))
3879 SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3880 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3882 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3889 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3890 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3893 if (Subtarget->hasSSE41()) {
3894 SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3899 MVT::ValueType VT = Op.getValueType();
3900 // TODO: handle v16i8.
3901 if (MVT::getSizeInBits(VT) == 16) {
3902 SDOperand Vec = Op.getOperand(0);
3903 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3905 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3906 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3907 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3909 // Transform it so it match pextrw which produces a 32-bit result.
3910 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3911 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3912 Op.getOperand(0), Op.getOperand(1));
3913 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3914 DAG.getValueType(VT));
3915 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3916 } else if (MVT::getSizeInBits(VT) == 32) {
3917 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3920 // SHUFPS the element to the lowest double word, then movss.
3921 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3922 SmallVector<SDOperand, 8> IdxVec;
3924 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3926 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3928 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3930 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3931 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3932 &IdxVec[0], IdxVec.size());
3933 SDOperand Vec = Op.getOperand(0);
3934 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3935 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3937 DAG.getIntPtrConstant(0));
3938 } else if (MVT::getSizeInBits(VT) == 64) {
3939 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3940 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3941 // to match extract_elt for f64.
3942 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3946 // UNPCKHPD the element to the lowest double word, then movsd.
3947 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3948 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3949 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3950 SmallVector<SDOperand, 8> IdxVec;
3951 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3953 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3954 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3955 &IdxVec[0], IdxVec.size());
3956 SDOperand Vec = Op.getOperand(0);
3957 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3958 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3959 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3960 DAG.getIntPtrConstant(0));
3967 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3968 MVT::ValueType VT = Op.getValueType();
3969 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3971 SDOperand N0 = Op.getOperand(0);
3972 SDOperand N1 = Op.getOperand(1);
3973 SDOperand N2 = Op.getOperand(2);
3975 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3976 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3978 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3980 if (N1.getValueType() != MVT::i32)
3981 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3982 if (N2.getValueType() != MVT::i32)
3983 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3984 return DAG.getNode(Opc, VT, N0, N1, N2);
3985 } else if (EVT == MVT::f32) {
3986 // Bits [7:6] of the constant are the source select. This will always be
3987 // zero here. The DAG Combiner may combine an extract_elt index into these
3988 // bits. For example (insert (extract, 3), 2) could be matched by putting
3989 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3990 // Bits [5:4] of the constant are the destination select. This is the
3991 // value of the incoming immediate.
3992 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3993 // combine either bitwise AND or insert of float 0.0 to set these bits.
3994 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3995 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4001 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
4002 MVT::ValueType VT = Op.getValueType();
4003 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4005 if (Subtarget->hasSSE41())
4006 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4011 SDOperand N0 = Op.getOperand(0);
4012 SDOperand N1 = Op.getOperand(1);
4013 SDOperand N2 = Op.getOperand(2);
4015 if (MVT::getSizeInBits(EVT) == 16) {
4016 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4017 // as its second argument.
4018 if (N1.getValueType() != MVT::i32)
4019 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4020 if (N2.getValueType() != MVT::i32)
4021 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4022 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4028 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
4029 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4030 MVT::ValueType VT = MVT::v2i32;
4031 switch (Op.getValueType()) {
4038 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4039 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4042 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4043 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4044 // one of the above mentioned nodes. It has to be wrapped because otherwise
4045 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4046 // be used to form addressing mode. These wrapped nodes will be selected
4049 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4050 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4051 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4053 CP->getAlignment());
4054 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4055 // With PIC, the address is actually $g + Offset.
4056 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4057 !Subtarget->isPICStyleRIPRel()) {
4058 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4059 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4067 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4068 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4069 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4070 // If it's a debug information descriptor, don't mess with it.
4071 if (DAG.isVerifiedDebugInfoDesc(Op))
4073 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4074 // With PIC, the address is actually $g + Offset.
4075 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4076 !Subtarget->isPICStyleRIPRel()) {
4077 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4078 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4082 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4083 // load the value at address GV, not the value of GV itself. This means that
4084 // the GlobalAddress must be in the base or index register of the address, not
4085 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4086 // The same applies for external symbols during PIC codegen
4087 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4088 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4089 PseudoSourceValue::getGOT(), 0);
4094 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4096 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4097 const MVT::ValueType PtrVT) {
4099 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4100 DAG.getNode(X86ISD::GlobalBaseReg,
4102 InFlag = Chain.getValue(1);
4104 // emit leal symbol@TLSGD(,%ebx,1), %eax
4105 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4106 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4107 GA->getValueType(0),
4109 SDOperand Ops[] = { Chain, TGA, InFlag };
4110 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4111 InFlag = Result.getValue(2);
4112 Chain = Result.getValue(1);
4114 // call ___tls_get_addr. This function receives its argument in
4115 // the register EAX.
4116 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4117 InFlag = Chain.getValue(1);
4119 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4120 SDOperand Ops1[] = { Chain,
4121 DAG.getTargetExternalSymbol("___tls_get_addr",
4123 DAG.getRegister(X86::EAX, PtrVT),
4124 DAG.getRegister(X86::EBX, PtrVT),
4126 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4127 InFlag = Chain.getValue(1);
4129 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4132 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4134 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4135 const MVT::ValueType PtrVT) {
4136 SDOperand InFlag, Chain;
4138 // emit leaq symbol@TLSGD(%rip), %rdi
4139 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4140 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4141 GA->getValueType(0),
4143 SDOperand Ops[] = { DAG.getEntryNode(), TGA};
4144 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4145 Chain = Result.getValue(1);
4146 InFlag = Result.getValue(2);
4148 // call ___tls_get_addr. This function receives its argument in
4149 // the register RDI.
4150 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4151 InFlag = Chain.getValue(1);
4153 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4154 SDOperand Ops1[] = { Chain,
4155 DAG.getTargetExternalSymbol("___tls_get_addr",
4157 DAG.getRegister(X86::RDI, PtrVT),
4159 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4160 InFlag = Chain.getValue(1);
4162 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4165 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4166 // "local exec" model.
4168 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4169 const MVT::ValueType PtrVT) {
4170 // Get the Thread Pointer
4171 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4172 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4174 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4175 GA->getValueType(0),
4177 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4179 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4180 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4181 PseudoSourceValue::getGOT(), 0);
4183 // The address of the thread local variable is the add of the thread
4184 // pointer with the offset of the variable.
4185 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4189 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4190 // TODO: implement the "local dynamic" model
4191 // TODO: implement the "initial exec"model for pic executables
4192 assert(Subtarget->isTargetELF() &&
4193 "TLS not implemented for non-ELF targets");
4194 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4195 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4196 // otherwise use the "Local Exec"TLS Model
4197 if (Subtarget->is64Bit()) {
4198 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4200 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4201 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4203 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4208 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4209 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4210 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4211 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4212 // With PIC, the address is actually $g + Offset.
4213 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4214 !Subtarget->isPICStyleRIPRel()) {
4215 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4216 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4223 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4224 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4225 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4226 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4227 // With PIC, the address is actually $g + Offset.
4228 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4229 !Subtarget->isPICStyleRIPRel()) {
4230 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4231 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4238 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4239 /// take a 2 x i32 value to shift plus a shift amount.
4240 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4241 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4242 MVT::ValueType VT = Op.getValueType();
4243 unsigned VTBits = MVT::getSizeInBits(VT);
4244 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4245 SDOperand ShOpLo = Op.getOperand(0);
4246 SDOperand ShOpHi = Op.getOperand(1);
4247 SDOperand ShAmt = Op.getOperand(2);
4248 SDOperand Tmp1 = isSRA ?
4249 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4250 DAG.getConstant(0, VT);
4252 SDOperand Tmp2, Tmp3;
4253 if (Op.getOpcode() == ISD::SHL_PARTS) {
4254 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4255 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4257 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4258 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4261 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4262 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4263 DAG.getConstant(VTBits, MVT::i8));
4264 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4265 AndNode, DAG.getConstant(0, MVT::i8));
4268 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4269 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4270 SmallVector<SDOperand, 4> Ops;
4271 if (Op.getOpcode() == ISD::SHL_PARTS) {
4272 Ops.push_back(Tmp2);
4273 Ops.push_back(Tmp3);
4275 Ops.push_back(Cond);
4276 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4279 Ops.push_back(Tmp3);
4280 Ops.push_back(Tmp1);
4282 Ops.push_back(Cond);
4283 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4285 Ops.push_back(Tmp2);
4286 Ops.push_back(Tmp3);
4288 Ops.push_back(Cond);
4289 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4292 Ops.push_back(Tmp3);
4293 Ops.push_back(Tmp1);
4295 Ops.push_back(Cond);
4296 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4299 VTs = DAG.getNodeValueTypes(VT, VT);
4303 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4306 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4307 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4308 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4309 "Unknown SINT_TO_FP to lower!");
4311 // These are really Legal; caller falls through into that case.
4312 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4314 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4315 Subtarget->is64Bit())
4318 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4319 MachineFunction &MF = DAG.getMachineFunction();
4320 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4321 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4322 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4324 PseudoSourceValue::getFixedStack(),
4329 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4331 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4333 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4334 SmallVector<SDOperand, 8> Ops;
4335 Ops.push_back(Chain);
4336 Ops.push_back(StackSlot);
4337 Ops.push_back(DAG.getValueType(SrcVT));
4338 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4339 Tys, &Ops[0], Ops.size());
4342 Chain = Result.getValue(1);
4343 SDOperand InFlag = Result.getValue(2);
4345 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4346 // shouldn't be necessary except that RFP cannot be live across
4347 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4348 MachineFunction &MF = DAG.getMachineFunction();
4349 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4350 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4351 Tys = DAG.getVTList(MVT::Other);
4352 SmallVector<SDOperand, 8> Ops;
4353 Ops.push_back(Chain);
4354 Ops.push_back(Result);
4355 Ops.push_back(StackSlot);
4356 Ops.push_back(DAG.getValueType(Op.getValueType()));
4357 Ops.push_back(InFlag);
4358 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4359 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4360 PseudoSourceValue::getFixedStack(), SSFI);
4366 std::pair<SDOperand,SDOperand> X86TargetLowering::
4367 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4368 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4369 "Unknown FP_TO_SINT to lower!");
4371 // These are really Legal.
4372 if (Op.getValueType() == MVT::i32 &&
4373 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4374 return std::make_pair(SDOperand(), SDOperand());
4375 if (Subtarget->is64Bit() &&
4376 Op.getValueType() == MVT::i64 &&
4377 Op.getOperand(0).getValueType() != MVT::f80)
4378 return std::make_pair(SDOperand(), SDOperand());
4380 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4382 MachineFunction &MF = DAG.getMachineFunction();
4383 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4384 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4385 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4387 switch (Op.getValueType()) {
4388 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4389 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4390 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4391 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4394 SDOperand Chain = DAG.getEntryNode();
4395 SDOperand Value = Op.getOperand(0);
4396 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4397 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4398 Chain = DAG.getStore(Chain, Value, StackSlot,
4399 PseudoSourceValue::getFixedStack(), SSFI);
4400 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4402 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4404 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4405 Chain = Value.getValue(1);
4406 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4407 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4410 // Build the FP_TO_INT*_IN_MEM
4411 SDOperand Ops[] = { Chain, Value, StackSlot };
4412 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4414 return std::make_pair(FIST, StackSlot);
4417 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4418 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4419 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4420 if (FIST.Val == 0) return SDOperand();
4423 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4426 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4427 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4428 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4429 if (FIST.Val == 0) return 0;
4431 // Return an i64 load from the stack slot.
4432 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4434 // Use a MERGE_VALUES node to drop the chain result value.
4435 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4438 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4439 MVT::ValueType VT = Op.getValueType();
4440 MVT::ValueType EltVT = VT;
4441 if (MVT::isVector(VT))
4442 EltVT = MVT::getVectorElementType(VT);
4443 std::vector<Constant*> CV;
4444 if (EltVT == MVT::f64) {
4445 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4449 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4455 Constant *C = ConstantVector::get(CV);
4456 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4457 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4458 PseudoSourceValue::getConstantPool(), 0,
4460 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4463 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4464 MVT::ValueType VT = Op.getValueType();
4465 MVT::ValueType EltVT = VT;
4466 unsigned EltNum = 1;
4467 if (MVT::isVector(VT)) {
4468 EltVT = MVT::getVectorElementType(VT);
4469 EltNum = MVT::getVectorNumElements(VT);
4471 std::vector<Constant*> CV;
4472 if (EltVT == MVT::f64) {
4473 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4477 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4483 Constant *C = ConstantVector::get(CV);
4484 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4485 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4486 PseudoSourceValue::getConstantPool(), 0,
4488 if (MVT::isVector(VT)) {
4489 return DAG.getNode(ISD::BIT_CONVERT, VT,
4490 DAG.getNode(ISD::XOR, MVT::v2i64,
4491 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4492 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4494 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4498 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4499 SDOperand Op0 = Op.getOperand(0);
4500 SDOperand Op1 = Op.getOperand(1);
4501 MVT::ValueType VT = Op.getValueType();
4502 MVT::ValueType SrcVT = Op1.getValueType();
4504 // If second operand is smaller, extend it first.
4505 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4506 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4509 // And if it is bigger, shrink it first.
4510 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4511 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4515 // At this point the operands and the result should have the same
4516 // type, and that won't be f80 since that is not custom lowered.
4518 // First get the sign bit of second operand.
4519 std::vector<Constant*> CV;
4520 if (SrcVT == MVT::f64) {
4521 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4522 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4524 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4525 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4526 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4527 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4529 Constant *C = ConstantVector::get(CV);
4530 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4531 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4532 PseudoSourceValue::getConstantPool(), 0,
4534 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4536 // Shift sign bit right or left if the two operands have different types.
4537 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4538 // Op0 is MVT::f32, Op1 is MVT::f64.
4539 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4540 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4541 DAG.getConstant(32, MVT::i32));
4542 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4543 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4544 DAG.getIntPtrConstant(0));
4547 // Clear first operand sign bit.
4549 if (VT == MVT::f64) {
4550 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4551 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4553 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4554 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4555 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4556 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4558 C = ConstantVector::get(CV);
4559 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4560 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4561 PseudoSourceValue::getConstantPool(), 0,
4563 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4565 // Or the value with the sign bit.
4566 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4569 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4570 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4572 SDOperand Op0 = Op.getOperand(0);
4573 SDOperand Op1 = Op.getOperand(1);
4574 SDOperand CC = Op.getOperand(2);
4575 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4576 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4579 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4581 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4582 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4583 DAG.getConstant(X86CC, MVT::i8), Cond);
4586 assert(isFP && "Illegal integer SetCC!");
4588 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4589 switch (SetCCOpcode) {
4590 default: assert(false && "Illegal floating point SetCC!");
4591 case ISD::SETOEQ: { // !PF & ZF
4592 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4593 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4594 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4595 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4596 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4598 case ISD::SETUNE: { // PF | !ZF
4599 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4600 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4601 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4602 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4603 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4609 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4610 bool addTest = true;
4611 SDOperand Cond = Op.getOperand(0);
4614 if (Cond.getOpcode() == ISD::SETCC)
4615 Cond = LowerSETCC(Cond, DAG);
4617 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4618 // setting operand in place of the X86ISD::SETCC.
4619 if (Cond.getOpcode() == X86ISD::SETCC) {
4620 CC = Cond.getOperand(0);
4622 SDOperand Cmp = Cond.getOperand(1);
4623 unsigned Opc = Cmp.getOpcode();
4624 MVT::ValueType VT = Op.getValueType();
4626 bool IllegalFPCMov = false;
4627 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4628 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4629 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4631 if ((Opc == X86ISD::CMP ||
4632 Opc == X86ISD::COMI ||
4633 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4640 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4641 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4644 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4646 SmallVector<SDOperand, 4> Ops;
4647 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4648 // condition is true.
4649 Ops.push_back(Op.getOperand(2));
4650 Ops.push_back(Op.getOperand(1));
4652 Ops.push_back(Cond);
4653 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4656 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4657 bool addTest = true;
4658 SDOperand Chain = Op.getOperand(0);
4659 SDOperand Cond = Op.getOperand(1);
4660 SDOperand Dest = Op.getOperand(2);
4663 if (Cond.getOpcode() == ISD::SETCC)
4664 Cond = LowerSETCC(Cond, DAG);
4666 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4667 // setting operand in place of the X86ISD::SETCC.
4668 if (Cond.getOpcode() == X86ISD::SETCC) {
4669 CC = Cond.getOperand(0);
4671 SDOperand Cmp = Cond.getOperand(1);
4672 unsigned Opc = Cmp.getOpcode();
4673 if (Opc == X86ISD::CMP ||
4674 Opc == X86ISD::COMI ||
4675 Opc == X86ISD::UCOMI) {
4682 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4683 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4685 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4686 Chain, Op.getOperand(2), CC, Cond);
4690 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4691 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4692 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4693 // that the guard pages used by the OS virtual memory manager are allocated in
4694 // correct sequence.
4696 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4697 SelectionDAG &DAG) {
4698 assert(Subtarget->isTargetCygMing() &&
4699 "This should be used only on Cygwin/Mingw targets");
4702 SDOperand Chain = Op.getOperand(0);
4703 SDOperand Size = Op.getOperand(1);
4704 // FIXME: Ensure alignment here
4708 MVT::ValueType IntPtr = getPointerTy();
4709 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4711 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4712 Flag = Chain.getValue(1);
4714 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4715 SDOperand Ops[] = { Chain,
4716 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4717 DAG.getRegister(X86::EAX, IntPtr),
4719 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4720 Flag = Chain.getValue(1);
4722 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4724 std::vector<MVT::ValueType> Tys;
4725 Tys.push_back(SPTy);
4726 Tys.push_back(MVT::Other);
4727 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4728 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4732 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4734 SDOperand Dst, SDOperand Src,
4735 SDOperand Size, unsigned Align,
4736 const Value *DstSV, uint64_t DstSVOff) {
4737 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4739 /// If not DWORD aligned or size is more than the threshold, call the library.
4740 /// The libc version is likely to be faster for these cases. It can use the
4741 /// address value and run time information about the CPU.
4742 if ((Align & 3) == 0 ||
4744 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4745 SDOperand InFlag(0, 0);
4747 // Check to see if there is a specialized entry-point for memory zeroing.
4748 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4749 if (const char *bzeroEntry =
4750 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4751 MVT::ValueType IntPtr = getPointerTy();
4752 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4753 TargetLowering::ArgListTy Args;
4754 TargetLowering::ArgListEntry Entry;
4756 Entry.Ty = IntPtrTy;
4757 Args.push_back(Entry);
4759 Args.push_back(Entry);
4760 std::pair<SDOperand,SDOperand> CallResult =
4761 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4762 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4764 return CallResult.second;
4767 // Otherwise have the target-independent code call memset.
4771 uint64_t SizeVal = ConstantSize->getValue();
4772 SDOperand InFlag(0, 0);
4775 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4776 unsigned BytesLeft = 0;
4777 bool TwoRepStos = false;
4780 uint64_t Val = ValC->getValue() & 255;
4782 // If the value is a constant, then we can potentially use larger sets.
4783 switch (Align & 3) {
4784 case 2: // WORD aligned
4787 Val = (Val << 8) | Val;
4789 case 0: // DWORD aligned
4792 Val = (Val << 8) | Val;
4793 Val = (Val << 16) | Val;
4794 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
4797 Val = (Val << 32) | Val;
4800 default: // Byte aligned
4803 Count = DAG.getIntPtrConstant(SizeVal);
4807 if (AVT > MVT::i8) {
4808 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4809 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4810 BytesLeft = SizeVal % UBytes;
4813 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4815 InFlag = Chain.getValue(1);
4818 Count = DAG.getIntPtrConstant(SizeVal);
4819 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4820 InFlag = Chain.getValue(1);
4823 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4825 InFlag = Chain.getValue(1);
4826 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4828 InFlag = Chain.getValue(1);
4830 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4831 SmallVector<SDOperand, 8> Ops;
4832 Ops.push_back(Chain);
4833 Ops.push_back(DAG.getValueType(AVT));
4834 Ops.push_back(InFlag);
4835 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4838 InFlag = Chain.getValue(1);
4840 MVT::ValueType CVT = Count.getValueType();
4841 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4842 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4843 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4845 InFlag = Chain.getValue(1);
4846 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4848 Ops.push_back(Chain);
4849 Ops.push_back(DAG.getValueType(MVT::i8));
4850 Ops.push_back(InFlag);
4851 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4852 } else if (BytesLeft) {
4853 // Handle the last 1 - 7 bytes.
4854 unsigned Offset = SizeVal - BytesLeft;
4855 MVT::ValueType AddrVT = Dst.getValueType();
4856 MVT::ValueType SizeVT = Size.getValueType();
4858 Chain = DAG.getMemset(Chain,
4859 DAG.getNode(ISD::ADD, AddrVT, Dst,
4860 DAG.getConstant(Offset, AddrVT)),
4862 DAG.getConstant(BytesLeft, SizeVT),
4863 Align, DstSV, DstSVOff + Offset);
4866 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4871 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4873 SDOperand Dst, SDOperand Src,
4874 SDOperand Size, unsigned Align,
4876 const Value *DstSV, uint64_t DstSVOff,
4877 const Value *SrcSV, uint64_t SrcSVOff){
4879 // This requires the copy size to be a constant, preferrably
4880 // within a subtarget-specific limit.
4881 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4884 uint64_t SizeVal = ConstantSize->getValue();
4885 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4889 unsigned BytesLeft = 0;
4890 if (Align >= 8 && Subtarget->is64Bit())
4892 else if (Align >= 4)
4894 else if (Align >= 2)
4899 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4900 unsigned CountVal = SizeVal / UBytes;
4901 SDOperand Count = DAG.getIntPtrConstant(CountVal);
4902 BytesLeft = SizeVal % UBytes;
4904 SDOperand InFlag(0, 0);
4905 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4907 InFlag = Chain.getValue(1);
4908 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4910 InFlag = Chain.getValue(1);
4911 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4913 InFlag = Chain.getValue(1);
4915 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4916 SmallVector<SDOperand, 8> Ops;
4917 Ops.push_back(Chain);
4918 Ops.push_back(DAG.getValueType(AVT));
4919 Ops.push_back(InFlag);
4920 SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4922 SmallVector<SDOperand, 4> Results;
4923 Results.push_back(RepMovs);
4925 // Handle the last 1 - 7 bytes.
4926 unsigned Offset = SizeVal - BytesLeft;
4927 MVT::ValueType DstVT = Dst.getValueType();
4928 MVT::ValueType SrcVT = Src.getValueType();
4929 MVT::ValueType SizeVT = Size.getValueType();
4930 Results.push_back(DAG.getMemcpy(Chain,
4931 DAG.getNode(ISD::ADD, DstVT, Dst,
4932 DAG.getConstant(Offset, DstVT)),
4933 DAG.getNode(ISD::ADD, SrcVT, Src,
4934 DAG.getConstant(Offset, SrcVT)),
4935 DAG.getConstant(BytesLeft, SizeVT),
4936 Align, AlwaysInline,
4937 DstSV, DstSVOff + Offset,
4938 SrcSV, SrcSVOff + Offset));
4941 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4944 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4945 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4946 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4947 SDOperand TheChain = N->getOperand(0);
4948 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4949 if (Subtarget->is64Bit()) {
4950 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4951 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4952 MVT::i64, rax.getValue(2));
4953 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4954 DAG.getConstant(32, MVT::i8));
4956 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4959 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4960 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4963 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4964 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4965 MVT::i32, eax.getValue(2));
4966 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4967 SDOperand Ops[] = { eax, edx };
4968 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4970 // Use a MERGE_VALUES to return the value and chain.
4971 Ops[1] = edx.getValue(1);
4972 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4973 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4976 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4977 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4979 if (!Subtarget->is64Bit()) {
4980 // vastart just stores the address of the VarArgsFrameIndex slot into the
4981 // memory location argument.
4982 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4983 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4987 // gp_offset (0 - 6 * 8)
4988 // fp_offset (48 - 48 + 8 * 16)
4989 // overflow_arg_area (point to parameters coming in memory).
4991 SmallVector<SDOperand, 8> MemOps;
4992 SDOperand FIN = Op.getOperand(1);
4994 SDOperand Store = DAG.getStore(Op.getOperand(0),
4995 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4997 MemOps.push_back(Store);
5000 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5001 Store = DAG.getStore(Op.getOperand(0),
5002 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5004 MemOps.push_back(Store);
5006 // Store ptr to overflow_arg_area
5007 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5008 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5009 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5010 MemOps.push_back(Store);
5012 // Store ptr to reg_save_area.
5013 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5014 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5015 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5016 MemOps.push_back(Store);
5017 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5020 SDOperand X86TargetLowering::LowerVAARG(SDOperand Op, SelectionDAG &DAG) {
5021 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5022 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5023 SDOperand Chain = Op.getOperand(0);
5024 SDOperand SrcPtr = Op.getOperand(1);
5025 SDOperand SrcSV = Op.getOperand(2);
5027 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5032 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5033 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5034 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5035 SDOperand Chain = Op.getOperand(0);
5036 SDOperand DstPtr = Op.getOperand(1);
5037 SDOperand SrcPtr = Op.getOperand(2);
5038 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5039 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5041 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5042 DAG.getIntPtrConstant(24), 8, false,
5043 DstSV, 0, SrcSV, 0);
5047 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5048 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5050 default: return SDOperand(); // Don't custom lower most intrinsics.
5051 // Comparison intrinsics.
5052 case Intrinsic::x86_sse_comieq_ss:
5053 case Intrinsic::x86_sse_comilt_ss:
5054 case Intrinsic::x86_sse_comile_ss:
5055 case Intrinsic::x86_sse_comigt_ss:
5056 case Intrinsic::x86_sse_comige_ss:
5057 case Intrinsic::x86_sse_comineq_ss:
5058 case Intrinsic::x86_sse_ucomieq_ss:
5059 case Intrinsic::x86_sse_ucomilt_ss:
5060 case Intrinsic::x86_sse_ucomile_ss:
5061 case Intrinsic::x86_sse_ucomigt_ss:
5062 case Intrinsic::x86_sse_ucomige_ss:
5063 case Intrinsic::x86_sse_ucomineq_ss:
5064 case Intrinsic::x86_sse2_comieq_sd:
5065 case Intrinsic::x86_sse2_comilt_sd:
5066 case Intrinsic::x86_sse2_comile_sd:
5067 case Intrinsic::x86_sse2_comigt_sd:
5068 case Intrinsic::x86_sse2_comige_sd:
5069 case Intrinsic::x86_sse2_comineq_sd:
5070 case Intrinsic::x86_sse2_ucomieq_sd:
5071 case Intrinsic::x86_sse2_ucomilt_sd:
5072 case Intrinsic::x86_sse2_ucomile_sd:
5073 case Intrinsic::x86_sse2_ucomigt_sd:
5074 case Intrinsic::x86_sse2_ucomige_sd:
5075 case Intrinsic::x86_sse2_ucomineq_sd: {
5077 ISD::CondCode CC = ISD::SETCC_INVALID;
5080 case Intrinsic::x86_sse_comieq_ss:
5081 case Intrinsic::x86_sse2_comieq_sd:
5085 case Intrinsic::x86_sse_comilt_ss:
5086 case Intrinsic::x86_sse2_comilt_sd:
5090 case Intrinsic::x86_sse_comile_ss:
5091 case Intrinsic::x86_sse2_comile_sd:
5095 case Intrinsic::x86_sse_comigt_ss:
5096 case Intrinsic::x86_sse2_comigt_sd:
5100 case Intrinsic::x86_sse_comige_ss:
5101 case Intrinsic::x86_sse2_comige_sd:
5105 case Intrinsic::x86_sse_comineq_ss:
5106 case Intrinsic::x86_sse2_comineq_sd:
5110 case Intrinsic::x86_sse_ucomieq_ss:
5111 case Intrinsic::x86_sse2_ucomieq_sd:
5112 Opc = X86ISD::UCOMI;
5115 case Intrinsic::x86_sse_ucomilt_ss:
5116 case Intrinsic::x86_sse2_ucomilt_sd:
5117 Opc = X86ISD::UCOMI;
5120 case Intrinsic::x86_sse_ucomile_ss:
5121 case Intrinsic::x86_sse2_ucomile_sd:
5122 Opc = X86ISD::UCOMI;
5125 case Intrinsic::x86_sse_ucomigt_ss:
5126 case Intrinsic::x86_sse2_ucomigt_sd:
5127 Opc = X86ISD::UCOMI;
5130 case Intrinsic::x86_sse_ucomige_ss:
5131 case Intrinsic::x86_sse2_ucomige_sd:
5132 Opc = X86ISD::UCOMI;
5135 case Intrinsic::x86_sse_ucomineq_ss:
5136 case Intrinsic::x86_sse2_ucomineq_sd:
5137 Opc = X86ISD::UCOMI;
5143 SDOperand LHS = Op.getOperand(1);
5144 SDOperand RHS = Op.getOperand(2);
5145 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5147 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5148 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5149 DAG.getConstant(X86CC, MVT::i8), Cond);
5150 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5153 // Fix vector shift instructions where the last operand is a non-immediate
5155 case Intrinsic::x86_sse2_pslli_w:
5156 case Intrinsic::x86_sse2_pslli_d:
5157 case Intrinsic::x86_sse2_pslli_q:
5158 case Intrinsic::x86_sse2_psrli_w:
5159 case Intrinsic::x86_sse2_psrli_d:
5160 case Intrinsic::x86_sse2_psrli_q:
5161 case Intrinsic::x86_sse2_psrai_w:
5162 case Intrinsic::x86_sse2_psrai_d:
5163 case Intrinsic::x86_mmx_pslli_w:
5164 case Intrinsic::x86_mmx_pslli_d:
5165 case Intrinsic::x86_mmx_pslli_q:
5166 case Intrinsic::x86_mmx_psrli_w:
5167 case Intrinsic::x86_mmx_psrli_d:
5168 case Intrinsic::x86_mmx_psrli_q:
5169 case Intrinsic::x86_mmx_psrai_w:
5170 case Intrinsic::x86_mmx_psrai_d: {
5171 SDOperand ShAmt = Op.getOperand(2);
5172 if (isa<ConstantSDNode>(ShAmt))
5175 unsigned NewIntNo = 0;
5176 MVT::ValueType ShAmtVT = MVT::v4i32;
5178 case Intrinsic::x86_sse2_pslli_w:
5179 NewIntNo = Intrinsic::x86_sse2_psll_w;
5181 case Intrinsic::x86_sse2_pslli_d:
5182 NewIntNo = Intrinsic::x86_sse2_psll_d;
5184 case Intrinsic::x86_sse2_pslli_q:
5185 NewIntNo = Intrinsic::x86_sse2_psll_q;
5187 case Intrinsic::x86_sse2_psrli_w:
5188 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5190 case Intrinsic::x86_sse2_psrli_d:
5191 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5193 case Intrinsic::x86_sse2_psrli_q:
5194 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5196 case Intrinsic::x86_sse2_psrai_w:
5197 NewIntNo = Intrinsic::x86_sse2_psra_w;
5199 case Intrinsic::x86_sse2_psrai_d:
5200 NewIntNo = Intrinsic::x86_sse2_psra_d;
5203 ShAmtVT = MVT::v2i32;
5205 case Intrinsic::x86_mmx_pslli_w:
5206 NewIntNo = Intrinsic::x86_mmx_psll_w;
5208 case Intrinsic::x86_mmx_pslli_d:
5209 NewIntNo = Intrinsic::x86_mmx_psll_d;
5211 case Intrinsic::x86_mmx_pslli_q:
5212 NewIntNo = Intrinsic::x86_mmx_psll_q;
5214 case Intrinsic::x86_mmx_psrli_w:
5215 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5217 case Intrinsic::x86_mmx_psrli_d:
5218 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5220 case Intrinsic::x86_mmx_psrli_q:
5221 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5223 case Intrinsic::x86_mmx_psrai_w:
5224 NewIntNo = Intrinsic::x86_mmx_psra_w;
5226 case Intrinsic::x86_mmx_psrai_d:
5227 NewIntNo = Intrinsic::x86_mmx_psra_d;
5229 default: abort(); // Can't reach here.
5234 MVT::ValueType VT = Op.getValueType();
5235 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5236 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5237 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5238 DAG.getConstant(NewIntNo, MVT::i32),
5239 Op.getOperand(1), ShAmt);
5244 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5245 // Depths > 0 not supported yet!
5246 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5249 // Just load the return address
5250 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5251 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5254 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5255 // Depths > 0 not supported yet!
5256 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5259 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5260 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5261 DAG.getIntPtrConstant(4));
5264 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5265 SelectionDAG &DAG) {
5266 // Is not yet supported on x86-64
5267 if (Subtarget->is64Bit())
5270 return DAG.getIntPtrConstant(8);
5273 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5275 assert(!Subtarget->is64Bit() &&
5276 "Lowering of eh_return builtin is not supported yet on x86-64");
5278 MachineFunction &MF = DAG.getMachineFunction();
5279 SDOperand Chain = Op.getOperand(0);
5280 SDOperand Offset = Op.getOperand(1);
5281 SDOperand Handler = Op.getOperand(2);
5283 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5286 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5287 DAG.getIntPtrConstant(-4UL));
5288 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5289 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5290 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5291 MF.getRegInfo().addLiveOut(X86::ECX);
5293 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5294 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5297 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5298 SelectionDAG &DAG) {
5299 SDOperand Root = Op.getOperand(0);
5300 SDOperand Trmp = Op.getOperand(1); // trampoline
5301 SDOperand FPtr = Op.getOperand(2); // nested function
5302 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5304 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5306 const X86InstrInfo *TII =
5307 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5309 if (Subtarget->is64Bit()) {
5310 SDOperand OutChains[6];
5312 // Large code-model.
5314 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5315 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5317 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5318 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5320 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5322 // Load the pointer to the nested function into R11.
5323 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5324 SDOperand Addr = Trmp;
5325 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5328 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5329 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5331 // Load the 'nest' parameter value into R10.
5332 // R10 is specified in X86CallingConv.td
5333 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5334 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5335 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5338 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5339 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5341 // Jump to the nested function.
5342 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5343 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5344 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5347 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5348 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5349 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5353 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5354 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5356 const Function *Func =
5357 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5358 unsigned CC = Func->getCallingConv();
5363 assert(0 && "Unsupported calling convention");
5364 case CallingConv::C:
5365 case CallingConv::X86_StdCall: {
5366 // Pass 'nest' parameter in ECX.
5367 // Must be kept in sync with X86CallingConv.td
5370 // Check that ECX wasn't needed by an 'inreg' parameter.
5371 const FunctionType *FTy = Func->getFunctionType();
5372 const PAListPtr &Attrs = Func->getParamAttrs();
5374 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5375 unsigned InRegCount = 0;
5378 for (FunctionType::param_iterator I = FTy->param_begin(),
5379 E = FTy->param_end(); I != E; ++I, ++Idx)
5380 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5381 // FIXME: should only count parameters that are lowered to integers.
5382 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5384 if (InRegCount > 2) {
5385 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5391 case CallingConv::X86_FastCall:
5392 // Pass 'nest' parameter in EAX.
5393 // Must be kept in sync with X86CallingConv.td
5398 SDOperand OutChains[4];
5399 SDOperand Addr, Disp;
5401 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5402 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5404 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5405 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5406 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5409 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5410 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5412 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5413 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5414 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5415 TrmpAddr, 5, false, 1);
5417 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5418 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5421 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5422 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5426 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5428 The rounding mode is in bits 11:10 of FPSR, and has the following
5435 FLT_ROUNDS, on the other hand, expects the following:
5442 To perform the conversion, we do:
5443 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5446 MachineFunction &MF = DAG.getMachineFunction();
5447 const TargetMachine &TM = MF.getTarget();
5448 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5449 unsigned StackAlignment = TFI.getStackAlignment();
5450 MVT::ValueType VT = Op.getValueType();
5452 // Save FP Control Word to stack slot
5453 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5454 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5456 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5457 DAG.getEntryNode(), StackSlot);
5459 // Load FP Control Word from stack slot
5460 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5462 // Transform as necessary
5464 DAG.getNode(ISD::SRL, MVT::i16,
5465 DAG.getNode(ISD::AND, MVT::i16,
5466 CWD, DAG.getConstant(0x800, MVT::i16)),
5467 DAG.getConstant(11, MVT::i8));
5469 DAG.getNode(ISD::SRL, MVT::i16,
5470 DAG.getNode(ISD::AND, MVT::i16,
5471 CWD, DAG.getConstant(0x400, MVT::i16)),
5472 DAG.getConstant(9, MVT::i8));
5475 DAG.getNode(ISD::AND, MVT::i16,
5476 DAG.getNode(ISD::ADD, MVT::i16,
5477 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5478 DAG.getConstant(1, MVT::i16)),
5479 DAG.getConstant(3, MVT::i16));
5482 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5483 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5486 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5487 MVT::ValueType VT = Op.getValueType();
5488 MVT::ValueType OpVT = VT;
5489 unsigned NumBits = MVT::getSizeInBits(VT);
5491 Op = Op.getOperand(0);
5492 if (VT == MVT::i8) {
5493 // Zero extend to i32 since there is not an i8 bsr.
5495 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5498 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5499 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5500 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5502 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5503 SmallVector<SDOperand, 4> Ops;
5505 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5506 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5507 Ops.push_back(Op.getValue(1));
5508 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5510 // Finally xor with NumBits-1.
5511 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5514 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5518 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5519 MVT::ValueType VT = Op.getValueType();
5520 MVT::ValueType OpVT = VT;
5521 unsigned NumBits = MVT::getSizeInBits(VT);
5523 Op = Op.getOperand(0);
5524 if (VT == MVT::i8) {
5526 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5529 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5530 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5531 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5533 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5534 SmallVector<SDOperand, 4> Ops;
5536 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5537 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5538 Ops.push_back(Op.getValue(1));
5539 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5542 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5546 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5547 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5551 case MVT::i8: Reg = X86::AL; size = 1; break;
5552 case MVT::i16: Reg = X86::AX; size = 2; break;
5553 case MVT::i32: Reg = X86::EAX; size = 4; break;
5555 if (Subtarget->is64Bit()) {
5556 Reg = X86::RAX; size = 8;
5557 } else //Should go away when LowerType stuff lands
5558 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5561 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5562 Op.getOperand(3), SDOperand());
5563 SDOperand Ops[] = { cpIn.getValue(0),
5566 DAG.getTargetConstant(size, MVT::i8),
5568 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5569 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5571 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5575 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5576 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5577 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5578 SDOperand cpInL, cpInH;
5579 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5580 DAG.getConstant(0, MVT::i32));
5581 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5582 DAG.getConstant(1, MVT::i32));
5583 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5584 cpInL, SDOperand());
5585 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5586 cpInH, cpInL.getValue(1));
5587 SDOperand swapInL, swapInH;
5588 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5589 DAG.getConstant(0, MVT::i32));
5590 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5591 DAG.getConstant(1, MVT::i32));
5592 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5593 swapInL, cpInH.getValue(1));
5594 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5595 swapInH, swapInL.getValue(1));
5596 SDOperand Ops[] = { swapInH.getValue(0),
5598 swapInH.getValue(1)};
5599 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5600 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5601 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5602 Result.getValue(1));
5603 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5604 cpOutL.getValue(2));
5605 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5606 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5607 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5608 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5611 SDNode* X86TargetLowering::ExpandATOMIC_LSS(SDNode* Op, SelectionDAG &DAG) {
5612 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5613 assert (T == MVT::i32 && "Only know how to expand i32 LSS");
5614 SDOperand negOp = DAG.getNode(ISD::SUB, T,
5615 DAG.getConstant(0, T), Op->getOperand(2));
5616 return DAG.getAtomic(ISD::ATOMIC_LAS, Op->getOperand(0),
5617 Op->getOperand(1), negOp, T).Val;
5620 /// LowerOperation - Provide custom lowering hooks for some operations.
5622 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5623 switch (Op.getOpcode()) {
5624 default: assert(0 && "Should not custom lower this!");
5625 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5626 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5627 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5628 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5629 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5630 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5631 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5632 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5633 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5634 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5635 case ISD::SHL_PARTS:
5636 case ISD::SRA_PARTS:
5637 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5638 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5639 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5640 case ISD::FABS: return LowerFABS(Op, DAG);
5641 case ISD::FNEG: return LowerFNEG(Op, DAG);
5642 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5643 case ISD::SETCC: return LowerSETCC(Op, DAG);
5644 case ISD::SELECT: return LowerSELECT(Op, DAG);
5645 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5646 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5647 case ISD::CALL: return LowerCALL(Op, DAG);
5648 case ISD::RET: return LowerRET(Op, DAG);
5649 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5650 case ISD::VASTART: return LowerVASTART(Op, DAG);
5651 case ISD::VAARG: return LowerVAARG(Op, DAG);
5652 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5653 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5654 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5655 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5656 case ISD::FRAME_TO_ARGS_OFFSET:
5657 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5658 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5659 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5660 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5661 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5662 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5663 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5665 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5666 case ISD::READCYCLECOUNTER:
5667 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5671 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5672 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5673 switch (N->getOpcode()) {
5674 default: assert(0 && "Should not custom lower this!");
5675 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5676 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5677 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5678 case ISD::ATOMIC_LSS: return ExpandATOMIC_LSS(N,DAG);
5682 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5684 default: return NULL;
5685 case X86ISD::BSF: return "X86ISD::BSF";
5686 case X86ISD::BSR: return "X86ISD::BSR";
5687 case X86ISD::SHLD: return "X86ISD::SHLD";
5688 case X86ISD::SHRD: return "X86ISD::SHRD";
5689 case X86ISD::FAND: return "X86ISD::FAND";
5690 case X86ISD::FOR: return "X86ISD::FOR";
5691 case X86ISD::FXOR: return "X86ISD::FXOR";
5692 case X86ISD::FSRL: return "X86ISD::FSRL";
5693 case X86ISD::FILD: return "X86ISD::FILD";
5694 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5695 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5696 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5697 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5698 case X86ISD::FLD: return "X86ISD::FLD";
5699 case X86ISD::FST: return "X86ISD::FST";
5700 case X86ISD::CALL: return "X86ISD::CALL";
5701 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5702 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5703 case X86ISD::CMP: return "X86ISD::CMP";
5704 case X86ISD::COMI: return "X86ISD::COMI";
5705 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5706 case X86ISD::SETCC: return "X86ISD::SETCC";
5707 case X86ISD::CMOV: return "X86ISD::CMOV";
5708 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5709 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5710 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5711 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5712 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5713 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5714 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5715 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5716 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5717 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5718 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5719 case X86ISD::FMAX: return "X86ISD::FMAX";
5720 case X86ISD::FMIN: return "X86ISD::FMIN";
5721 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5722 case X86ISD::FRCP: return "X86ISD::FRCP";
5723 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5724 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5725 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5726 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5727 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5728 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
5729 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
5730 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
5731 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
5735 // isLegalAddressingMode - Return true if the addressing mode represented
5736 // by AM is legal for this target, for a load/store of the specified type.
5737 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5738 const Type *Ty) const {
5739 // X86 supports extremely general addressing modes.
5741 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5742 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5746 // We can only fold this if we don't need an extra load.
5747 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5750 // X86-64 only supports addr of globals in small code model.
5751 if (Subtarget->is64Bit()) {
5752 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5754 // If lower 4G is not available, then we must use rip-relative addressing.
5755 if (AM.BaseOffs || AM.Scale > 1)
5766 // These scales always work.
5771 // These scales are formed with basereg+scalereg. Only accept if there is
5776 default: // Other stuff never works.
5784 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5785 if (!Ty1->isInteger() || !Ty2->isInteger())
5787 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5788 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5789 if (NumBits1 <= NumBits2)
5791 return Subtarget->is64Bit() || NumBits1 < 64;
5794 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5795 MVT::ValueType VT2) const {
5796 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5798 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5799 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5800 if (NumBits1 <= NumBits2)
5802 return Subtarget->is64Bit() || NumBits1 < 64;
5805 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5806 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5807 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5808 /// are assumed to be legal.
5810 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5811 // Only do shuffles on 128-bit vector types for now.
5812 if (MVT::getSizeInBits(VT) == 64) return false;
5813 return (Mask.Val->getNumOperands() <= 4 ||
5814 isIdentityMask(Mask.Val) ||
5815 isIdentityMask(Mask.Val, true) ||
5816 isSplatMask(Mask.Val) ||
5817 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5818 X86::isUNPCKLMask(Mask.Val) ||
5819 X86::isUNPCKHMask(Mask.Val) ||
5820 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5821 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5825 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5827 SelectionDAG &DAG) const {
5828 unsigned NumElts = BVOps.size();
5829 // Only do shuffles on 128-bit vector types for now.
5830 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5831 if (NumElts == 2) return true;
5833 return (isMOVLMask(&BVOps[0], 4) ||
5834 isCommutedMOVL(&BVOps[0], 4, true) ||
5835 isSHUFPMask(&BVOps[0], 4) ||
5836 isCommutedSHUFP(&BVOps[0], 4));
5841 //===----------------------------------------------------------------------===//
5842 // X86 Scheduler Hooks
5843 //===----------------------------------------------------------------------===//
5845 // private utility function
5847 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
5848 MachineBasicBlock *MBB,
5851 // For the atomic bitwise operator, we generate
5854 // ld t1 = [bitinstr.addr]
5855 // op t2 = t1, [bitinstr.val]
5857 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5859 // fallthrough -->nextMBB
5860 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5861 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5862 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5865 /// First build the CFG
5866 MachineFunction *F = MBB->getParent();
5867 MachineBasicBlock *thisMBB = MBB;
5868 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5869 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5870 F->getBasicBlockList().insert(MBBIter, newMBB);
5871 F->getBasicBlockList().insert(MBBIter, nextMBB);
5873 // Move all successors to thisMBB to nextMBB
5874 nextMBB->transferSuccessors(thisMBB);
5876 // Update thisMBB to fall through to newMBB
5877 thisMBB->addSuccessor(newMBB);
5879 // newMBB jumps to itself and fall through to nextMBB
5880 newMBB->addSuccessor(nextMBB);
5881 newMBB->addSuccessor(newMBB);
5883 // Insert instructions into newMBB based on incoming instruction
5884 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
5885 MachineOperand& destOper = bInstr->getOperand(0);
5886 MachineOperand* argOpers[6];
5887 int numArgs = bInstr->getNumOperands() - 1;
5888 for (int i=0; i < numArgs; ++i)
5889 argOpers[i] = &bInstr->getOperand(i+1);
5891 // x86 address has 4 operands: base, index, scale, and displacement
5892 int lastAddrIndx = 3; // [0,3]
5895 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5896 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5897 for (int i=0; i <= lastAddrIndx; ++i)
5898 (*MIB).addOperand(*argOpers[i]);
5900 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5901 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5902 && "invalid operand");
5903 if (argOpers[valArgIndx]->isReg())
5904 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
5906 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
5908 (*MIB).addOperand(*argOpers[valArgIndx]);
5910 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5913 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
5914 for (int i=0; i <= lastAddrIndx; ++i)
5915 (*MIB).addOperand(*argOpers[i]);
5918 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
5919 MIB.addReg(X86::EAX);
5922 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
5924 delete bInstr; // The pseudo instruction is gone now.
5928 // private utility function
5930 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
5931 MachineBasicBlock *MBB,
5933 // For the atomic min/max operator, we generate
5936 // ld t1 = [min/max.addr]
5937 // mov t2 = [min/max.val]
5939 // cmov[cond] t2 = t1
5941 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5943 // fallthrough -->nextMBB
5945 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5946 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5947 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5950 /// First build the CFG
5951 MachineFunction *F = MBB->getParent();
5952 MachineBasicBlock *thisMBB = MBB;
5953 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5954 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5955 F->getBasicBlockList().insert(MBBIter, newMBB);
5956 F->getBasicBlockList().insert(MBBIter, nextMBB);
5958 // Move all successors to thisMBB to nextMBB
5959 nextMBB->transferSuccessors(thisMBB);
5961 // Update thisMBB to fall through to newMBB
5962 thisMBB->addSuccessor(newMBB);
5964 // newMBB jumps to newMBB and fall through to nextMBB
5965 newMBB->addSuccessor(nextMBB);
5966 newMBB->addSuccessor(newMBB);
5968 // Insert instructions into newMBB based on incoming instruction
5969 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
5970 MachineOperand& destOper = mInstr->getOperand(0);
5971 MachineOperand* argOpers[6];
5972 int numArgs = mInstr->getNumOperands() - 1;
5973 for (int i=0; i < numArgs; ++i)
5974 argOpers[i] = &mInstr->getOperand(i+1);
5976 // x86 address has 4 operands: base, index, scale, and displacement
5977 int lastAddrIndx = 3; // [0,3]
5980 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5981 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5982 for (int i=0; i <= lastAddrIndx; ++i)
5983 (*MIB).addOperand(*argOpers[i]);
5985 // We only support register and immediate values
5986 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5987 && "invalid operand");
5989 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5990 if (argOpers[valArgIndx]->isReg())
5991 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5993 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5994 (*MIB).addOperand(*argOpers[valArgIndx]);
5996 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5999 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6004 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6005 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6009 // Cmp and exchange if none has modified the memory location
6010 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6011 for (int i=0; i <= lastAddrIndx; ++i)
6012 (*MIB).addOperand(*argOpers[i]);
6015 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6016 MIB.addReg(X86::EAX);
6019 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6021 delete mInstr; // The pseudo instruction is gone now.
6027 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6028 MachineBasicBlock *BB) {
6029 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6030 switch (MI->getOpcode()) {
6031 default: assert(false && "Unexpected instr type to insert");
6032 case X86::CMOV_FR32:
6033 case X86::CMOV_FR64:
6034 case X86::CMOV_V4F32:
6035 case X86::CMOV_V2F64:
6036 case X86::CMOV_V2I64: {
6037 // To "insert" a SELECT_CC instruction, we actually have to insert the
6038 // diamond control-flow pattern. The incoming instruction knows the
6039 // destination vreg to set, the condition code register to branch on, the
6040 // true/false values to select between, and a branch opcode to use.
6041 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6042 ilist<MachineBasicBlock>::iterator It = BB;
6048 // cmpTY ccX, r1, r2
6050 // fallthrough --> copy0MBB
6051 MachineBasicBlock *thisMBB = BB;
6052 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
6053 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
6055 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6056 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6057 MachineFunction *F = BB->getParent();
6058 F->getBasicBlockList().insert(It, copy0MBB);
6059 F->getBasicBlockList().insert(It, sinkMBB);
6060 // Update machine-CFG edges by transferring all successors of the current
6061 // block to the new block which will contain the Phi node for the select.
6062 sinkMBB->transferSuccessors(BB);
6064 // Add the true and fallthrough blocks as its successors.
6065 BB->addSuccessor(copy0MBB);
6066 BB->addSuccessor(sinkMBB);
6069 // %FalseValue = ...
6070 // # fallthrough to sinkMBB
6073 // Update machine-CFG edges
6074 BB->addSuccessor(sinkMBB);
6077 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6080 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6081 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6082 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6084 delete MI; // The pseudo instruction is gone now.
6088 case X86::FP32_TO_INT16_IN_MEM:
6089 case X86::FP32_TO_INT32_IN_MEM:
6090 case X86::FP32_TO_INT64_IN_MEM:
6091 case X86::FP64_TO_INT16_IN_MEM:
6092 case X86::FP64_TO_INT32_IN_MEM:
6093 case X86::FP64_TO_INT64_IN_MEM:
6094 case X86::FP80_TO_INT16_IN_MEM:
6095 case X86::FP80_TO_INT32_IN_MEM:
6096 case X86::FP80_TO_INT64_IN_MEM: {
6097 // Change the floating point control register to use "round towards zero"
6098 // mode when truncating to an integer value.
6099 MachineFunction *F = BB->getParent();
6100 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6101 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6103 // Load the old value of the high byte of the control word...
6105 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6106 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6108 // Set the high part to be round to zero...
6109 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6112 // Reload the modified control word now...
6113 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6115 // Restore the memory image of control word to original value
6116 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6119 // Get the X86 opcode to use.
6121 switch (MI->getOpcode()) {
6122 default: assert(0 && "illegal opcode!");
6123 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6124 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6125 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6126 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6127 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6128 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6129 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6130 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6131 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6135 MachineOperand &Op = MI->getOperand(0);
6136 if (Op.isRegister()) {
6137 AM.BaseType = X86AddressMode::RegBase;
6138 AM.Base.Reg = Op.getReg();
6140 AM.BaseType = X86AddressMode::FrameIndexBase;
6141 AM.Base.FrameIndex = Op.getIndex();
6143 Op = MI->getOperand(1);
6144 if (Op.isImmediate())
6145 AM.Scale = Op.getImm();
6146 Op = MI->getOperand(2);
6147 if (Op.isImmediate())
6148 AM.IndexReg = Op.getImm();
6149 Op = MI->getOperand(3);
6150 if (Op.isGlobalAddress()) {
6151 AM.GV = Op.getGlobal();
6153 AM.Disp = Op.getImm();
6155 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6156 .addReg(MI->getOperand(4).getReg());
6158 // Reload the original control word now.
6159 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6161 delete MI; // The pseudo instruction is gone now.
6164 case X86::ATOMAND32:
6165 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6168 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6170 case X86::ATOMXOR32:
6171 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6173 case X86::ATOMMIN32:
6174 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6175 case X86::ATOMMAX32:
6176 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6177 case X86::ATOMUMIN32:
6178 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6179 case X86::ATOMUMAX32:
6180 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6184 //===----------------------------------------------------------------------===//
6185 // X86 Optimization Hooks
6186 //===----------------------------------------------------------------------===//
6188 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
6192 const SelectionDAG &DAG,
6193 unsigned Depth) const {
6194 unsigned Opc = Op.getOpcode();
6195 assert((Opc >= ISD::BUILTIN_OP_END ||
6196 Opc == ISD::INTRINSIC_WO_CHAIN ||
6197 Opc == ISD::INTRINSIC_W_CHAIN ||
6198 Opc == ISD::INTRINSIC_VOID) &&
6199 "Should use MaskedValueIsZero if you don't know whether Op"
6200 " is a target node!");
6202 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6206 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6207 Mask.getBitWidth() - 1);
6212 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6213 /// node is a GlobalAddress + offset.
6214 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6215 GlobalValue* &GA, int64_t &Offset) const{
6216 if (N->getOpcode() == X86ISD::Wrapper) {
6217 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6218 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6222 return TargetLowering::isGAPlusOffset(N, GA, Offset);
6225 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6226 const TargetLowering &TLI) {
6229 if (TLI.isGAPlusOffset(Base, GV, Offset))
6230 return (GV->getAlignment() >= N && (Offset % N) == 0);
6231 // DAG combine handles the stack object case.
6235 static bool EltsFromConsecutiveLoads(SDNode *N, SDOperand PermMask,
6236 unsigned NumElems, MVT::ValueType EVT,
6238 SelectionDAG &DAG, MachineFrameInfo *MFI,
6239 const TargetLowering &TLI) {
6241 for (unsigned i = 0; i < NumElems; ++i) {
6242 SDOperand Idx = PermMask.getOperand(i);
6243 if (Idx.getOpcode() == ISD::UNDEF) {
6249 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
6250 SDOperand Elt = DAG.getShuffleScalarElt(N, Index);
6252 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6256 if (Base->getOpcode() == ISD::UNDEF)
6260 if (Elt.getOpcode() == ISD::UNDEF)
6263 if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6264 MVT::getSizeInBits(EVT)/8, i, MFI))
6270 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6271 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6272 /// if the load addresses are consecutive, non-overlapping, and in the right
6274 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6275 const TargetLowering &TLI) {
6276 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6277 MVT::ValueType VT = N->getValueType(0);
6278 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6279 SDOperand PermMask = N->getOperand(2);
6280 unsigned NumElems = PermMask.getNumOperands();
6281 SDNode *Base = NULL;
6282 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6286 LoadSDNode *LD = cast<LoadSDNode>(Base);
6287 if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6288 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6289 LD->getSrcValueOffset(), LD->isVolatile());
6290 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6291 LD->getSrcValueOffset(), LD->isVolatile(),
6292 LD->getAlignment());
6295 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6296 static SDOperand PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6297 const X86Subtarget *Subtarget,
6298 const TargetLowering &TLI) {
6299 // Ignore single operand BUILD_VECTOR.
6300 if (N->getNumOperands() == 1)
6303 MVT::ValueType VT = N->getValueType(0);
6304 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6305 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6306 // We are looking for load i64 and zero extend. We want to transform
6307 // it before legalizer has a chance to expand it. Also look for i64
6308 // BUILD_PAIR bit casted to f64.
6310 // This must be an insertion into a zero vector.
6311 SDOperand HighElt = N->getOperand(1);
6312 if (!isZeroNode(HighElt))
6315 // Value must be a load.
6316 SDNode *Base = N->getOperand(0).Val;
6317 if (!isa<LoadSDNode>(Base)) {
6318 if (Base->getOpcode() != ISD::BIT_CONVERT)
6320 Base = Base->getOperand(0).Val;
6321 if (!isa<LoadSDNode>(Base))
6325 // Transform it into VZEXT_LOAD addr.
6326 LoadSDNode *LD = cast<LoadSDNode>(Base);
6327 return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6330 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6331 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6332 const X86Subtarget *Subtarget) {
6333 SDOperand Cond = N->getOperand(0);
6335 // If we have SSE[12] support, try to form min/max nodes.
6336 if (Subtarget->hasSSE2() &&
6337 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6338 if (Cond.getOpcode() == ISD::SETCC) {
6339 // Get the LHS/RHS of the select.
6340 SDOperand LHS = N->getOperand(1);
6341 SDOperand RHS = N->getOperand(2);
6342 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6344 unsigned Opcode = 0;
6345 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6348 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6351 if (!UnsafeFPMath) break;
6353 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6355 Opcode = X86ISD::FMIN;
6358 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6361 if (!UnsafeFPMath) break;
6363 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6365 Opcode = X86ISD::FMAX;
6368 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6371 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6374 if (!UnsafeFPMath) break;
6376 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6378 Opcode = X86ISD::FMIN;
6381 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6384 if (!UnsafeFPMath) break;
6386 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6388 Opcode = X86ISD::FMAX;
6394 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6402 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6403 static SDOperand PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6404 const X86Subtarget *Subtarget) {
6405 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6406 // the FP state in cases where an emms may be missing.
6407 // A preferable solution to the general problem is to figure out the right
6408 // places to insert EMMS. This qualifies as a quick hack.
6409 StoreSDNode *St = cast<StoreSDNode>(N);
6410 if (MVT::isVector(St->getValue().getValueType()) &&
6411 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6412 isa<LoadSDNode>(St->getValue()) &&
6413 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6414 St->getChain().hasOneUse() && !St->isVolatile()) {
6415 SDNode* LdVal = St->getValue().Val;
6417 int TokenFactorIndex = -1;
6418 SmallVector<SDOperand, 8> Ops;
6419 SDNode* ChainVal = St->getChain().Val;
6420 // Must be a store of a load. We currently handle two cases: the load
6421 // is a direct child, and it's under an intervening TokenFactor. It is
6422 // possible to dig deeper under nested TokenFactors.
6423 if (ChainVal == LdVal)
6424 Ld = cast<LoadSDNode>(St->getChain());
6425 else if (St->getValue().hasOneUse() &&
6426 ChainVal->getOpcode() == ISD::TokenFactor) {
6427 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6428 if (ChainVal->getOperand(i).Val == LdVal) {
6429 TokenFactorIndex = i;
6430 Ld = cast<LoadSDNode>(St->getValue());
6432 Ops.push_back(ChainVal->getOperand(i));
6436 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6437 if (Subtarget->is64Bit()) {
6438 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6439 Ld->getBasePtr(), Ld->getSrcValue(),
6440 Ld->getSrcValueOffset(), Ld->isVolatile(),
6441 Ld->getAlignment());
6442 SDOperand NewChain = NewLd.getValue(1);
6443 if (TokenFactorIndex != -1) {
6444 Ops.push_back(NewChain);
6445 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6448 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6449 St->getSrcValue(), St->getSrcValueOffset(),
6450 St->isVolatile(), St->getAlignment());
6453 // Otherwise, lower to two 32-bit copies.
6454 SDOperand LoAddr = Ld->getBasePtr();
6455 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6456 DAG.getConstant(MVT::i32, 4));
6458 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6459 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6460 Ld->isVolatile(), Ld->getAlignment());
6461 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6462 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6464 MinAlign(Ld->getAlignment(), 4));
6466 SDOperand NewChain = LoLd.getValue(1);
6467 if (TokenFactorIndex != -1) {
6468 Ops.push_back(LoLd);
6469 Ops.push_back(HiLd);
6470 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6474 LoAddr = St->getBasePtr();
6475 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6476 DAG.getConstant(MVT::i32, 4));
6478 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6479 St->getSrcValue(), St->getSrcValueOffset(),
6480 St->isVolatile(), St->getAlignment());
6481 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6482 St->getSrcValue(), St->getSrcValueOffset()+4,
6484 MinAlign(St->getAlignment(), 4));
6485 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6491 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6492 /// X86ISD::FXOR nodes.
6493 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6494 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6495 // F[X]OR(0.0, x) -> x
6496 // F[X]OR(x, 0.0) -> x
6497 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6498 if (C->getValueAPF().isPosZero())
6499 return N->getOperand(1);
6500 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6501 if (C->getValueAPF().isPosZero())
6502 return N->getOperand(0);
6506 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6507 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6508 // FAND(0.0, x) -> 0.0
6509 // FAND(x, 0.0) -> 0.0
6510 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6511 if (C->getValueAPF().isPosZero())
6512 return N->getOperand(0);
6513 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6514 if (C->getValueAPF().isPosZero())
6515 return N->getOperand(1);
6520 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6521 DAGCombinerInfo &DCI) const {
6522 SelectionDAG &DAG = DCI.DAG;
6523 switch (N->getOpcode()) {
6525 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6526 case ISD::BUILD_VECTOR:
6527 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6528 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6529 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
6531 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6532 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6538 //===----------------------------------------------------------------------===//
6539 // X86 Inline Assembly Support
6540 //===----------------------------------------------------------------------===//
6542 /// getConstraintType - Given a constraint letter, return the type of
6543 /// constraint it is for this target.
6544 X86TargetLowering::ConstraintType
6545 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6546 if (Constraint.size() == 1) {
6547 switch (Constraint[0]) {
6558 return C_RegisterClass;
6563 return TargetLowering::getConstraintType(Constraint);
6566 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6567 /// with another that has more specific requirements based on the type of the
6568 /// corresponding operand.
6569 const char *X86TargetLowering::
6570 LowerXConstraint(MVT::ValueType ConstraintVT) const {
6571 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6572 // 'f' like normal targets.
6573 if (MVT::isFloatingPoint(ConstraintVT)) {
6574 if (Subtarget->hasSSE2())
6576 if (Subtarget->hasSSE1())
6580 return TargetLowering::LowerXConstraint(ConstraintVT);
6583 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6584 /// vector. If it is invalid, don't add anything to Ops.
6585 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6587 std::vector<SDOperand>&Ops,
6588 SelectionDAG &DAG) const {
6589 SDOperand Result(0, 0);
6591 switch (Constraint) {
6594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6595 if (C->getValue() <= 31) {
6596 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6602 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6603 if (C->getValue() <= 255) {
6604 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6610 // Literal immediates are always ok.
6611 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6612 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6616 // If we are in non-pic codegen mode, we allow the address of a global (with
6617 // an optional displacement) to be used with 'i'.
6618 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6621 // Match either (GA) or (GA+C)
6623 Offset = GA->getOffset();
6624 } else if (Op.getOpcode() == ISD::ADD) {
6625 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6626 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6628 Offset = GA->getOffset()+C->getValue();
6630 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6631 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6633 Offset = GA->getOffset()+C->getValue();
6640 // If addressing this global requires a load (e.g. in PIC mode), we can't
6642 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6646 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6652 // Otherwise, not valid for this mode.
6658 Ops.push_back(Result);
6661 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6664 std::vector<unsigned> X86TargetLowering::
6665 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6666 MVT::ValueType VT) const {
6667 if (Constraint.size() == 1) {
6668 // FIXME: not handling fp-stack yet!
6669 switch (Constraint[0]) { // GCC X86 Constraint Letters
6670 default: break; // Unknown constraint letter
6671 case 'A': // EAX/EDX
6672 if (VT == MVT::i32 || VT == MVT::i64)
6673 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6675 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6678 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6679 else if (VT == MVT::i16)
6680 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6681 else if (VT == MVT::i8)
6682 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6683 else if (VT == MVT::i64)
6684 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6689 return std::vector<unsigned>();
6692 std::pair<unsigned, const TargetRegisterClass*>
6693 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6694 MVT::ValueType VT) const {
6695 // First, see if this is a constraint that directly corresponds to an LLVM
6697 if (Constraint.size() == 1) {
6698 // GCC Constraint Letters
6699 switch (Constraint[0]) {
6701 case 'r': // GENERAL_REGS
6702 case 'R': // LEGACY_REGS
6703 case 'l': // INDEX_REGS
6704 if (VT == MVT::i64 && Subtarget->is64Bit())
6705 return std::make_pair(0U, X86::GR64RegisterClass);
6707 return std::make_pair(0U, X86::GR32RegisterClass);
6708 else if (VT == MVT::i16)
6709 return std::make_pair(0U, X86::GR16RegisterClass);
6710 else if (VT == MVT::i8)
6711 return std::make_pair(0U, X86::GR8RegisterClass);
6713 case 'f': // FP Stack registers.
6714 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6715 // value to the correct fpstack register class.
6716 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6717 return std::make_pair(0U, X86::RFP32RegisterClass);
6718 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6719 return std::make_pair(0U, X86::RFP64RegisterClass);
6720 return std::make_pair(0U, X86::RFP80RegisterClass);
6721 case 'y': // MMX_REGS if MMX allowed.
6722 if (!Subtarget->hasMMX()) break;
6723 return std::make_pair(0U, X86::VR64RegisterClass);
6725 case 'Y': // SSE_REGS if SSE2 allowed
6726 if (!Subtarget->hasSSE2()) break;
6728 case 'x': // SSE_REGS if SSE1 allowed
6729 if (!Subtarget->hasSSE1()) break;
6733 // Scalar SSE types.
6736 return std::make_pair(0U, X86::FR32RegisterClass);
6739 return std::make_pair(0U, X86::FR64RegisterClass);
6747 return std::make_pair(0U, X86::VR128RegisterClass);
6753 // Use the default implementation in TargetLowering to convert the register
6754 // constraint into a member of a register class.
6755 std::pair<unsigned, const TargetRegisterClass*> Res;
6756 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6758 // Not found as a standard register?
6759 if (Res.second == 0) {
6760 // GCC calls "st(0)" just plain "st".
6761 if (StringsEqualNoCase("{st}", Constraint)) {
6762 Res.first = X86::ST0;
6763 Res.second = X86::RFP80RegisterClass;
6769 // Otherwise, check to see if this is a register class of the wrong value
6770 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6771 // turn into {ax},{dx}.
6772 if (Res.second->hasType(VT))
6773 return Res; // Correct type already, nothing to do.
6775 // All of the single-register GCC register classes map their values onto
6776 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6777 // really want an 8-bit or 32-bit register, map to the appropriate register
6778 // class and return the appropriate register.
6779 if (Res.second != X86::GR16RegisterClass)
6782 if (VT == MVT::i8) {
6783 unsigned DestReg = 0;
6784 switch (Res.first) {
6786 case X86::AX: DestReg = X86::AL; break;
6787 case X86::DX: DestReg = X86::DL; break;
6788 case X86::CX: DestReg = X86::CL; break;
6789 case X86::BX: DestReg = X86::BL; break;
6792 Res.first = DestReg;
6793 Res.second = Res.second = X86::GR8RegisterClass;
6795 } else if (VT == MVT::i32) {
6796 unsigned DestReg = 0;
6797 switch (Res.first) {
6799 case X86::AX: DestReg = X86::EAX; break;
6800 case X86::DX: DestReg = X86::EDX; break;
6801 case X86::CX: DestReg = X86::ECX; break;
6802 case X86::BX: DestReg = X86::EBX; break;
6803 case X86::SI: DestReg = X86::ESI; break;
6804 case X86::DI: DestReg = X86::EDI; break;
6805 case X86::BP: DestReg = X86::EBP; break;
6806 case X86::SP: DestReg = X86::ESP; break;
6809 Res.first = DestReg;
6810 Res.second = Res.second = X86::GR32RegisterClass;
6812 } else if (VT == MVT::i64) {
6813 unsigned DestReg = 0;
6814 switch (Res.first) {
6816 case X86::AX: DestReg = X86::RAX; break;
6817 case X86::DX: DestReg = X86::RDX; break;
6818 case X86::CX: DestReg = X86::RCX; break;
6819 case X86::BX: DestReg = X86::RBX; break;
6820 case X86::SI: DestReg = X86::RSI; break;
6821 case X86::DI: DestReg = X86::RDI; break;
6822 case X86::BP: DestReg = X86::RBP; break;
6823 case X86::SP: DestReg = X86::RSP; break;
6826 Res.first = DestReg;
6827 Res.second = Res.second = X86::GR64RegisterClass;