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(TargetMachine &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 setOperationAction(ISD::ATOMIC_LCS , MVT::i8, Custom);
296 setOperationAction(ISD::ATOMIC_LCS , MVT::i16, Custom);
297 setOperationAction(ISD::ATOMIC_LCS , MVT::i32, Custom);
298 setOperationAction(ISD::ATOMIC_LCS , MVT::i64, Custom);
300 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
301 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
302 // FIXME - use subtarget debug flags
303 if (!Subtarget->isTargetDarwin() &&
304 !Subtarget->isTargetELF() &&
305 !Subtarget->isTargetCygMing())
306 setOperationAction(ISD::LABEL, MVT::Other, Expand);
308 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
309 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
310 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
311 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
312 if (Subtarget->is64Bit()) {
314 setExceptionPointerRegister(X86::RAX);
315 setExceptionSelectorRegister(X86::RDX);
317 setExceptionPointerRegister(X86::EAX);
318 setExceptionSelectorRegister(X86::EDX);
320 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
322 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
324 setOperationAction(ISD::TRAP, MVT::Other, Legal);
326 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
327 setOperationAction(ISD::VASTART , MVT::Other, Custom);
328 setOperationAction(ISD::VAARG , MVT::Other, Expand);
329 setOperationAction(ISD::VAEND , MVT::Other, Expand);
330 if (Subtarget->is64Bit())
331 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
333 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
335 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
336 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
337 if (Subtarget->is64Bit())
338 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
339 if (Subtarget->isTargetCygMing())
340 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
342 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
344 if (X86ScalarSSEf64) {
345 // f32 and f64 use SSE.
346 // Set up the FP register classes.
347 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
348 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
350 // Use ANDPD to simulate FABS.
351 setOperationAction(ISD::FABS , MVT::f64, Custom);
352 setOperationAction(ISD::FABS , MVT::f32, Custom);
354 // Use XORP to simulate FNEG.
355 setOperationAction(ISD::FNEG , MVT::f64, Custom);
356 setOperationAction(ISD::FNEG , MVT::f32, Custom);
358 // Use ANDPD and ORPD to simulate FCOPYSIGN.
359 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
360 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
362 // We don't support sin/cos/fmod
363 setOperationAction(ISD::FSIN , MVT::f64, Expand);
364 setOperationAction(ISD::FCOS , MVT::f64, Expand);
365 setOperationAction(ISD::FSIN , MVT::f32, Expand);
366 setOperationAction(ISD::FCOS , MVT::f32, Expand);
368 // Expand FP immediates into loads from the stack, except for the special
370 addLegalFPImmediate(APFloat(+0.0)); // xorpd
371 addLegalFPImmediate(APFloat(+0.0f)); // xorps
373 // Floating truncations from f80 and extensions to f80 go through memory.
374 // If optimizing, we lie about this though and handle it in
375 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
377 setConvertAction(MVT::f32, MVT::f80, Expand);
378 setConvertAction(MVT::f64, MVT::f80, Expand);
379 setConvertAction(MVT::f80, MVT::f32, Expand);
380 setConvertAction(MVT::f80, MVT::f64, Expand);
382 } else if (X86ScalarSSEf32) {
383 // Use SSE for f32, x87 for f64.
384 // Set up the FP register classes.
385 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
386 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
388 // Use ANDPS to simulate FABS.
389 setOperationAction(ISD::FABS , MVT::f32, Custom);
391 // Use XORP to simulate FNEG.
392 setOperationAction(ISD::FNEG , MVT::f32, Custom);
394 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
396 // Use ANDPS and ORPS to simulate FCOPYSIGN.
397 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
398 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
400 // We don't support sin/cos/fmod
401 setOperationAction(ISD::FSIN , MVT::f32, Expand);
402 setOperationAction(ISD::FCOS , MVT::f32, Expand);
404 // Special cases we handle for FP constants.
405 addLegalFPImmediate(APFloat(+0.0f)); // xorps
406 addLegalFPImmediate(APFloat(+0.0)); // FLD0
407 addLegalFPImmediate(APFloat(+1.0)); // FLD1
408 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
409 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
411 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
412 // this though and handle it in InstructionSelectPreprocess so that
413 // dagcombine2 can hack on these.
415 setConvertAction(MVT::f32, MVT::f64, Expand);
416 setConvertAction(MVT::f32, MVT::f80, Expand);
417 setConvertAction(MVT::f80, MVT::f32, Expand);
418 setConvertAction(MVT::f64, MVT::f32, Expand);
419 // And x87->x87 truncations also.
420 setConvertAction(MVT::f80, MVT::f64, Expand);
424 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
425 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
428 // f32 and f64 in x87.
429 // Set up the FP register classes.
430 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
431 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
433 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
434 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
435 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
438 // Floating truncations go through memory. If optimizing, we lie about
439 // this though and handle it in InstructionSelectPreprocess so that
440 // dagcombine2 can hack on these.
442 setConvertAction(MVT::f80, MVT::f32, Expand);
443 setConvertAction(MVT::f64, MVT::f32, Expand);
444 setConvertAction(MVT::f80, MVT::f64, Expand);
448 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
449 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
451 addLegalFPImmediate(APFloat(+0.0)); // FLD0
452 addLegalFPImmediate(APFloat(+1.0)); // FLD1
453 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
454 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
455 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
456 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
457 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
458 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
461 // Long double always uses X87.
462 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
463 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
464 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
466 APFloat TmpFlt(+0.0);
467 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
468 addLegalFPImmediate(TmpFlt); // FLD0
470 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
471 APFloat TmpFlt2(+1.0);
472 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
473 addLegalFPImmediate(TmpFlt2); // FLD1
474 TmpFlt2.changeSign();
475 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
479 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
480 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
483 // Always use a library call for pow.
484 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
485 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
486 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
488 // First set operation action for all vector types to expand. Then we
489 // will selectively turn on ones that can be effectively codegen'd.
490 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
491 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
492 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
525 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
526 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
527 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
528 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
531 if (Subtarget->hasMMX()) {
532 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
533 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
534 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
535 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
537 // FIXME: add MMX packed arithmetics
539 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
540 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
541 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
542 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
544 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
545 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
546 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
547 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
549 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
550 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
552 setOperationAction(ISD::AND, MVT::v8i8, Promote);
553 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
554 setOperationAction(ISD::AND, MVT::v4i16, Promote);
555 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
556 setOperationAction(ISD::AND, MVT::v2i32, Promote);
557 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
558 setOperationAction(ISD::AND, MVT::v1i64, Legal);
560 setOperationAction(ISD::OR, MVT::v8i8, Promote);
561 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
562 setOperationAction(ISD::OR, MVT::v4i16, Promote);
563 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
564 setOperationAction(ISD::OR, MVT::v2i32, Promote);
565 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
566 setOperationAction(ISD::OR, MVT::v1i64, Legal);
568 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
569 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
570 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
571 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
572 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
573 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
574 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
576 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
577 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
578 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
579 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
580 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
581 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
582 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
584 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
585 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
586 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
587 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
589 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
590 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
591 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
592 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
594 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
595 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
596 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
599 if (Subtarget->hasSSE1()) {
600 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
602 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
603 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
604 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
605 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
606 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
607 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
608 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
609 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
610 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
611 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
612 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
615 if (Subtarget->hasSSE2()) {
616 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
617 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
618 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
619 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
620 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
622 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
623 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
624 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
625 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
626 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
627 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
628 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
629 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
630 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
631 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
632 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
633 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
634 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
635 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
636 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
638 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
640 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
641 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
642 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
644 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
645 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
646 // Do not attempt to custom lower non-power-of-2 vectors
647 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
649 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
653 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
654 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
658 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
659 if (Subtarget->is64Bit()) {
660 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
661 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
664 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
665 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
666 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
667 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
668 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
669 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
670 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
671 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
672 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
673 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
674 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
675 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
678 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
680 // Custom lower v2i64 and v2f64 selects.
681 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
682 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
683 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
684 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
687 if (Subtarget->hasSSE41()) {
688 // FIXME: Do we need to handle scalar-to-vector here?
689 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
691 // i8 and i16 vectors are custom , because the source register and source
692 // source memory operand types are not the same width. f32 vectors are
693 // custom since the immediate controlling the insert encodes additional
695 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
696 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
697 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
698 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
702 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
703 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
705 if (Subtarget->is64Bit()) {
706 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
707 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
711 // We want to custom lower some of our intrinsics.
712 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
714 // We have target-specific dag combine patterns for the following nodes:
715 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
716 setTargetDAGCombine(ISD::SELECT);
717 setTargetDAGCombine(ISD::STORE);
719 computeRegisterProperties();
721 // FIXME: These should be based on subtarget info. Plus, the values should
722 // be smaller when we are in optimizing for size mode.
723 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
724 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
725 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
726 allowUnalignedMemoryAccesses = true; // x86 supports it!
727 setPrefLoopAlignment(16);
732 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
737 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
738 /// the desired ByVal argument alignment.
739 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
742 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
743 if (VTy->getBitWidth() == 128)
745 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
746 unsigned EltAlign = 0;
747 getMaxByValAlign(ATy->getElementType(), EltAlign);
748 if (EltAlign > MaxAlign)
750 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
751 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
752 unsigned EltAlign = 0;
753 getMaxByValAlign(STy->getElementType(i), EltAlign);
754 if (EltAlign > MaxAlign)
763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
764 /// function arguments in the caller parameter area. For X86, aggregates
765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
766 /// are at 4-byte boundaries.
767 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
768 if (Subtarget->is64Bit())
769 return getTargetData()->getABITypeAlignment(Ty);
771 if (Subtarget->hasSSE1())
772 getMaxByValAlign(Ty, Align);
776 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
778 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
779 SelectionDAG &DAG) const {
780 if (usesGlobalOffsetTable())
781 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
782 if (!Subtarget->isPICStyleRIPRel())
783 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
787 //===----------------------------------------------------------------------===//
788 // Return Value Calling Convention Implementation
789 //===----------------------------------------------------------------------===//
791 #include "X86GenCallingConv.inc"
793 /// LowerRET - Lower an ISD::RET node.
794 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
795 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
797 SmallVector<CCValAssign, 16> RVLocs;
798 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
799 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
800 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
801 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
803 // If this is the first return lowered for this function, add the regs to the
804 // liveout set for the function.
805 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
806 for (unsigned i = 0; i != RVLocs.size(); ++i)
807 if (RVLocs[i].isRegLoc())
808 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
810 SDOperand Chain = Op.getOperand(0);
812 // Handle tail call return.
813 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
814 if (Chain.getOpcode() == X86ISD::TAILCALL) {
815 SDOperand TailCall = Chain;
816 SDOperand TargetAddress = TailCall.getOperand(1);
817 SDOperand StackAdjustment = TailCall.getOperand(2);
818 assert(((TargetAddress.getOpcode() == ISD::Register &&
819 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
820 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
821 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
822 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
823 "Expecting an global address, external symbol, or register");
824 assert(StackAdjustment.getOpcode() == ISD::Constant &&
825 "Expecting a const value");
827 SmallVector<SDOperand,8> Operands;
828 Operands.push_back(Chain.getOperand(0));
829 Operands.push_back(TargetAddress);
830 Operands.push_back(StackAdjustment);
831 // Copy registers used by the call. Last operand is a flag so it is not
833 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
834 Operands.push_back(Chain.getOperand(i));
836 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
843 SmallVector<SDOperand, 6> RetOps;
844 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
845 // Operand #1 = Bytes To Pop
846 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
848 // Copy the result values into the output registers.
849 for (unsigned i = 0; i != RVLocs.size(); ++i) {
850 CCValAssign &VA = RVLocs[i];
851 assert(VA.isRegLoc() && "Can only return in registers!");
852 SDOperand ValToCopy = Op.getOperand(i*2+1);
854 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
855 // the RET instruction and handled by the FP Stackifier.
856 if (RVLocs[i].getLocReg() == X86::ST0 ||
857 RVLocs[i].getLocReg() == X86::ST1) {
858 // If this is a copy from an xmm register to ST(0), use an FPExtend to
859 // change the value to the FP stack register class.
860 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
861 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
862 RetOps.push_back(ValToCopy);
863 // Don't emit a copytoreg.
867 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
868 Flag = Chain.getValue(1);
871 // The x86-64 ABI for returning structs by value requires that we copy
872 // the sret argument into %rax for the return. We saved the argument into
873 // a virtual register in the entry block, so now we copy the value out
875 if (Subtarget->is64Bit() &&
876 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
877 MachineFunction &MF = DAG.getMachineFunction();
878 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
879 unsigned Reg = FuncInfo->getSRetReturnReg();
881 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
882 FuncInfo->setSRetReturnReg(Reg);
884 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
886 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
887 Flag = Chain.getValue(1);
890 RetOps[0] = Chain; // Update chain.
892 // Add the flag if we have it.
894 RetOps.push_back(Flag);
896 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
900 /// LowerCallResult - Lower the result values of an ISD::CALL into the
901 /// appropriate copies out of appropriate physical registers. This assumes that
902 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
903 /// being lowered. The returns a SDNode with the same number of values as the
905 SDNode *X86TargetLowering::
906 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
907 unsigned CallingConv, SelectionDAG &DAG) {
909 // Assign locations to each value returned by this call.
910 SmallVector<CCValAssign, 16> RVLocs;
911 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
912 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
913 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
915 SmallVector<SDOperand, 8> ResultVals;
917 // Copy all of the result registers out of their specified physreg.
918 for (unsigned i = 0; i != RVLocs.size(); ++i) {
919 MVT::ValueType CopyVT = RVLocs[i].getValVT();
921 // If this is a call to a function that returns an fp value on the floating
922 // point stack, but where we prefer to use the value in xmm registers, copy
923 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
924 if (RVLocs[i].getLocReg() == X86::ST0 &&
925 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
929 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
930 CopyVT, InFlag).getValue(1);
931 SDOperand Val = Chain.getValue(0);
932 InFlag = Chain.getValue(2);
934 if (CopyVT != RVLocs[i].getValVT()) {
935 // Round the F80 the right size, which also moves to the appropriate xmm
937 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
938 // This truncation won't change the value.
939 DAG.getIntPtrConstant(1));
942 ResultVals.push_back(Val);
945 // Merge everything together with a MERGE_VALUES node.
946 ResultVals.push_back(Chain);
947 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
948 &ResultVals[0], ResultVals.size()).Val;
952 //===----------------------------------------------------------------------===//
953 // C & StdCall & Fast Calling Convention implementation
954 //===----------------------------------------------------------------------===//
955 // StdCall calling convention seems to be standard for many Windows' API
956 // routines and around. It differs from C calling convention just a little:
957 // callee should clean up the stack, not caller. Symbols should be also
958 // decorated in some fancy way :) It doesn't support any vector arguments.
959 // For info on fast calling convention see Fast Calling Convention (tail call)
960 // implementation LowerX86_32FastCCCallTo.
962 /// AddLiveIn - This helper function adds the specified physical register to the
963 /// MachineFunction as a live in value. It also creates a corresponding virtual
965 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
966 const TargetRegisterClass *RC) {
967 assert(RC->contains(PReg) && "Not the correct regclass!");
968 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
969 MF.getRegInfo().addLiveIn(PReg, VReg);
973 /// CallIsStructReturn - Determines whether a CALL node uses struct return
975 static bool CallIsStructReturn(SDOperand Op) {
976 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
980 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
983 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
984 /// return semantics.
985 static bool ArgsAreStructReturn(SDOperand Op) {
986 unsigned NumArgs = Op.Val->getNumValues() - 1;
990 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
993 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
994 /// the callee to pop its own arguments. Callee pop is necessary to support tail
996 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
997 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1001 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1004 case CallingConv::X86_StdCall:
1005 return !Subtarget->is64Bit();
1006 case CallingConv::X86_FastCall:
1007 return !Subtarget->is64Bit();
1008 case CallingConv::Fast:
1009 return PerformTailCallOpt;
1013 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1014 /// FORMAL_ARGUMENTS node.
1015 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1016 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1018 if (Subtarget->is64Bit()) {
1019 if (Subtarget->isTargetWin64())
1020 return CC_X86_Win64_C;
1022 if (CC == CallingConv::Fast && PerformTailCallOpt)
1023 return CC_X86_64_TailCall;
1029 if (CC == CallingConv::X86_FastCall)
1030 return CC_X86_32_FastCall;
1031 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1032 return CC_X86_32_TailCall;
1037 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1038 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1040 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1041 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1042 if (CC == CallingConv::X86_FastCall)
1044 else if (CC == CallingConv::X86_StdCall)
1050 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1051 /// in a register before calling.
1052 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1053 return !IsTailCall && !Is64Bit &&
1054 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1055 Subtarget->isPICStyleGOT();
1058 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1059 /// address to be loaded in a register.
1061 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1062 return !Is64Bit && IsTailCall &&
1063 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1064 Subtarget->isPICStyleGOT();
1067 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1068 /// by "Src" to address "Dst" with size and alignment information specified by
1069 /// the specific parameter attribute. The copy will be passed as a byval
1070 /// function parameter.
1072 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1073 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1074 SDOperand SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1075 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1076 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1079 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1080 const CCValAssign &VA,
1081 MachineFrameInfo *MFI,
1083 SDOperand Root, unsigned i) {
1084 // Create the nodes corresponding to a load from this parameter slot.
1085 ISD::ArgFlagsTy Flags =
1086 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1087 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1088 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1090 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1091 // changed with more analysis.
1092 // In case of tail call optimization mark all arguments mutable. Since they
1093 // could be overwritten by lowering of arguments in case of a tail call.
1094 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1095 VA.getLocMemOffset(), isImmutable);
1096 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1097 if (Flags.isByVal())
1099 return DAG.getLoad(VA.getValVT(), Root, FIN,
1100 PseudoSourceValue::getFixedStack(), FI);
1104 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1105 MachineFunction &MF = DAG.getMachineFunction();
1106 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1108 const Function* Fn = MF.getFunction();
1109 if (Fn->hasExternalLinkage() &&
1110 Subtarget->isTargetCygMing() &&
1111 Fn->getName() == "main")
1112 FuncInfo->setForceFramePointer(true);
1114 // Decorate the function name.
1115 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1117 MachineFrameInfo *MFI = MF.getFrameInfo();
1118 SDOperand Root = Op.getOperand(0);
1119 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1120 unsigned CC = MF.getFunction()->getCallingConv();
1121 bool Is64Bit = Subtarget->is64Bit();
1122 bool IsWin64 = Subtarget->isTargetWin64();
1124 assert(!(isVarArg && CC == CallingConv::Fast) &&
1125 "Var args not supported with calling convention fastcc");
1127 // Assign locations to all of the incoming arguments.
1128 SmallVector<CCValAssign, 16> ArgLocs;
1129 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1130 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1132 SmallVector<SDOperand, 8> ArgValues;
1133 unsigned LastVal = ~0U;
1134 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1135 CCValAssign &VA = ArgLocs[i];
1136 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1138 assert(VA.getValNo() != LastVal &&
1139 "Don't support value assigned to multiple locs yet");
1140 LastVal = VA.getValNo();
1142 if (VA.isRegLoc()) {
1143 MVT::ValueType RegVT = VA.getLocVT();
1144 TargetRegisterClass *RC;
1145 if (RegVT == MVT::i32)
1146 RC = X86::GR32RegisterClass;
1147 else if (Is64Bit && RegVT == MVT::i64)
1148 RC = X86::GR64RegisterClass;
1149 else if (RegVT == MVT::f32)
1150 RC = X86::FR32RegisterClass;
1151 else if (RegVT == MVT::f64)
1152 RC = X86::FR64RegisterClass;
1153 else if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 128)
1154 RC = X86::VR128RegisterClass;
1155 else if (MVT::isVector(RegVT)) {
1156 assert(MVT::getSizeInBits(RegVT) == 64);
1158 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1160 // Darwin calling convention passes MMX values in either GPRs or
1161 // XMMs in x86-64. Other targets pass them in memory.
1162 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1163 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1166 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1171 assert(0 && "Unknown argument type!");
1174 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1175 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1177 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1178 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1180 if (VA.getLocInfo() == CCValAssign::SExt)
1181 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1182 DAG.getValueType(VA.getValVT()));
1183 else if (VA.getLocInfo() == CCValAssign::ZExt)
1184 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1185 DAG.getValueType(VA.getValVT()));
1187 if (VA.getLocInfo() != CCValAssign::Full)
1188 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1190 // Handle MMX values passed in GPRs.
1191 if (Is64Bit && RegVT != VA.getLocVT()) {
1192 if (MVT::getSizeInBits(RegVT) == 64 && RC == X86::GR64RegisterClass)
1193 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1194 else if (RC == X86::VR128RegisterClass) {
1195 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1196 DAG.getConstant(0, MVT::i64));
1197 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1201 ArgValues.push_back(ArgValue);
1203 assert(VA.isMemLoc());
1204 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1208 // The x86-64 ABI for returning structs by value requires that we copy
1209 // the sret argument into %rax for the return. Save the argument into
1210 // a virtual register so that we can access it from the return points.
1211 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1212 MachineFunction &MF = DAG.getMachineFunction();
1213 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1214 unsigned Reg = FuncInfo->getSRetReturnReg();
1216 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1217 FuncInfo->setSRetReturnReg(Reg);
1219 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1220 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1223 unsigned StackSize = CCInfo.getNextStackOffset();
1224 // align stack specially for tail calls
1225 if (CC == CallingConv::Fast)
1226 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1228 // If the function takes variable number of arguments, make a frame index for
1229 // the start of the first vararg value... for expansion of llvm.va_start.
1231 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1232 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1235 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1237 // FIXME: We should really autogenerate these arrays
1238 static const unsigned GPR64ArgRegsWin64[] = {
1239 X86::RCX, X86::RDX, X86::R8, X86::R9
1241 static const unsigned XMMArgRegsWin64[] = {
1242 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1244 static const unsigned GPR64ArgRegs64Bit[] = {
1245 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1247 static const unsigned XMMArgRegs64Bit[] = {
1248 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1249 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1251 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1254 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1255 GPR64ArgRegs = GPR64ArgRegsWin64;
1256 XMMArgRegs = XMMArgRegsWin64;
1258 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1259 GPR64ArgRegs = GPR64ArgRegs64Bit;
1260 XMMArgRegs = XMMArgRegs64Bit;
1262 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1264 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1267 // For X86-64, if there are vararg parameters that are passed via
1268 // registers, then we must store them to their spots on the stack so they
1269 // may be loaded by deferencing the result of va_next.
1270 VarArgsGPOffset = NumIntRegs * 8;
1271 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1272 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1273 TotalNumXMMRegs * 16, 16);
1275 // Store the integer parameter registers.
1276 SmallVector<SDOperand, 8> MemOps;
1277 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1278 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1279 DAG.getIntPtrConstant(VarArgsGPOffset));
1280 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1281 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1282 X86::GR64RegisterClass);
1283 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1285 DAG.getStore(Val.getValue(1), Val, FIN,
1286 PseudoSourceValue::getFixedStack(),
1288 MemOps.push_back(Store);
1289 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1290 DAG.getIntPtrConstant(8));
1293 // Now store the XMM (fp + vector) parameter registers.
1294 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1295 DAG.getIntPtrConstant(VarArgsFPOffset));
1296 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1297 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1298 X86::VR128RegisterClass);
1299 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1301 DAG.getStore(Val.getValue(1), Val, FIN,
1302 PseudoSourceValue::getFixedStack(),
1304 MemOps.push_back(Store);
1305 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1306 DAG.getIntPtrConstant(16));
1308 if (!MemOps.empty())
1309 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1310 &MemOps[0], MemOps.size());
1314 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1315 // arguments and the arguments after the retaddr has been pushed are
1317 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1318 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1319 (StackSize & 7) == 0)
1322 ArgValues.push_back(Root);
1324 // Some CCs need callee pop.
1325 if (IsCalleePop(Op)) {
1326 BytesToPopOnReturn = StackSize; // Callee pops everything.
1327 BytesCallerReserves = 0;
1329 BytesToPopOnReturn = 0; // Callee pops nothing.
1330 // If this is an sret function, the return should pop the hidden pointer.
1331 if (!Is64Bit && ArgsAreStructReturn(Op))
1332 BytesToPopOnReturn = 4;
1333 BytesCallerReserves = StackSize;
1337 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1338 if (CC == CallingConv::X86_FastCall)
1339 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1342 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1344 // Return the new list of results.
1345 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1346 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1350 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1351 const SDOperand &StackPtr,
1352 const CCValAssign &VA,
1355 unsigned LocMemOffset = VA.getLocMemOffset();
1356 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1357 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1358 ISD::ArgFlagsTy Flags =
1359 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1360 if (Flags.isByVal()) {
1361 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1363 return DAG.getStore(Chain, Arg, PtrOff,
1364 PseudoSourceValue::getStack(), LocMemOffset);
1367 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1368 /// optimization is performed and it is required.
1370 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1371 SDOperand &OutRetAddr,
1376 if (!IsTailCall || FPDiff==0) return Chain;
1378 // Adjust the Return address stack slot.
1379 MVT::ValueType VT = getPointerTy();
1380 OutRetAddr = getReturnAddressFrameIndex(DAG);
1381 // Load the "old" Return address.
1382 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1383 return SDOperand(OutRetAddr.Val, 1);
1386 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1387 /// optimization is performed and it is required (FPDiff!=0).
1389 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1390 SDOperand Chain, SDOperand RetAddrFrIdx,
1391 bool Is64Bit, int FPDiff) {
1392 // Store the return address to the appropriate stack slot.
1393 if (!FPDiff) return Chain;
1394 // Calculate the new stack slot for the return address.
1395 int SlotSize = Is64Bit ? 8 : 4;
1396 int NewReturnAddrFI =
1397 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1398 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1399 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1400 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1401 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1405 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1406 MachineFunction &MF = DAG.getMachineFunction();
1407 SDOperand Chain = Op.getOperand(0);
1408 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1409 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1410 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1411 && CC == CallingConv::Fast && PerformTailCallOpt;
1412 SDOperand Callee = Op.getOperand(4);
1413 bool Is64Bit = Subtarget->is64Bit();
1414 bool IsStructRet = CallIsStructReturn(Op);
1416 assert(!(isVarArg && CC == CallingConv::Fast) &&
1417 "Var args not supported with calling convention fastcc");
1419 // Analyze operands of the call, assigning locations to each operand.
1420 SmallVector<CCValAssign, 16> ArgLocs;
1421 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1422 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1424 // Get a count of how many bytes are to be pushed on the stack.
1425 unsigned NumBytes = CCInfo.getNextStackOffset();
1426 if (CC == CallingConv::Fast)
1427 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1429 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1430 // arguments and the arguments after the retaddr has been pushed are aligned.
1431 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1432 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1433 (NumBytes & 7) == 0)
1438 // Lower arguments at fp - stackoffset + fpdiff.
1439 unsigned NumBytesCallerPushed =
1440 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1441 FPDiff = NumBytesCallerPushed - NumBytes;
1443 // Set the delta of movement of the returnaddr stackslot.
1444 // But only set if delta is greater than previous delta.
1445 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1446 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1449 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1451 SDOperand RetAddrFrIdx;
1452 // Load return adress for tail calls.
1453 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1456 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1457 SmallVector<SDOperand, 8> MemOpChains;
1460 // Walk the register/memloc assignments, inserting copies/loads. In the case
1461 // of tail call optimization arguments are handle later.
1462 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1463 CCValAssign &VA = ArgLocs[i];
1464 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1465 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1466 getArgFlags().isByVal();
1468 // Promote the value if needed.
1469 switch (VA.getLocInfo()) {
1470 default: assert(0 && "Unknown loc info!");
1471 case CCValAssign::Full: break;
1472 case CCValAssign::SExt:
1473 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1475 case CCValAssign::ZExt:
1476 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1478 case CCValAssign::AExt:
1479 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1483 if (VA.isRegLoc()) {
1485 MVT::ValueType RegVT = VA.getLocVT();
1486 if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 64)
1487 switch (VA.getLocReg()) {
1490 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1492 // Special case: passing MMX values in GPR registers.
1493 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1496 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1497 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1498 // Special case: passing MMX values in XMM registers.
1499 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1500 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1501 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1502 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1503 getMOVLMask(2, DAG));
1508 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1510 if (!IsTailCall || (IsTailCall && isByVal)) {
1511 assert(VA.isMemLoc());
1512 if (StackPtr.Val == 0)
1513 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1515 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1521 if (!MemOpChains.empty())
1522 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1523 &MemOpChains[0], MemOpChains.size());
1525 // Build a sequence of copy-to-reg nodes chained together with token chain
1526 // and flag operands which copy the outgoing args into registers.
1528 // Tail call byval lowering might overwrite argument registers so in case of
1529 // tail call optimization the copies to registers are lowered later.
1531 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1532 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1534 InFlag = Chain.getValue(1);
1537 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1539 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1540 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1541 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1543 InFlag = Chain.getValue(1);
1545 // If we are tail calling and generating PIC/GOT style code load the address
1546 // of the callee into ecx. The value in ecx is used as target of the tail
1547 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1548 // calls on PIC/GOT architectures. Normally we would just put the address of
1549 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1550 // restored (since ebx is callee saved) before jumping to the target@PLT.
1551 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1552 // Note: The actual moving to ecx is done further down.
1553 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1554 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1555 !G->getGlobal()->hasProtectedVisibility())
1556 Callee = LowerGlobalAddress(Callee, DAG);
1557 else if (isa<ExternalSymbolSDNode>(Callee))
1558 Callee = LowerExternalSymbol(Callee,DAG);
1561 if (Is64Bit && isVarArg) {
1562 // From AMD64 ABI document:
1563 // For calls that may call functions that use varargs or stdargs
1564 // (prototype-less calls or calls to functions containing ellipsis (...) in
1565 // the declaration) %al is used as hidden argument to specify the number
1566 // of SSE registers used. The contents of %al do not need to match exactly
1567 // the number of registers, but must be an ubound on the number of SSE
1568 // registers used and is in the range 0 - 8 inclusive.
1570 // FIXME: Verify this on Win64
1571 // Count the number of XMM registers allocated.
1572 static const unsigned XMMArgRegs[] = {
1573 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1574 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1576 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1578 Chain = DAG.getCopyToReg(Chain, X86::AL,
1579 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1580 InFlag = Chain.getValue(1);
1584 // For tail calls lower the arguments to the 'real' stack slot.
1586 SmallVector<SDOperand, 8> MemOpChains2;
1589 // Do not flag preceeding copytoreg stuff together with the following stuff.
1590 InFlag = SDOperand();
1591 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1592 CCValAssign &VA = ArgLocs[i];
1593 if (!VA.isRegLoc()) {
1594 assert(VA.isMemLoc());
1595 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1596 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1597 ISD::ArgFlagsTy Flags =
1598 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1599 // Create frame index.
1600 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1601 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1602 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1603 FIN = DAG.getFrameIndex(FI, getPointerTy());
1605 if (Flags.isByVal()) {
1606 // Copy relative to framepointer.
1607 SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1608 if (StackPtr.Val == 0)
1609 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1610 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1612 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1615 // Store relative to framepointer.
1616 MemOpChains2.push_back(
1617 DAG.getStore(Chain, Arg, FIN,
1618 PseudoSourceValue::getFixedStack(), FI));
1623 if (!MemOpChains2.empty())
1624 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1625 &MemOpChains2[0], MemOpChains2.size());
1627 // Copy arguments to their registers.
1628 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1629 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1631 InFlag = Chain.getValue(1);
1633 InFlag =SDOperand();
1635 // Store the return address to the appropriate stack slot.
1636 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1640 // If the callee is a GlobalAddress node (quite common, every direct call is)
1641 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1642 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1643 // We should use extra load for direct calls to dllimported functions in
1645 if ((IsTailCall || !Is64Bit ||
1646 getTargetMachine().getCodeModel() != CodeModel::Large)
1647 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1648 getTargetMachine(), true))
1649 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1650 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1651 if (IsTailCall || !Is64Bit ||
1652 getTargetMachine().getCodeModel() != CodeModel::Large)
1653 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1654 } else if (IsTailCall) {
1655 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1657 Chain = DAG.getCopyToReg(Chain,
1658 DAG.getRegister(Opc, getPointerTy()),
1660 Callee = DAG.getRegister(Opc, getPointerTy());
1661 // Add register as live out.
1662 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1665 // Returns a chain & a flag for retval copy to use.
1666 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1667 SmallVector<SDOperand, 8> Ops;
1670 Ops.push_back(Chain);
1671 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1672 Ops.push_back(DAG.getIntPtrConstant(0));
1674 Ops.push_back(InFlag);
1675 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1676 InFlag = Chain.getValue(1);
1678 // Returns a chain & a flag for retval copy to use.
1679 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1683 Ops.push_back(Chain);
1684 Ops.push_back(Callee);
1687 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1689 // Add argument registers to the end of the list so that they are known live
1691 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1692 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1693 RegsToPass[i].second.getValueType()));
1695 // Add an implicit use GOT pointer in EBX.
1696 if (!IsTailCall && !Is64Bit &&
1697 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1698 Subtarget->isPICStyleGOT())
1699 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1701 // Add an implicit use of AL for x86 vararg functions.
1702 if (Is64Bit && isVarArg)
1703 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1706 Ops.push_back(InFlag);
1709 assert(InFlag.Val &&
1710 "Flag must be set. Depend on flag being set in LowerRET");
1711 Chain = DAG.getNode(X86ISD::TAILCALL,
1712 Op.Val->getVTList(), &Ops[0], Ops.size());
1714 return SDOperand(Chain.Val, Op.ResNo);
1717 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1718 InFlag = Chain.getValue(1);
1720 // Create the CALLSEQ_END node.
1721 unsigned NumBytesForCalleeToPush;
1722 if (IsCalleePop(Op))
1723 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1724 else if (!Is64Bit && IsStructRet)
1725 // If this is is a call to a struct-return function, the callee
1726 // pops the hidden struct pointer, so we have to push it back.
1727 // This is common for Darwin/X86, Linux & Mingw32 targets.
1728 NumBytesForCalleeToPush = 4;
1730 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1732 // Returns a flag for retval copy to use.
1733 Chain = DAG.getCALLSEQ_END(Chain,
1734 DAG.getIntPtrConstant(NumBytes),
1735 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1737 InFlag = Chain.getValue(1);
1739 // Handle result values, copying them out of physregs into vregs that we
1741 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1745 //===----------------------------------------------------------------------===//
1746 // Fast Calling Convention (tail call) implementation
1747 //===----------------------------------------------------------------------===//
1749 // Like std call, callee cleans arguments, convention except that ECX is
1750 // reserved for storing the tail called function address. Only 2 registers are
1751 // free for argument passing (inreg). Tail call optimization is performed
1753 // * tailcallopt is enabled
1754 // * caller/callee are fastcc
1755 // On X86_64 architecture with GOT-style position independent code only local
1756 // (within module) calls are supported at the moment.
1757 // To keep the stack aligned according to platform abi the function
1758 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1759 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1760 // If a tail called function callee has more arguments than the caller the
1761 // caller needs to make sure that there is room to move the RETADDR to. This is
1762 // achieved by reserving an area the size of the argument delta right after the
1763 // original REtADDR, but before the saved framepointer or the spilled registers
1764 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1776 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1777 /// for a 16 byte align requirement.
1778 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1779 SelectionDAG& DAG) {
1780 if (PerformTailCallOpt) {
1781 MachineFunction &MF = DAG.getMachineFunction();
1782 const TargetMachine &TM = MF.getTarget();
1783 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1784 unsigned StackAlignment = TFI.getStackAlignment();
1785 uint64_t AlignMask = StackAlignment - 1;
1786 int64_t Offset = StackSize;
1787 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1788 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1789 // Number smaller than 12 so just add the difference.
1790 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1792 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1793 Offset = ((~AlignMask) & Offset) + StackAlignment +
1794 (StackAlignment-SlotSize);
1801 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1802 /// following the call is a return. A function is eligible if caller/callee
1803 /// calling conventions match, currently only fastcc supports tail calls, and
1804 /// the function CALL is immediatly followed by a RET.
1805 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1807 SelectionDAG& DAG) const {
1808 if (!PerformTailCallOpt)
1811 if (CheckTailCallReturnConstraints(Call, Ret)) {
1812 MachineFunction &MF = DAG.getMachineFunction();
1813 unsigned CallerCC = MF.getFunction()->getCallingConv();
1814 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1815 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1816 SDOperand Callee = Call.getOperand(4);
1817 // On x86/32Bit PIC/GOT tail calls are supported.
1818 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1819 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1822 // Can only do local tail calls (in same module, hidden or protected) on
1823 // x86_64 PIC/GOT at the moment.
1824 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1825 return G->getGlobal()->hasHiddenVisibility()
1826 || G->getGlobal()->hasProtectedVisibility();
1833 //===----------------------------------------------------------------------===//
1834 // Other Lowering Hooks
1835 //===----------------------------------------------------------------------===//
1838 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1839 MachineFunction &MF = DAG.getMachineFunction();
1840 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1841 int ReturnAddrIndex = FuncInfo->getRAIndex();
1843 if (ReturnAddrIndex == 0) {
1844 // Set up a frame object for the return address.
1845 if (Subtarget->is64Bit())
1846 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1848 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1850 FuncInfo->setRAIndex(ReturnAddrIndex);
1853 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1858 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1859 /// specific condition code. It returns a false if it cannot do a direct
1860 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1862 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1863 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1864 SelectionDAG &DAG) {
1865 X86CC = X86::COND_INVALID;
1867 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1868 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1869 // X > -1 -> X == 0, jump !sign.
1870 RHS = DAG.getConstant(0, RHS.getValueType());
1871 X86CC = X86::COND_NS;
1873 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1874 // X < 0 -> X == 0, jump on sign.
1875 X86CC = X86::COND_S;
1877 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1879 RHS = DAG.getConstant(0, RHS.getValueType());
1880 X86CC = X86::COND_LE;
1885 switch (SetCCOpcode) {
1887 case ISD::SETEQ: X86CC = X86::COND_E; break;
1888 case ISD::SETGT: X86CC = X86::COND_G; break;
1889 case ISD::SETGE: X86CC = X86::COND_GE; break;
1890 case ISD::SETLT: X86CC = X86::COND_L; break;
1891 case ISD::SETLE: X86CC = X86::COND_LE; break;
1892 case ISD::SETNE: X86CC = X86::COND_NE; break;
1893 case ISD::SETULT: X86CC = X86::COND_B; break;
1894 case ISD::SETUGT: X86CC = X86::COND_A; break;
1895 case ISD::SETULE: X86CC = X86::COND_BE; break;
1896 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1899 // On a floating point condition, the flags are set as follows:
1901 // 0 | 0 | 0 | X > Y
1902 // 0 | 0 | 1 | X < Y
1903 // 1 | 0 | 0 | X == Y
1904 // 1 | 1 | 1 | unordered
1906 switch (SetCCOpcode) {
1909 case ISD::SETEQ: X86CC = X86::COND_E; break;
1910 case ISD::SETOLT: Flip = true; // Fallthrough
1912 case ISD::SETGT: X86CC = X86::COND_A; break;
1913 case ISD::SETOLE: Flip = true; // Fallthrough
1915 case ISD::SETGE: X86CC = X86::COND_AE; break;
1916 case ISD::SETUGT: Flip = true; // Fallthrough
1918 case ISD::SETLT: X86CC = X86::COND_B; break;
1919 case ISD::SETUGE: Flip = true; // Fallthrough
1921 case ISD::SETLE: X86CC = X86::COND_BE; break;
1923 case ISD::SETNE: X86CC = X86::COND_NE; break;
1924 case ISD::SETUO: X86CC = X86::COND_P; break;
1925 case ISD::SETO: X86CC = X86::COND_NP; break;
1928 std::swap(LHS, RHS);
1931 return X86CC != X86::COND_INVALID;
1934 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1935 /// code. Current x86 isa includes the following FP cmov instructions:
1936 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1937 static bool hasFPCMov(unsigned X86CC) {
1953 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1954 /// true if Op is undef or if its value falls within the specified range (L, H].
1955 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1956 if (Op.getOpcode() == ISD::UNDEF)
1959 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1960 return (Val >= Low && Val < Hi);
1963 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1964 /// true if Op is undef or if its value equal to the specified value.
1965 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1966 if (Op.getOpcode() == ISD::UNDEF)
1968 return cast<ConstantSDNode>(Op)->getValue() == Val;
1971 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1972 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1973 bool X86::isPSHUFDMask(SDNode *N) {
1974 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1976 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1979 // Check if the value doesn't reference the second vector.
1980 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1981 SDOperand Arg = N->getOperand(i);
1982 if (Arg.getOpcode() == ISD::UNDEF) continue;
1983 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1984 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1991 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1992 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1993 bool X86::isPSHUFHWMask(SDNode *N) {
1994 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1996 if (N->getNumOperands() != 8)
1999 // Lower quadword copied in order.
2000 for (unsigned i = 0; i != 4; ++i) {
2001 SDOperand Arg = N->getOperand(i);
2002 if (Arg.getOpcode() == ISD::UNDEF) continue;
2003 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2004 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2008 // Upper quadword shuffled.
2009 for (unsigned i = 4; i != 8; ++i) {
2010 SDOperand Arg = N->getOperand(i);
2011 if (Arg.getOpcode() == ISD::UNDEF) continue;
2012 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2013 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2014 if (Val < 4 || Val > 7)
2021 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2022 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2023 bool X86::isPSHUFLWMask(SDNode *N) {
2024 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2026 if (N->getNumOperands() != 8)
2029 // Upper quadword copied in order.
2030 for (unsigned i = 4; i != 8; ++i)
2031 if (!isUndefOrEqual(N->getOperand(i), i))
2034 // Lower quadword shuffled.
2035 for (unsigned i = 0; i != 4; ++i)
2036 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2042 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2043 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2044 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2045 if (NumElems != 2 && NumElems != 4) return false;
2047 unsigned Half = NumElems / 2;
2048 for (unsigned i = 0; i < Half; ++i)
2049 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2051 for (unsigned i = Half; i < NumElems; ++i)
2052 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2058 bool X86::isSHUFPMask(SDNode *N) {
2059 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2060 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2063 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2064 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2065 /// half elements to come from vector 1 (which would equal the dest.) and
2066 /// the upper half to come from vector 2.
2067 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2068 if (NumOps != 2 && NumOps != 4) return false;
2070 unsigned Half = NumOps / 2;
2071 for (unsigned i = 0; i < Half; ++i)
2072 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2074 for (unsigned i = Half; i < NumOps; ++i)
2075 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2080 static bool isCommutedSHUFP(SDNode *N) {
2081 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2082 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2085 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2086 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2087 bool X86::isMOVHLPSMask(SDNode *N) {
2088 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2090 if (N->getNumOperands() != 4)
2093 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2094 return isUndefOrEqual(N->getOperand(0), 6) &&
2095 isUndefOrEqual(N->getOperand(1), 7) &&
2096 isUndefOrEqual(N->getOperand(2), 2) &&
2097 isUndefOrEqual(N->getOperand(3), 3);
2100 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2101 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2103 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2104 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2106 if (N->getNumOperands() != 4)
2109 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2110 return isUndefOrEqual(N->getOperand(0), 2) &&
2111 isUndefOrEqual(N->getOperand(1), 3) &&
2112 isUndefOrEqual(N->getOperand(2), 2) &&
2113 isUndefOrEqual(N->getOperand(3), 3);
2116 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2117 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2118 bool X86::isMOVLPMask(SDNode *N) {
2119 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2121 unsigned NumElems = N->getNumOperands();
2122 if (NumElems != 2 && NumElems != 4)
2125 for (unsigned i = 0; i < NumElems/2; ++i)
2126 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2129 for (unsigned i = NumElems/2; i < NumElems; ++i)
2130 if (!isUndefOrEqual(N->getOperand(i), i))
2136 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2137 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2139 bool X86::isMOVHPMask(SDNode *N) {
2140 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2142 unsigned NumElems = N->getNumOperands();
2143 if (NumElems != 2 && NumElems != 4)
2146 for (unsigned i = 0; i < NumElems/2; ++i)
2147 if (!isUndefOrEqual(N->getOperand(i), i))
2150 for (unsigned i = 0; i < NumElems/2; ++i) {
2151 SDOperand Arg = N->getOperand(i + NumElems/2);
2152 if (!isUndefOrEqual(Arg, i + NumElems))
2159 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2160 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2161 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2162 bool V2IsSplat = false) {
2163 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2166 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2167 SDOperand BitI = Elts[i];
2168 SDOperand BitI1 = Elts[i+1];
2169 if (!isUndefOrEqual(BitI, j))
2172 if (isUndefOrEqual(BitI1, NumElts))
2175 if (!isUndefOrEqual(BitI1, j + NumElts))
2183 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2184 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2185 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2188 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2189 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2190 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2191 bool V2IsSplat = false) {
2192 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2195 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2196 SDOperand BitI = Elts[i];
2197 SDOperand BitI1 = Elts[i+1];
2198 if (!isUndefOrEqual(BitI, j + NumElts/2))
2201 if (isUndefOrEqual(BitI1, NumElts))
2204 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2212 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2213 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2214 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2217 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2218 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2220 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2221 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2223 unsigned NumElems = N->getNumOperands();
2224 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2227 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2228 SDOperand BitI = N->getOperand(i);
2229 SDOperand BitI1 = N->getOperand(i+1);
2231 if (!isUndefOrEqual(BitI, j))
2233 if (!isUndefOrEqual(BitI1, j))
2240 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2241 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2243 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2244 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2246 unsigned NumElems = N->getNumOperands();
2247 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2250 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2251 SDOperand BitI = N->getOperand(i);
2252 SDOperand BitI1 = N->getOperand(i + 1);
2254 if (!isUndefOrEqual(BitI, j))
2256 if (!isUndefOrEqual(BitI1, j))
2263 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2264 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2265 /// MOVSD, and MOVD, i.e. setting the lowest element.
2266 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2267 if (NumElts != 2 && NumElts != 4)
2270 if (!isUndefOrEqual(Elts[0], NumElts))
2273 for (unsigned i = 1; i < NumElts; ++i) {
2274 if (!isUndefOrEqual(Elts[i], i))
2281 bool X86::isMOVLMask(SDNode *N) {
2282 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2283 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2286 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2287 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2288 /// element of vector 2 and the other elements to come from vector 1 in order.
2289 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2290 bool V2IsSplat = false,
2291 bool V2IsUndef = false) {
2292 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2295 if (!isUndefOrEqual(Ops[0], 0))
2298 for (unsigned i = 1; i < NumOps; ++i) {
2299 SDOperand Arg = Ops[i];
2300 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2301 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2302 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2309 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2310 bool V2IsUndef = false) {
2311 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2312 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2313 V2IsSplat, V2IsUndef);
2316 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2317 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2318 bool X86::isMOVSHDUPMask(SDNode *N) {
2319 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2321 if (N->getNumOperands() != 4)
2324 // Expect 1, 1, 3, 3
2325 for (unsigned i = 0; i < 2; ++i) {
2326 SDOperand Arg = N->getOperand(i);
2327 if (Arg.getOpcode() == ISD::UNDEF) continue;
2328 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2329 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2330 if (Val != 1) return false;
2334 for (unsigned i = 2; i < 4; ++i) {
2335 SDOperand Arg = N->getOperand(i);
2336 if (Arg.getOpcode() == ISD::UNDEF) continue;
2337 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2338 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2339 if (Val != 3) return false;
2343 // Don't use movshdup if it can be done with a shufps.
2347 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2348 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2349 bool X86::isMOVSLDUPMask(SDNode *N) {
2350 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2352 if (N->getNumOperands() != 4)
2355 // Expect 0, 0, 2, 2
2356 for (unsigned i = 0; i < 2; ++i) {
2357 SDOperand Arg = N->getOperand(i);
2358 if (Arg.getOpcode() == ISD::UNDEF) continue;
2359 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2360 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2361 if (Val != 0) return false;
2365 for (unsigned i = 2; i < 4; ++i) {
2366 SDOperand Arg = N->getOperand(i);
2367 if (Arg.getOpcode() == ISD::UNDEF) continue;
2368 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2369 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2370 if (Val != 2) return false;
2374 // Don't use movshdup if it can be done with a shufps.
2378 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2379 /// specifies a identity operation on the LHS or RHS.
2380 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2381 unsigned NumElems = N->getNumOperands();
2382 for (unsigned i = 0; i < NumElems; ++i)
2383 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2388 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2389 /// a splat of a single element.
2390 static bool isSplatMask(SDNode *N) {
2391 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2393 // This is a splat operation if each element of the permute is the same, and
2394 // if the value doesn't reference the second vector.
2395 unsigned NumElems = N->getNumOperands();
2396 SDOperand ElementBase;
2398 for (; i != NumElems; ++i) {
2399 SDOperand Elt = N->getOperand(i);
2400 if (isa<ConstantSDNode>(Elt)) {
2406 if (!ElementBase.Val)
2409 for (; i != NumElems; ++i) {
2410 SDOperand Arg = N->getOperand(i);
2411 if (Arg.getOpcode() == ISD::UNDEF) continue;
2412 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2413 if (Arg != ElementBase) return false;
2416 // Make sure it is a splat of the first vector operand.
2417 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2420 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2421 /// a splat of a single element and it's a 2 or 4 element mask.
2422 bool X86::isSplatMask(SDNode *N) {
2423 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2425 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2426 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2428 return ::isSplatMask(N);
2431 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2432 /// specifies a splat of zero element.
2433 bool X86::isSplatLoMask(SDNode *N) {
2434 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2436 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2437 if (!isUndefOrEqual(N->getOperand(i), 0))
2442 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2443 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2445 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2446 unsigned NumOperands = N->getNumOperands();
2447 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2449 for (unsigned i = 0; i < NumOperands; ++i) {
2451 SDOperand Arg = N->getOperand(NumOperands-i-1);
2452 if (Arg.getOpcode() != ISD::UNDEF)
2453 Val = cast<ConstantSDNode>(Arg)->getValue();
2454 if (Val >= NumOperands) Val -= NumOperands;
2456 if (i != NumOperands - 1)
2463 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2464 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2466 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2468 // 8 nodes, but we only care about the last 4.
2469 for (unsigned i = 7; i >= 4; --i) {
2471 SDOperand Arg = N->getOperand(i);
2472 if (Arg.getOpcode() != ISD::UNDEF)
2473 Val = cast<ConstantSDNode>(Arg)->getValue();
2482 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2483 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2485 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2487 // 8 nodes, but we only care about the first 4.
2488 for (int i = 3; i >= 0; --i) {
2490 SDOperand Arg = N->getOperand(i);
2491 if (Arg.getOpcode() != ISD::UNDEF)
2492 Val = cast<ConstantSDNode>(Arg)->getValue();
2501 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2502 /// specifies a 8 element shuffle that can be broken into a pair of
2503 /// PSHUFHW and PSHUFLW.
2504 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2505 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2507 if (N->getNumOperands() != 8)
2510 // Lower quadword shuffled.
2511 for (unsigned i = 0; i != 4; ++i) {
2512 SDOperand Arg = N->getOperand(i);
2513 if (Arg.getOpcode() == ISD::UNDEF) continue;
2514 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2515 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2520 // Upper quadword shuffled.
2521 for (unsigned i = 4; i != 8; ++i) {
2522 SDOperand Arg = N->getOperand(i);
2523 if (Arg.getOpcode() == ISD::UNDEF) continue;
2524 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2525 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2526 if (Val < 4 || Val > 7)
2533 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2534 /// values in ther permute mask.
2535 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2536 SDOperand &V2, SDOperand &Mask,
2537 SelectionDAG &DAG) {
2538 MVT::ValueType VT = Op.getValueType();
2539 MVT::ValueType MaskVT = Mask.getValueType();
2540 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2541 unsigned NumElems = Mask.getNumOperands();
2542 SmallVector<SDOperand, 8> MaskVec;
2544 for (unsigned i = 0; i != NumElems; ++i) {
2545 SDOperand Arg = Mask.getOperand(i);
2546 if (Arg.getOpcode() == ISD::UNDEF) {
2547 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2550 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2551 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2553 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2555 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2559 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2560 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2563 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2564 /// the two vector operands have swapped position.
2566 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2567 MVT::ValueType MaskVT = Mask.getValueType();
2568 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2569 unsigned NumElems = Mask.getNumOperands();
2570 SmallVector<SDOperand, 8> MaskVec;
2571 for (unsigned i = 0; i != NumElems; ++i) {
2572 SDOperand Arg = Mask.getOperand(i);
2573 if (Arg.getOpcode() == ISD::UNDEF) {
2574 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2577 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2578 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2580 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2582 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2584 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2588 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2589 /// match movhlps. The lower half elements should come from upper half of
2590 /// V1 (and in order), and the upper half elements should come from the upper
2591 /// half of V2 (and in order).
2592 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2593 unsigned NumElems = Mask->getNumOperands();
2596 for (unsigned i = 0, e = 2; i != e; ++i)
2597 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2599 for (unsigned i = 2; i != 4; ++i)
2600 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2605 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2606 /// is promoted to a vector.
2607 static inline bool isScalarLoadToVector(SDNode *N) {
2608 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2609 N = N->getOperand(0).Val;
2610 return ISD::isNON_EXTLoad(N);
2615 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2616 /// match movlp{s|d}. The lower half elements should come from lower half of
2617 /// V1 (and in order), and the upper half elements should come from the upper
2618 /// half of V2 (and in order). And since V1 will become the source of the
2619 /// MOVLP, it must be either a vector load or a scalar load to vector.
2620 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2621 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2623 // Is V2 is a vector load, don't do this transformation. We will try to use
2624 // load folding shufps op.
2625 if (ISD::isNON_EXTLoad(V2))
2628 unsigned NumElems = Mask->getNumOperands();
2629 if (NumElems != 2 && NumElems != 4)
2631 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2632 if (!isUndefOrEqual(Mask->getOperand(i), i))
2634 for (unsigned i = NumElems/2; i != NumElems; ++i)
2635 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2640 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2642 static bool isSplatVector(SDNode *N) {
2643 if (N->getOpcode() != ISD::BUILD_VECTOR)
2646 SDOperand SplatValue = N->getOperand(0);
2647 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2648 if (N->getOperand(i) != SplatValue)
2653 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2655 static bool isUndefShuffle(SDNode *N) {
2656 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2659 SDOperand V1 = N->getOperand(0);
2660 SDOperand V2 = N->getOperand(1);
2661 SDOperand Mask = N->getOperand(2);
2662 unsigned NumElems = Mask.getNumOperands();
2663 for (unsigned i = 0; i != NumElems; ++i) {
2664 SDOperand Arg = Mask.getOperand(i);
2665 if (Arg.getOpcode() != ISD::UNDEF) {
2666 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2667 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2669 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2676 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2678 static inline bool isZeroNode(SDOperand Elt) {
2679 return ((isa<ConstantSDNode>(Elt) &&
2680 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2681 (isa<ConstantFPSDNode>(Elt) &&
2682 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2685 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2686 /// to an zero vector.
2687 static bool isZeroShuffle(SDNode *N) {
2688 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2691 SDOperand V1 = N->getOperand(0);
2692 SDOperand V2 = N->getOperand(1);
2693 SDOperand Mask = N->getOperand(2);
2694 unsigned NumElems = Mask.getNumOperands();
2695 for (unsigned i = 0; i != NumElems; ++i) {
2696 SDOperand Arg = Mask.getOperand(i);
2697 if (Arg.getOpcode() == ISD::UNDEF)
2700 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2701 if (Idx < NumElems) {
2702 unsigned Opc = V1.Val->getOpcode();
2703 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2705 if (Opc != ISD::BUILD_VECTOR ||
2706 !isZeroNode(V1.Val->getOperand(Idx)))
2708 } else if (Idx >= NumElems) {
2709 unsigned Opc = V2.Val->getOpcode();
2710 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2712 if (Opc != ISD::BUILD_VECTOR ||
2713 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2720 /// getZeroVector - Returns a vector of specified type with all zero elements.
2722 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2723 assert(MVT::isVector(VT) && "Expected a vector type");
2725 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2726 // type. This ensures they get CSE'd.
2727 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2729 if (MVT::getSizeInBits(VT) == 64) // MMX
2730 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2732 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2733 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2736 /// getOnesVector - Returns a vector of specified type with all bits set.
2738 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2739 assert(MVT::isVector(VT) && "Expected a vector type");
2741 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2742 // type. This ensures they get CSE'd.
2743 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2745 if (MVT::getSizeInBits(VT) == 64) // MMX
2746 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2748 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2749 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2753 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2754 /// that point to V2 points to its first element.
2755 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2756 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2758 bool Changed = false;
2759 SmallVector<SDOperand, 8> MaskVec;
2760 unsigned NumElems = Mask.getNumOperands();
2761 for (unsigned i = 0; i != NumElems; ++i) {
2762 SDOperand Arg = Mask.getOperand(i);
2763 if (Arg.getOpcode() != ISD::UNDEF) {
2764 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2765 if (Val > NumElems) {
2766 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2770 MaskVec.push_back(Arg);
2774 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2775 &MaskVec[0], MaskVec.size());
2779 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2780 /// operation of specified width.
2781 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2782 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2783 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2785 SmallVector<SDOperand, 8> MaskVec;
2786 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2787 for (unsigned i = 1; i != NumElems; ++i)
2788 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2789 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2792 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2793 /// of specified width.
2794 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2795 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2796 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2797 SmallVector<SDOperand, 8> MaskVec;
2798 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2799 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2800 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2802 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2805 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2806 /// of specified width.
2807 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2808 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2809 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2810 unsigned Half = NumElems/2;
2811 SmallVector<SDOperand, 8> MaskVec;
2812 for (unsigned i = 0; i != Half; ++i) {
2813 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2814 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2816 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2819 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2820 /// element #0 of a vector with the specified index, leaving the rest of the
2821 /// elements in place.
2822 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2823 SelectionDAG &DAG) {
2824 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2825 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2826 SmallVector<SDOperand, 8> MaskVec;
2827 // Element #0 of the result gets the elt we are replacing.
2828 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2829 for (unsigned i = 1; i != NumElems; ++i)
2830 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2831 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2834 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2835 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2836 MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2837 MVT::ValueType VT = Op.getValueType();
2840 SDOperand V1 = Op.getOperand(0);
2841 SDOperand Mask = Op.getOperand(2);
2842 unsigned NumElems = Mask.getNumOperands();
2843 // Special handling of v4f32 -> v4i32.
2844 if (VT != MVT::v4f32) {
2845 Mask = getUnpacklMask(NumElems, DAG);
2846 while (NumElems > 4) {
2847 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2850 Mask = getZeroVector(MVT::v4i32, DAG);
2853 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2854 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2855 DAG.getNode(ISD::UNDEF, PVT), Mask);
2856 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2859 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2860 /// vector of zero or undef vector. This produces a shuffle where the low
2861 /// element of V2 is swizzled into the zero/undef vector, landing at element
2862 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2863 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2864 bool isZero, SelectionDAG &DAG) {
2865 MVT::ValueType VT = V2.getValueType();
2866 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2867 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2868 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2869 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2870 SmallVector<SDOperand, 16> MaskVec;
2871 for (unsigned i = 0; i != NumElems; ++i)
2872 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2873 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2875 MaskVec.push_back(DAG.getConstant(i, EVT));
2876 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2877 &MaskVec[0], MaskVec.size());
2878 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2881 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2883 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2884 unsigned NumNonZero, unsigned NumZero,
2885 SelectionDAG &DAG, TargetLowering &TLI) {
2891 for (unsigned i = 0; i < 16; ++i) {
2892 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2893 if (ThisIsNonZero && First) {
2895 V = getZeroVector(MVT::v8i16, DAG);
2897 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2902 SDOperand ThisElt(0, 0), LastElt(0, 0);
2903 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2904 if (LastIsNonZero) {
2905 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2907 if (ThisIsNonZero) {
2908 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2909 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2910 ThisElt, DAG.getConstant(8, MVT::i8));
2912 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2917 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2918 DAG.getIntPtrConstant(i/2));
2922 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2925 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2927 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2928 unsigned NumNonZero, unsigned NumZero,
2929 SelectionDAG &DAG, TargetLowering &TLI) {
2935 for (unsigned i = 0; i < 8; ++i) {
2936 bool isNonZero = (NonZeros & (1 << i)) != 0;
2940 V = getZeroVector(MVT::v8i16, DAG);
2942 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2945 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2946 DAG.getIntPtrConstant(i));
2954 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2955 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2956 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2957 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2958 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2959 // eliminated on x86-32 hosts.
2960 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2963 if (ISD::isBuildVectorAllOnes(Op.Val))
2964 return getOnesVector(Op.getValueType(), DAG);
2965 return getZeroVector(Op.getValueType(), DAG);
2968 MVT::ValueType VT = Op.getValueType();
2969 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2970 unsigned EVTBits = MVT::getSizeInBits(EVT);
2972 unsigned NumElems = Op.getNumOperands();
2973 unsigned NumZero = 0;
2974 unsigned NumNonZero = 0;
2975 unsigned NonZeros = 0;
2976 bool IsAllConstants = true;
2977 SmallSet<SDOperand, 8> Values;
2978 for (unsigned i = 0; i < NumElems; ++i) {
2979 SDOperand Elt = Op.getOperand(i);
2980 if (Elt.getOpcode() == ISD::UNDEF)
2983 if (Elt.getOpcode() != ISD::Constant &&
2984 Elt.getOpcode() != ISD::ConstantFP)
2985 IsAllConstants = false;
2986 if (isZeroNode(Elt))
2989 NonZeros |= (1 << i);
2994 if (NumNonZero == 0) {
2995 // All undef vector. Return an UNDEF. All zero vectors were handled above.
2996 return DAG.getNode(ISD::UNDEF, VT);
2999 // Special case for single non-zero, non-undef, element.
3000 if (NumNonZero == 1 && NumElems <= 4) {
3001 unsigned Idx = CountTrailingZeros_32(NonZeros);
3002 SDOperand Item = Op.getOperand(Idx);
3004 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3005 // the value are obviously zero, truncate the value to i32 and do the
3006 // insertion that way. Only do this if the value is non-constant or if the
3007 // value is a constant being inserted into element 0. It is cheaper to do
3008 // a constant pool load than it is to do a movd + shuffle.
3009 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3010 (!IsAllConstants || Idx == 0)) {
3011 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3012 // Handle MMX and SSE both.
3013 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3014 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3016 // Truncate the value (which may itself be a constant) to i32, and
3017 // convert it to a vector with movd (S2V+shuffle to zero extend).
3018 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3019 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3020 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3022 // Now we have our 32-bit value zero extended in the low element of
3023 // a vector. If Idx != 0, swizzle it into place.
3026 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3027 getSwapEltZeroMask(VecElts, Idx, DAG)
3029 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3031 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3035 // If we have a constant or non-constant insertion into the low element of
3036 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3037 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3038 // depending on what the source datatype is. Because we can only get here
3039 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3041 // Don't do this for i64 values on x86-32.
3042 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3043 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3044 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3045 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3048 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3051 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3052 // is a non-constant being inserted into an element other than the low one,
3053 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3054 // movd/movss) to move this into the low element, then shuffle it into
3056 if (EVTBits == 32) {
3057 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3059 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3060 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3061 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3062 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3063 SmallVector<SDOperand, 8> MaskVec;
3064 for (unsigned i = 0; i < NumElems; i++)
3065 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3066 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3067 &MaskVec[0], MaskVec.size());
3068 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3069 DAG.getNode(ISD::UNDEF, VT), Mask);
3073 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3074 if (Values.size() == 1)
3077 // A vector full of immediates; various special cases are already
3078 // handled, so this is best done with a single constant-pool load.
3082 // Let legalizer expand 2-wide build_vectors.
3086 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3087 if (EVTBits == 8 && NumElems == 16) {
3088 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3090 if (V.Val) return V;
3093 if (EVTBits == 16 && NumElems == 8) {
3094 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3096 if (V.Val) return V;
3099 // If element VT is == 32 bits, turn it into a number of shuffles.
3100 SmallVector<SDOperand, 8> V;
3102 if (NumElems == 4 && NumZero > 0) {
3103 for (unsigned i = 0; i < 4; ++i) {
3104 bool isZero = !(NonZeros & (1 << i));
3106 V[i] = getZeroVector(VT, DAG);
3108 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3111 for (unsigned i = 0; i < 2; ++i) {
3112 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3115 V[i] = V[i*2]; // Must be a zero vector.
3118 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3119 getMOVLMask(NumElems, DAG));
3122 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3123 getMOVLMask(NumElems, DAG));
3126 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3127 getUnpacklMask(NumElems, DAG));
3132 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3133 // clears the upper bits.
3134 // FIXME: we can do the same for v4f32 case when we know both parts of
3135 // the lower half come from scalar_to_vector (loadf32). We should do
3136 // that in post legalizer dag combiner with target specific hooks.
3137 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3139 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3140 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3141 SmallVector<SDOperand, 8> MaskVec;
3142 bool Reverse = (NonZeros & 0x3) == 2;
3143 for (unsigned i = 0; i < 2; ++i)
3145 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3147 MaskVec.push_back(DAG.getConstant(i, EVT));
3148 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3149 for (unsigned i = 0; i < 2; ++i)
3151 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3153 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3154 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3155 &MaskVec[0], MaskVec.size());
3156 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3159 if (Values.size() > 2) {
3160 // Expand into a number of unpckl*.
3162 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3163 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3164 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3165 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3166 for (unsigned i = 0; i < NumElems; ++i)
3167 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3169 while (NumElems != 0) {
3170 for (unsigned i = 0; i < NumElems; ++i)
3171 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3182 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3183 SDOperand PermMask, SelectionDAG &DAG,
3184 TargetLowering &TLI) {
3186 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3187 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3188 MVT::ValueType PtrVT = TLI.getPointerTy();
3189 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3190 PermMask.Val->op_end());
3192 // First record which half of which vector the low elements come from.
3193 SmallVector<unsigned, 4> LowQuad(4);
3194 for (unsigned i = 0; i < 4; ++i) {
3195 SDOperand Elt = MaskElts[i];
3196 if (Elt.getOpcode() == ISD::UNDEF)
3198 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3199 int QuadIdx = EltIdx / 4;
3202 int BestLowQuad = -1;
3203 unsigned MaxQuad = 1;
3204 for (unsigned i = 0; i < 4; ++i) {
3205 if (LowQuad[i] > MaxQuad) {
3207 MaxQuad = LowQuad[i];
3211 // Record which half of which vector the high elements come from.
3212 SmallVector<unsigned, 4> HighQuad(4);
3213 for (unsigned i = 4; i < 8; ++i) {
3214 SDOperand Elt = MaskElts[i];
3215 if (Elt.getOpcode() == ISD::UNDEF)
3217 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3218 int QuadIdx = EltIdx / 4;
3219 ++HighQuad[QuadIdx];
3221 int BestHighQuad = -1;
3223 for (unsigned i = 0; i < 4; ++i) {
3224 if (HighQuad[i] > MaxQuad) {
3226 MaxQuad = HighQuad[i];
3230 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3231 if (BestLowQuad != -1 || BestHighQuad != -1) {
3232 // First sort the 4 chunks in order using shufpd.
3233 SmallVector<SDOperand, 8> MaskVec;
3234 if (BestLowQuad != -1)
3235 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3237 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3238 if (BestHighQuad != -1)
3239 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3241 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3242 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3243 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3244 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3245 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3246 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3248 // Now sort high and low parts separately.
3249 BitVector InOrder(8);
3250 if (BestLowQuad != -1) {
3251 // Sort lower half in order using PSHUFLW.
3253 bool AnyOutOrder = false;
3254 for (unsigned i = 0; i != 4; ++i) {
3255 SDOperand Elt = MaskElts[i];
3256 if (Elt.getOpcode() == ISD::UNDEF) {
3257 MaskVec.push_back(Elt);
3260 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3263 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3264 // If this element is in the right place after this shuffle, then
3266 if ((int)(EltIdx / 4) == BestLowQuad)
3271 for (unsigned i = 4; i != 8; ++i)
3272 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3273 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3274 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3278 if (BestHighQuad != -1) {
3279 // Sort high half in order using PSHUFHW if possible.
3281 for (unsigned i = 0; i != 4; ++i)
3282 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3283 bool AnyOutOrder = false;
3284 for (unsigned i = 4; i != 8; ++i) {
3285 SDOperand Elt = MaskElts[i];
3286 if (Elt.getOpcode() == ISD::UNDEF) {
3287 MaskVec.push_back(Elt);
3290 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3293 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3294 // If this element is in the right place after this shuffle, then
3296 if ((int)(EltIdx / 4) == BestHighQuad)
3301 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3302 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3306 // The other elements are put in the right place using pextrw and pinsrw.
3307 for (unsigned i = 0; i != 8; ++i) {
3310 SDOperand Elt = MaskElts[i];
3311 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3314 SDOperand ExtOp = (EltIdx < 8)
3315 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3316 DAG.getConstant(EltIdx, PtrVT))
3317 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3318 DAG.getConstant(EltIdx - 8, PtrVT));
3319 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3320 DAG.getConstant(i, PtrVT));
3325 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3326 ///as few as possible.
3327 // First, let's find out how many elements are already in the right order.
3328 unsigned V1InOrder = 0;
3329 unsigned V1FromV1 = 0;
3330 unsigned V2InOrder = 0;
3331 unsigned V2FromV2 = 0;
3332 SmallVector<SDOperand, 8> V1Elts;
3333 SmallVector<SDOperand, 8> V2Elts;
3334 for (unsigned i = 0; i < 8; ++i) {
3335 SDOperand Elt = MaskElts[i];
3336 if (Elt.getOpcode() == ISD::UNDEF) {
3337 V1Elts.push_back(Elt);
3338 V2Elts.push_back(Elt);
3343 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3345 V1Elts.push_back(Elt);
3346 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3348 } else if (EltIdx == i+8) {
3349 V1Elts.push_back(Elt);
3350 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3352 } else if (EltIdx < 8) {
3353 V1Elts.push_back(Elt);
3356 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3361 if (V2InOrder > V1InOrder) {
3362 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3364 std::swap(V1Elts, V2Elts);
3365 std::swap(V1FromV1, V2FromV2);
3368 if ((V1FromV1 + V1InOrder) != 8) {
3369 // Some elements are from V2.
3371 // If there are elements that are from V1 but out of place,
3372 // then first sort them in place
3373 SmallVector<SDOperand, 8> MaskVec;
3374 for (unsigned i = 0; i < 8; ++i) {
3375 SDOperand Elt = V1Elts[i];
3376 if (Elt.getOpcode() == ISD::UNDEF) {
3377 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3380 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3382 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3384 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3386 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3387 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3391 for (unsigned i = 0; i < 8; ++i) {
3392 SDOperand Elt = V1Elts[i];
3393 if (Elt.getOpcode() == ISD::UNDEF)
3395 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3398 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3399 DAG.getConstant(EltIdx - 8, PtrVT));
3400 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3401 DAG.getConstant(i, PtrVT));
3405 // All elements are from V1.
3407 for (unsigned i = 0; i < 8; ++i) {
3408 SDOperand Elt = V1Elts[i];
3409 if (Elt.getOpcode() == ISD::UNDEF)
3411 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3412 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3413 DAG.getConstant(EltIdx, PtrVT));
3414 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3415 DAG.getConstant(i, PtrVT));
3421 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3422 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3423 /// done when every pair / quad of shuffle mask elements point to elements in
3424 /// the right sequence. e.g.
3425 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3427 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3429 SDOperand PermMask, SelectionDAG &DAG,
3430 TargetLowering &TLI) {
3431 unsigned NumElems = PermMask.getNumOperands();
3432 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3433 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3434 MVT::ValueType NewVT = MaskVT;
3436 case MVT::v4f32: NewVT = MVT::v2f64; break;
3437 case MVT::v4i32: NewVT = MVT::v2i64; break;
3438 case MVT::v8i16: NewVT = MVT::v4i32; break;
3439 case MVT::v16i8: NewVT = MVT::v4i32; break;
3440 default: assert(false && "Unexpected!");
3443 if (NewWidth == 2) {
3444 if (MVT::isInteger(VT))
3449 unsigned Scale = NumElems / NewWidth;
3450 SmallVector<SDOperand, 8> MaskVec;
3451 for (unsigned i = 0; i < NumElems; i += Scale) {
3452 unsigned StartIdx = ~0U;
3453 for (unsigned j = 0; j < Scale; ++j) {
3454 SDOperand Elt = PermMask.getOperand(i+j);
3455 if (Elt.getOpcode() == ISD::UNDEF)
3457 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3458 if (StartIdx == ~0U)
3459 StartIdx = EltIdx - (EltIdx % Scale);
3460 if (EltIdx != StartIdx + j)
3463 if (StartIdx == ~0U)
3464 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3466 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3469 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3470 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3471 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3472 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3473 &MaskVec[0], MaskVec.size()));
3477 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3478 SDOperand V1 = Op.getOperand(0);
3479 SDOperand V2 = Op.getOperand(1);
3480 SDOperand PermMask = Op.getOperand(2);
3481 MVT::ValueType VT = Op.getValueType();
3482 unsigned NumElems = PermMask.getNumOperands();
3483 bool isMMX = MVT::getSizeInBits(VT) == 64;
3484 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3485 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3486 bool V1IsSplat = false;
3487 bool V2IsSplat = false;
3489 if (isUndefShuffle(Op.Val))
3490 return DAG.getNode(ISD::UNDEF, VT);
3492 if (isZeroShuffle(Op.Val))
3493 return getZeroVector(VT, DAG);
3495 if (isIdentityMask(PermMask.Val))
3497 else if (isIdentityMask(PermMask.Val, true))
3500 if (isSplatMask(PermMask.Val)) {
3501 if (isMMX || NumElems < 4) return Op;
3502 // Promote it to a v4{if}32 splat.
3503 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3506 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3508 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3509 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3511 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3512 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3513 // FIXME: Figure out a cleaner way to do this.
3514 // Try to make use of movq to zero out the top part.
3515 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3516 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3518 SDOperand NewV1 = NewOp.getOperand(0);
3519 SDOperand NewV2 = NewOp.getOperand(1);
3520 SDOperand NewMask = NewOp.getOperand(2);
3521 if (isCommutedMOVL(NewMask.Val, true, false)) {
3522 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3523 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3524 NewV1, NewV2, getMOVLMask(2, DAG));
3525 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3528 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3529 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3530 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3531 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3535 if (X86::isMOVLMask(PermMask.Val))
3536 return (V1IsUndef) ? V2 : Op;
3538 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3539 X86::isMOVSLDUPMask(PermMask.Val) ||
3540 X86::isMOVHLPSMask(PermMask.Val) ||
3541 X86::isMOVHPMask(PermMask.Val) ||
3542 X86::isMOVLPMask(PermMask.Val))
3545 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3546 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3547 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3549 bool Commuted = false;
3550 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3551 // 1,1,1,1 -> v8i16 though.
3552 V1IsSplat = isSplatVector(V1.Val);
3553 V2IsSplat = isSplatVector(V2.Val);
3555 // Canonicalize the splat or undef, if present, to be on the RHS.
3556 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3557 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3558 std::swap(V1IsSplat, V2IsSplat);
3559 std::swap(V1IsUndef, V2IsUndef);
3563 // FIXME: Figure out a cleaner way to do this.
3564 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3565 if (V2IsUndef) return V1;
3566 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3568 // V2 is a splat, so the mask may be malformed. That is, it may point
3569 // to any V2 element. The instruction selectior won't like this. Get
3570 // a corrected mask and commute to form a proper MOVS{S|D}.
3571 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3572 if (NewMask.Val != PermMask.Val)
3573 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3578 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3579 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3580 X86::isUNPCKLMask(PermMask.Val) ||
3581 X86::isUNPCKHMask(PermMask.Val))
3585 // Normalize mask so all entries that point to V2 points to its first
3586 // element then try to match unpck{h|l} again. If match, return a
3587 // new vector_shuffle with the corrected mask.
3588 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3589 if (NewMask.Val != PermMask.Val) {
3590 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3591 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3592 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3593 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3594 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3595 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3600 // Normalize the node to match x86 shuffle ops if needed
3601 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3602 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3605 // Commute is back and try unpck* again.
3606 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3607 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3608 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3609 X86::isUNPCKLMask(PermMask.Val) ||
3610 X86::isUNPCKHMask(PermMask.Val))
3614 // Try PSHUF* first, then SHUFP*.
3615 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3616 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3617 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3618 if (V2.getOpcode() != ISD::UNDEF)
3619 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3620 DAG.getNode(ISD::UNDEF, VT), PermMask);
3625 if (Subtarget->hasSSE2() &&
3626 (X86::isPSHUFDMask(PermMask.Val) ||
3627 X86::isPSHUFHWMask(PermMask.Val) ||
3628 X86::isPSHUFLWMask(PermMask.Val))) {
3629 MVT::ValueType RVT = VT;
3630 if (VT == MVT::v4f32) {
3632 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3633 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3634 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3635 } else if (V2.getOpcode() != ISD::UNDEF)
3636 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3637 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3639 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3643 // Binary or unary shufps.
3644 if (X86::isSHUFPMask(PermMask.Val) ||
3645 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3649 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3650 if (VT == MVT::v8i16) {
3651 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3656 // Handle all 4 wide cases with a number of shuffles.
3657 if (NumElems == 4 && !isMMX) {
3658 // Don't do this for MMX.
3659 MVT::ValueType MaskVT = PermMask.getValueType();
3660 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3661 SmallVector<std::pair<int, int>, 8> Locs;
3662 Locs.reserve(NumElems);
3663 SmallVector<SDOperand, 8> Mask1(NumElems,
3664 DAG.getNode(ISD::UNDEF, MaskEVT));
3665 SmallVector<SDOperand, 8> Mask2(NumElems,
3666 DAG.getNode(ISD::UNDEF, MaskEVT));
3669 // If no more than two elements come from either vector. This can be
3670 // implemented with two shuffles. First shuffle gather the elements.
3671 // The second shuffle, which takes the first shuffle as both of its
3672 // vector operands, put the elements into the right order.
3673 for (unsigned i = 0; i != NumElems; ++i) {
3674 SDOperand Elt = PermMask.getOperand(i);
3675 if (Elt.getOpcode() == ISD::UNDEF) {
3676 Locs[i] = std::make_pair(-1, -1);
3678 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3679 if (Val < NumElems) {
3680 Locs[i] = std::make_pair(0, NumLo);
3684 Locs[i] = std::make_pair(1, NumHi);
3685 if (2+NumHi < NumElems)
3686 Mask1[2+NumHi] = Elt;
3691 if (NumLo <= 2 && NumHi <= 2) {
3692 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3693 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3694 &Mask1[0], Mask1.size()));
3695 for (unsigned i = 0; i != NumElems; ++i) {
3696 if (Locs[i].first == -1)
3699 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3700 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3701 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3705 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3706 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3707 &Mask2[0], Mask2.size()));
3710 // Break it into (shuffle shuffle_hi, shuffle_lo).
3712 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3713 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3714 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3715 unsigned MaskIdx = 0;
3717 unsigned HiIdx = NumElems/2;
3718 for (unsigned i = 0; i != NumElems; ++i) {
3719 if (i == NumElems/2) {
3725 SDOperand Elt = PermMask.getOperand(i);
3726 if (Elt.getOpcode() == ISD::UNDEF) {
3727 Locs[i] = std::make_pair(-1, -1);
3728 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3729 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3730 (*MaskPtr)[LoIdx] = Elt;
3733 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3734 (*MaskPtr)[HiIdx] = Elt;
3739 SDOperand LoShuffle =
3740 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3741 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3742 &LoMask[0], LoMask.size()));
3743 SDOperand HiShuffle =
3744 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3745 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3746 &HiMask[0], HiMask.size()));
3747 SmallVector<SDOperand, 8> MaskOps;
3748 for (unsigned i = 0; i != NumElems; ++i) {
3749 if (Locs[i].first == -1) {
3750 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3752 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3753 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3756 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3757 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3758 &MaskOps[0], MaskOps.size()));
3765 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3766 SelectionDAG &DAG) {
3767 MVT::ValueType VT = Op.getValueType();
3768 if (MVT::getSizeInBits(VT) == 8) {
3769 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3770 Op.getOperand(0), Op.getOperand(1));
3771 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3772 DAG.getValueType(VT));
3773 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3774 } else if (MVT::getSizeInBits(VT) == 16) {
3775 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3776 Op.getOperand(0), Op.getOperand(1));
3777 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3778 DAG.getValueType(VT));
3779 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3780 } else if (VT == MVT::f32) {
3781 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3782 // the result back to FR32 register. It's only worth matching if the
3783 // result has a single use which is a store or a bitcast to i32.
3784 if (!Op.hasOneUse())
3786 SDNode *User = Op.Val->use_begin()->getUser();
3787 if (User->getOpcode() != ISD::STORE &&
3788 (User->getOpcode() != ISD::BIT_CONVERT ||
3789 User->getValueType(0) != MVT::i32))
3791 SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3792 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3794 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3801 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3802 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3805 if (Subtarget->hasSSE41()) {
3806 SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3811 MVT::ValueType VT = Op.getValueType();
3812 // TODO: handle v16i8.
3813 if (MVT::getSizeInBits(VT) == 16) {
3814 SDOperand Vec = Op.getOperand(0);
3815 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3817 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3818 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3819 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3821 // Transform it so it match pextrw which produces a 32-bit result.
3822 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3823 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3824 Op.getOperand(0), Op.getOperand(1));
3825 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3826 DAG.getValueType(VT));
3827 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3828 } else if (MVT::getSizeInBits(VT) == 32) {
3829 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3832 // SHUFPS the element to the lowest double word, then movss.
3833 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3834 SmallVector<SDOperand, 8> IdxVec;
3836 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3838 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3840 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3842 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3843 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3844 &IdxVec[0], IdxVec.size());
3845 SDOperand Vec = Op.getOperand(0);
3846 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3847 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3848 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3849 DAG.getIntPtrConstant(0));
3850 } else if (MVT::getSizeInBits(VT) == 64) {
3851 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3852 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3853 // to match extract_elt for f64.
3854 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3858 // UNPCKHPD the element to the lowest double word, then movsd.
3859 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3860 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3861 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3862 SmallVector<SDOperand, 8> IdxVec;
3863 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3865 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3866 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3867 &IdxVec[0], IdxVec.size());
3868 SDOperand Vec = Op.getOperand(0);
3869 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3870 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3871 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3872 DAG.getIntPtrConstant(0));
3879 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3880 MVT::ValueType VT = Op.getValueType();
3881 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3883 SDOperand N0 = Op.getOperand(0);
3884 SDOperand N1 = Op.getOperand(1);
3885 SDOperand N2 = Op.getOperand(2);
3887 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3888 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3890 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3892 if (N1.getValueType() != MVT::i32)
3893 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3894 if (N2.getValueType() != MVT::i32)
3895 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3896 return DAG.getNode(Opc, VT, N0, N1, N2);
3897 } else if (EVT == MVT::f32) {
3898 // Bits [7:6] of the constant are the source select. This will always be
3899 // zero here. The DAG Combiner may combine an extract_elt index into these
3900 // bits. For example (insert (extract, 3), 2) could be matched by putting
3901 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3902 // Bits [5:4] of the constant are the destination select. This is the
3903 // value of the incoming immediate.
3904 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3905 // combine either bitwise AND or insert of float 0.0 to set these bits.
3906 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3907 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3913 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3914 MVT::ValueType VT = Op.getValueType();
3915 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3917 if (Subtarget->hasSSE41())
3918 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3923 SDOperand N0 = Op.getOperand(0);
3924 SDOperand N1 = Op.getOperand(1);
3925 SDOperand N2 = Op.getOperand(2);
3927 if (MVT::getSizeInBits(EVT) == 16) {
3928 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3929 // as its second argument.
3930 if (N1.getValueType() != MVT::i32)
3931 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3932 if (N2.getValueType() != MVT::i32)
3933 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3934 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3940 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3941 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3942 MVT::ValueType VT = MVT::v2i32;
3943 switch (Op.getValueType()) {
3950 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3951 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3954 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3955 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3956 // one of the above mentioned nodes. It has to be wrapped because otherwise
3957 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3958 // be used to form addressing mode. These wrapped nodes will be selected
3961 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3962 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3963 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3965 CP->getAlignment());
3966 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3967 // With PIC, the address is actually $g + Offset.
3968 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3969 !Subtarget->isPICStyleRIPRel()) {
3970 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3971 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3979 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3980 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3981 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3982 // If it's a debug information descriptor, don't mess with it.
3983 if (DAG.isVerifiedDebugInfoDesc(Op))
3985 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3986 // With PIC, the address is actually $g + Offset.
3987 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3988 !Subtarget->isPICStyleRIPRel()) {
3989 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3990 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3994 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3995 // load the value at address GV, not the value of GV itself. This means that
3996 // the GlobalAddress must be in the base or index register of the address, not
3997 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3998 // The same applies for external symbols during PIC codegen
3999 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4000 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4001 PseudoSourceValue::getGOT(), 0);
4006 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4008 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4009 const MVT::ValueType PtrVT) {
4011 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4012 DAG.getNode(X86ISD::GlobalBaseReg,
4014 InFlag = Chain.getValue(1);
4016 // emit leal symbol@TLSGD(,%ebx,1), %eax
4017 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4018 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4019 GA->getValueType(0),
4021 SDOperand Ops[] = { Chain, TGA, InFlag };
4022 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4023 InFlag = Result.getValue(2);
4024 Chain = Result.getValue(1);
4026 // call ___tls_get_addr. This function receives its argument in
4027 // the register EAX.
4028 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4029 InFlag = Chain.getValue(1);
4031 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4032 SDOperand Ops1[] = { Chain,
4033 DAG.getTargetExternalSymbol("___tls_get_addr",
4035 DAG.getRegister(X86::EAX, PtrVT),
4036 DAG.getRegister(X86::EBX, PtrVT),
4038 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4039 InFlag = Chain.getValue(1);
4041 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4044 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4046 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4047 const MVT::ValueType PtrVT) {
4048 SDOperand InFlag, Chain;
4050 // emit leaq symbol@TLSGD(%rip), %rdi
4051 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4052 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4053 GA->getValueType(0),
4055 SDOperand Ops[] = { DAG.getEntryNode(), TGA};
4056 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4057 Chain = Result.getValue(1);
4058 InFlag = Result.getValue(2);
4060 // call ___tls_get_addr. This function receives its argument in
4061 // the register RDI.
4062 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4063 InFlag = Chain.getValue(1);
4065 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4066 SDOperand Ops1[] = { Chain,
4067 DAG.getTargetExternalSymbol("___tls_get_addr",
4069 DAG.getRegister(X86::RDI, PtrVT),
4071 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4072 InFlag = Chain.getValue(1);
4074 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4077 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4078 // "local exec" model.
4080 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4081 const MVT::ValueType PtrVT) {
4082 // Get the Thread Pointer
4083 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4084 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4086 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4087 GA->getValueType(0),
4089 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4091 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4092 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4093 PseudoSourceValue::getGOT(), 0);
4095 // The address of the thread local variable is the add of the thread
4096 // pointer with the offset of the variable.
4097 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4101 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4102 // TODO: implement the "local dynamic" model
4103 // TODO: implement the "initial exec"model for pic executables
4104 assert(Subtarget->isTargetELF() &&
4105 "TLS not implemented for non-ELF targets");
4106 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4107 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4108 // otherwise use the "Local Exec"TLS Model
4109 if (Subtarget->is64Bit()) {
4110 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4112 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4113 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4115 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4120 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4121 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4122 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4123 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4124 // With PIC, the address is actually $g + Offset.
4125 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4126 !Subtarget->isPICStyleRIPRel()) {
4127 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4128 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4135 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4136 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4137 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4138 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4139 // With PIC, the address is actually $g + Offset.
4140 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4141 !Subtarget->isPICStyleRIPRel()) {
4142 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4143 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4150 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4151 /// take a 2 x i32 value to shift plus a shift amount.
4152 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4153 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4154 MVT::ValueType VT = Op.getValueType();
4155 unsigned VTBits = MVT::getSizeInBits(VT);
4156 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4157 SDOperand ShOpLo = Op.getOperand(0);
4158 SDOperand ShOpHi = Op.getOperand(1);
4159 SDOperand ShAmt = Op.getOperand(2);
4160 SDOperand Tmp1 = isSRA ?
4161 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4162 DAG.getConstant(0, VT);
4164 SDOperand Tmp2, Tmp3;
4165 if (Op.getOpcode() == ISD::SHL_PARTS) {
4166 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4167 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4169 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4170 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4173 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4174 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4175 DAG.getConstant(VTBits, MVT::i8));
4176 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4177 AndNode, DAG.getConstant(0, MVT::i8));
4180 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4181 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4182 SmallVector<SDOperand, 4> Ops;
4183 if (Op.getOpcode() == ISD::SHL_PARTS) {
4184 Ops.push_back(Tmp2);
4185 Ops.push_back(Tmp3);
4187 Ops.push_back(Cond);
4188 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4191 Ops.push_back(Tmp3);
4192 Ops.push_back(Tmp1);
4194 Ops.push_back(Cond);
4195 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4197 Ops.push_back(Tmp2);
4198 Ops.push_back(Tmp3);
4200 Ops.push_back(Cond);
4201 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4204 Ops.push_back(Tmp3);
4205 Ops.push_back(Tmp1);
4207 Ops.push_back(Cond);
4208 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4211 VTs = DAG.getNodeValueTypes(VT, VT);
4215 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4218 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4219 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4220 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4221 "Unknown SINT_TO_FP to lower!");
4223 // These are really Legal; caller falls through into that case.
4224 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4226 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4227 Subtarget->is64Bit())
4230 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4231 MachineFunction &MF = DAG.getMachineFunction();
4232 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4233 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4234 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4236 PseudoSourceValue::getFixedStack(),
4241 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4243 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4245 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4246 SmallVector<SDOperand, 8> Ops;
4247 Ops.push_back(Chain);
4248 Ops.push_back(StackSlot);
4249 Ops.push_back(DAG.getValueType(SrcVT));
4250 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4251 Tys, &Ops[0], Ops.size());
4254 Chain = Result.getValue(1);
4255 SDOperand InFlag = Result.getValue(2);
4257 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4258 // shouldn't be necessary except that RFP cannot be live across
4259 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4260 MachineFunction &MF = DAG.getMachineFunction();
4261 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4262 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4263 Tys = DAG.getVTList(MVT::Other);
4264 SmallVector<SDOperand, 8> Ops;
4265 Ops.push_back(Chain);
4266 Ops.push_back(Result);
4267 Ops.push_back(StackSlot);
4268 Ops.push_back(DAG.getValueType(Op.getValueType()));
4269 Ops.push_back(InFlag);
4270 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4271 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4272 PseudoSourceValue::getFixedStack(), SSFI);
4278 std::pair<SDOperand,SDOperand> X86TargetLowering::
4279 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4280 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4281 "Unknown FP_TO_SINT to lower!");
4283 // These are really Legal.
4284 if (Op.getValueType() == MVT::i32 &&
4285 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4286 return std::make_pair(SDOperand(), SDOperand());
4287 if (Subtarget->is64Bit() &&
4288 Op.getValueType() == MVT::i64 &&
4289 Op.getOperand(0).getValueType() != MVT::f80)
4290 return std::make_pair(SDOperand(), SDOperand());
4292 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4294 MachineFunction &MF = DAG.getMachineFunction();
4295 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4296 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4297 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4299 switch (Op.getValueType()) {
4300 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4301 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4302 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4303 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4306 SDOperand Chain = DAG.getEntryNode();
4307 SDOperand Value = Op.getOperand(0);
4308 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4309 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4310 Chain = DAG.getStore(Chain, Value, StackSlot,
4311 PseudoSourceValue::getFixedStack(), SSFI);
4312 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4314 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4316 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4317 Chain = Value.getValue(1);
4318 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4319 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4322 // Build the FP_TO_INT*_IN_MEM
4323 SDOperand Ops[] = { Chain, Value, StackSlot };
4324 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4326 return std::make_pair(FIST, StackSlot);
4329 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4330 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4331 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4332 if (FIST.Val == 0) return SDOperand();
4335 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4338 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4339 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4340 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4341 if (FIST.Val == 0) return 0;
4343 // Return an i64 load from the stack slot.
4344 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4346 // Use a MERGE_VALUES node to drop the chain result value.
4347 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4350 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4351 MVT::ValueType VT = Op.getValueType();
4352 MVT::ValueType EltVT = VT;
4353 if (MVT::isVector(VT))
4354 EltVT = MVT::getVectorElementType(VT);
4355 std::vector<Constant*> CV;
4356 if (EltVT == MVT::f64) {
4357 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4361 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4367 Constant *C = ConstantVector::get(CV);
4368 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4369 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4370 PseudoSourceValue::getConstantPool(), 0,
4372 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4375 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4376 MVT::ValueType VT = Op.getValueType();
4377 MVT::ValueType EltVT = VT;
4378 unsigned EltNum = 1;
4379 if (MVT::isVector(VT)) {
4380 EltVT = MVT::getVectorElementType(VT);
4381 EltNum = MVT::getVectorNumElements(VT);
4383 std::vector<Constant*> CV;
4384 if (EltVT == MVT::f64) {
4385 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4389 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4395 Constant *C = ConstantVector::get(CV);
4396 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4397 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4398 PseudoSourceValue::getConstantPool(), 0,
4400 if (MVT::isVector(VT)) {
4401 return DAG.getNode(ISD::BIT_CONVERT, VT,
4402 DAG.getNode(ISD::XOR, MVT::v2i64,
4403 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4404 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4406 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4410 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4411 SDOperand Op0 = Op.getOperand(0);
4412 SDOperand Op1 = Op.getOperand(1);
4413 MVT::ValueType VT = Op.getValueType();
4414 MVT::ValueType SrcVT = Op1.getValueType();
4416 // If second operand is smaller, extend it first.
4417 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4418 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4421 // And if it is bigger, shrink it first.
4422 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4423 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4427 // At this point the operands and the result should have the same
4428 // type, and that won't be f80 since that is not custom lowered.
4430 // First get the sign bit of second operand.
4431 std::vector<Constant*> CV;
4432 if (SrcVT == MVT::f64) {
4433 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4434 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4436 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4437 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4438 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4439 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4441 Constant *C = ConstantVector::get(CV);
4442 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4443 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4444 PseudoSourceValue::getConstantPool(), 0,
4446 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4448 // Shift sign bit right or left if the two operands have different types.
4449 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4450 // Op0 is MVT::f32, Op1 is MVT::f64.
4451 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4452 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4453 DAG.getConstant(32, MVT::i32));
4454 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4455 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4456 DAG.getIntPtrConstant(0));
4459 // Clear first operand sign bit.
4461 if (VT == MVT::f64) {
4462 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4463 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4465 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4466 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4467 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4468 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4470 C = ConstantVector::get(CV);
4471 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4472 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4473 PseudoSourceValue::getConstantPool(), 0,
4475 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4477 // Or the value with the sign bit.
4478 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4481 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4482 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4484 SDOperand Op0 = Op.getOperand(0);
4485 SDOperand Op1 = Op.getOperand(1);
4486 SDOperand CC = Op.getOperand(2);
4487 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4488 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4491 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4493 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4494 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4495 DAG.getConstant(X86CC, MVT::i8), Cond);
4498 assert(isFP && "Illegal integer SetCC!");
4500 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4501 switch (SetCCOpcode) {
4502 default: assert(false && "Illegal floating point SetCC!");
4503 case ISD::SETOEQ: { // !PF & ZF
4504 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4505 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4506 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4507 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4508 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4510 case ISD::SETUNE: { // PF | !ZF
4511 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4512 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4513 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4514 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4515 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4521 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4522 bool addTest = true;
4523 SDOperand Cond = Op.getOperand(0);
4526 if (Cond.getOpcode() == ISD::SETCC)
4527 Cond = LowerSETCC(Cond, DAG);
4529 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4530 // setting operand in place of the X86ISD::SETCC.
4531 if (Cond.getOpcode() == X86ISD::SETCC) {
4532 CC = Cond.getOperand(0);
4534 SDOperand Cmp = Cond.getOperand(1);
4535 unsigned Opc = Cmp.getOpcode();
4536 MVT::ValueType VT = Op.getValueType();
4538 bool IllegalFPCMov = false;
4539 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4540 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4541 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4543 if ((Opc == X86ISD::CMP ||
4544 Opc == X86ISD::COMI ||
4545 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4552 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4553 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4556 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4558 SmallVector<SDOperand, 4> Ops;
4559 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4560 // condition is true.
4561 Ops.push_back(Op.getOperand(2));
4562 Ops.push_back(Op.getOperand(1));
4564 Ops.push_back(Cond);
4565 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4568 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4569 bool addTest = true;
4570 SDOperand Chain = Op.getOperand(0);
4571 SDOperand Cond = Op.getOperand(1);
4572 SDOperand Dest = Op.getOperand(2);
4575 if (Cond.getOpcode() == ISD::SETCC)
4576 Cond = LowerSETCC(Cond, DAG);
4578 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4579 // setting operand in place of the X86ISD::SETCC.
4580 if (Cond.getOpcode() == X86ISD::SETCC) {
4581 CC = Cond.getOperand(0);
4583 SDOperand Cmp = Cond.getOperand(1);
4584 unsigned Opc = Cmp.getOpcode();
4585 if (Opc == X86ISD::CMP ||
4586 Opc == X86ISD::COMI ||
4587 Opc == X86ISD::UCOMI) {
4594 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4595 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4597 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4598 Chain, Op.getOperand(2), CC, Cond);
4602 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4603 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4604 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4605 // that the guard pages used by the OS virtual memory manager are allocated in
4606 // correct sequence.
4608 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4609 SelectionDAG &DAG) {
4610 assert(Subtarget->isTargetCygMing() &&
4611 "This should be used only on Cygwin/Mingw targets");
4614 SDOperand Chain = Op.getOperand(0);
4615 SDOperand Size = Op.getOperand(1);
4616 // FIXME: Ensure alignment here
4620 MVT::ValueType IntPtr = getPointerTy();
4621 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4623 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4624 Flag = Chain.getValue(1);
4626 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4627 SDOperand Ops[] = { Chain,
4628 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4629 DAG.getRegister(X86::EAX, IntPtr),
4631 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4632 Flag = Chain.getValue(1);
4634 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4636 std::vector<MVT::ValueType> Tys;
4637 Tys.push_back(SPTy);
4638 Tys.push_back(MVT::Other);
4639 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4640 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4644 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4646 SDOperand Dst, SDOperand Src,
4647 SDOperand Size, unsigned Align,
4648 const Value *DstSV, uint64_t DstSVOff) {
4649 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4651 /// If not DWORD aligned or size is more than the threshold, call the library.
4652 /// The libc version is likely to be faster for these cases. It can use the
4653 /// address value and run time information about the CPU.
4654 if ((Align & 3) == 0 ||
4656 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4657 SDOperand InFlag(0, 0);
4659 // Check to see if there is a specialized entry-point for memory zeroing.
4660 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4661 if (const char *bzeroEntry =
4662 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4663 MVT::ValueType IntPtr = getPointerTy();
4664 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4665 TargetLowering::ArgListTy Args;
4666 TargetLowering::ArgListEntry Entry;
4668 Entry.Ty = IntPtrTy;
4669 Args.push_back(Entry);
4671 Args.push_back(Entry);
4672 std::pair<SDOperand,SDOperand> CallResult =
4673 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4674 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4676 return CallResult.second;
4679 // Otherwise have the target-independent code call memset.
4683 uint64_t SizeVal = ConstantSize->getValue();
4684 SDOperand InFlag(0, 0);
4687 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4688 unsigned BytesLeft = 0;
4689 bool TwoRepStos = false;
4692 uint64_t Val = ValC->getValue() & 255;
4694 // If the value is a constant, then we can potentially use larger sets.
4695 switch (Align & 3) {
4696 case 2: // WORD aligned
4699 Val = (Val << 8) | Val;
4701 case 0: // DWORD aligned
4704 Val = (Val << 8) | Val;
4705 Val = (Val << 16) | Val;
4706 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
4709 Val = (Val << 32) | Val;
4712 default: // Byte aligned
4715 Count = DAG.getIntPtrConstant(SizeVal);
4719 if (AVT > MVT::i8) {
4720 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4721 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4722 BytesLeft = SizeVal % UBytes;
4725 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4727 InFlag = Chain.getValue(1);
4730 Count = DAG.getIntPtrConstant(SizeVal);
4731 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4732 InFlag = Chain.getValue(1);
4735 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4737 InFlag = Chain.getValue(1);
4738 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4740 InFlag = Chain.getValue(1);
4742 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4743 SmallVector<SDOperand, 8> Ops;
4744 Ops.push_back(Chain);
4745 Ops.push_back(DAG.getValueType(AVT));
4746 Ops.push_back(InFlag);
4747 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4750 InFlag = Chain.getValue(1);
4752 MVT::ValueType CVT = Count.getValueType();
4753 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4754 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4755 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4757 InFlag = Chain.getValue(1);
4758 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4760 Ops.push_back(Chain);
4761 Ops.push_back(DAG.getValueType(MVT::i8));
4762 Ops.push_back(InFlag);
4763 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4764 } else if (BytesLeft) {
4765 // Handle the last 1 - 7 bytes.
4766 unsigned Offset = SizeVal - BytesLeft;
4767 MVT::ValueType AddrVT = Dst.getValueType();
4768 MVT::ValueType SizeVT = Size.getValueType();
4770 Chain = DAG.getMemset(Chain,
4771 DAG.getNode(ISD::ADD, AddrVT, Dst,
4772 DAG.getConstant(Offset, AddrVT)),
4774 DAG.getConstant(BytesLeft, SizeVT),
4775 Align, DstSV, DstSVOff + Offset);
4778 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4783 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4785 SDOperand Dst, SDOperand Src,
4786 SDOperand Size, unsigned Align,
4788 const Value *DstSV, uint64_t DstSVOff,
4789 const Value *SrcSV, uint64_t SrcSVOff){
4791 // This requires the copy size to be a constant, preferrably
4792 // within a subtarget-specific limit.
4793 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4796 uint64_t SizeVal = ConstantSize->getValue();
4797 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4801 unsigned BytesLeft = 0;
4802 if (Align >= 8 && Subtarget->is64Bit())
4804 else if (Align >= 4)
4806 else if (Align >= 2)
4811 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4812 unsigned CountVal = SizeVal / UBytes;
4813 SDOperand Count = DAG.getIntPtrConstant(CountVal);
4814 BytesLeft = SizeVal % UBytes;
4816 SDOperand InFlag(0, 0);
4817 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4819 InFlag = Chain.getValue(1);
4820 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4822 InFlag = Chain.getValue(1);
4823 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4825 InFlag = Chain.getValue(1);
4827 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4828 SmallVector<SDOperand, 8> Ops;
4829 Ops.push_back(Chain);
4830 Ops.push_back(DAG.getValueType(AVT));
4831 Ops.push_back(InFlag);
4832 SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4834 SmallVector<SDOperand, 4> Results;
4835 Results.push_back(RepMovs);
4837 // Handle the last 1 - 7 bytes.
4838 unsigned Offset = SizeVal - BytesLeft;
4839 MVT::ValueType DstVT = Dst.getValueType();
4840 MVT::ValueType SrcVT = Src.getValueType();
4841 MVT::ValueType SizeVT = Size.getValueType();
4842 Results.push_back(DAG.getMemcpy(Chain,
4843 DAG.getNode(ISD::ADD, DstVT, Dst,
4844 DAG.getConstant(Offset, DstVT)),
4845 DAG.getNode(ISD::ADD, SrcVT, Src,
4846 DAG.getConstant(Offset, SrcVT)),
4847 DAG.getConstant(BytesLeft, SizeVT),
4848 Align, AlwaysInline,
4849 DstSV, DstSVOff + Offset,
4850 SrcSV, SrcSVOff + Offset));
4853 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4856 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4857 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4858 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4859 SDOperand TheChain = N->getOperand(0);
4860 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4861 if (Subtarget->is64Bit()) {
4862 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4863 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4864 MVT::i64, rax.getValue(2));
4865 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4866 DAG.getConstant(32, MVT::i8));
4868 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4871 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4872 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4875 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4876 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4877 MVT::i32, eax.getValue(2));
4878 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4879 SDOperand Ops[] = { eax, edx };
4880 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4882 // Use a MERGE_VALUES to return the value and chain.
4883 Ops[1] = edx.getValue(1);
4884 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4885 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4888 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4889 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4891 if (!Subtarget->is64Bit()) {
4892 // vastart just stores the address of the VarArgsFrameIndex slot into the
4893 // memory location argument.
4894 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4895 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4899 // gp_offset (0 - 6 * 8)
4900 // fp_offset (48 - 48 + 8 * 16)
4901 // overflow_arg_area (point to parameters coming in memory).
4903 SmallVector<SDOperand, 8> MemOps;
4904 SDOperand FIN = Op.getOperand(1);
4906 SDOperand Store = DAG.getStore(Op.getOperand(0),
4907 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4909 MemOps.push_back(Store);
4912 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4913 Store = DAG.getStore(Op.getOperand(0),
4914 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4916 MemOps.push_back(Store);
4918 // Store ptr to overflow_arg_area
4919 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4920 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4921 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4922 MemOps.push_back(Store);
4924 // Store ptr to reg_save_area.
4925 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4926 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4927 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4928 MemOps.push_back(Store);
4929 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4932 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4933 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4934 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
4935 SDOperand Chain = Op.getOperand(0);
4936 SDOperand DstPtr = Op.getOperand(1);
4937 SDOperand SrcPtr = Op.getOperand(2);
4938 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4939 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4941 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
4942 DAG.getIntPtrConstant(24), 8, false,
4943 DstSV, 0, SrcSV, 0);
4947 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4948 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4950 default: return SDOperand(); // Don't custom lower most intrinsics.
4951 // Comparison intrinsics.
4952 case Intrinsic::x86_sse_comieq_ss:
4953 case Intrinsic::x86_sse_comilt_ss:
4954 case Intrinsic::x86_sse_comile_ss:
4955 case Intrinsic::x86_sse_comigt_ss:
4956 case Intrinsic::x86_sse_comige_ss:
4957 case Intrinsic::x86_sse_comineq_ss:
4958 case Intrinsic::x86_sse_ucomieq_ss:
4959 case Intrinsic::x86_sse_ucomilt_ss:
4960 case Intrinsic::x86_sse_ucomile_ss:
4961 case Intrinsic::x86_sse_ucomigt_ss:
4962 case Intrinsic::x86_sse_ucomige_ss:
4963 case Intrinsic::x86_sse_ucomineq_ss:
4964 case Intrinsic::x86_sse2_comieq_sd:
4965 case Intrinsic::x86_sse2_comilt_sd:
4966 case Intrinsic::x86_sse2_comile_sd:
4967 case Intrinsic::x86_sse2_comigt_sd:
4968 case Intrinsic::x86_sse2_comige_sd:
4969 case Intrinsic::x86_sse2_comineq_sd:
4970 case Intrinsic::x86_sse2_ucomieq_sd:
4971 case Intrinsic::x86_sse2_ucomilt_sd:
4972 case Intrinsic::x86_sse2_ucomile_sd:
4973 case Intrinsic::x86_sse2_ucomigt_sd:
4974 case Intrinsic::x86_sse2_ucomige_sd:
4975 case Intrinsic::x86_sse2_ucomineq_sd: {
4977 ISD::CondCode CC = ISD::SETCC_INVALID;
4980 case Intrinsic::x86_sse_comieq_ss:
4981 case Intrinsic::x86_sse2_comieq_sd:
4985 case Intrinsic::x86_sse_comilt_ss:
4986 case Intrinsic::x86_sse2_comilt_sd:
4990 case Intrinsic::x86_sse_comile_ss:
4991 case Intrinsic::x86_sse2_comile_sd:
4995 case Intrinsic::x86_sse_comigt_ss:
4996 case Intrinsic::x86_sse2_comigt_sd:
5000 case Intrinsic::x86_sse_comige_ss:
5001 case Intrinsic::x86_sse2_comige_sd:
5005 case Intrinsic::x86_sse_comineq_ss:
5006 case Intrinsic::x86_sse2_comineq_sd:
5010 case Intrinsic::x86_sse_ucomieq_ss:
5011 case Intrinsic::x86_sse2_ucomieq_sd:
5012 Opc = X86ISD::UCOMI;
5015 case Intrinsic::x86_sse_ucomilt_ss:
5016 case Intrinsic::x86_sse2_ucomilt_sd:
5017 Opc = X86ISD::UCOMI;
5020 case Intrinsic::x86_sse_ucomile_ss:
5021 case Intrinsic::x86_sse2_ucomile_sd:
5022 Opc = X86ISD::UCOMI;
5025 case Intrinsic::x86_sse_ucomigt_ss:
5026 case Intrinsic::x86_sse2_ucomigt_sd:
5027 Opc = X86ISD::UCOMI;
5030 case Intrinsic::x86_sse_ucomige_ss:
5031 case Intrinsic::x86_sse2_ucomige_sd:
5032 Opc = X86ISD::UCOMI;
5035 case Intrinsic::x86_sse_ucomineq_ss:
5036 case Intrinsic::x86_sse2_ucomineq_sd:
5037 Opc = X86ISD::UCOMI;
5043 SDOperand LHS = Op.getOperand(1);
5044 SDOperand RHS = Op.getOperand(2);
5045 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5047 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5048 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5049 DAG.getConstant(X86CC, MVT::i8), Cond);
5050 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5053 // Fix vector shift instructions where the last operand is a non-immediate
5055 case Intrinsic::x86_sse2_pslli_w:
5056 case Intrinsic::x86_sse2_pslli_d:
5057 case Intrinsic::x86_sse2_pslli_q:
5058 case Intrinsic::x86_sse2_psrli_w:
5059 case Intrinsic::x86_sse2_psrli_d:
5060 case Intrinsic::x86_sse2_psrli_q:
5061 case Intrinsic::x86_sse2_psrai_w:
5062 case Intrinsic::x86_sse2_psrai_d:
5063 case Intrinsic::x86_mmx_pslli_w:
5064 case Intrinsic::x86_mmx_pslli_d:
5065 case Intrinsic::x86_mmx_pslli_q:
5066 case Intrinsic::x86_mmx_psrli_w:
5067 case Intrinsic::x86_mmx_psrli_d:
5068 case Intrinsic::x86_mmx_psrli_q:
5069 case Intrinsic::x86_mmx_psrai_w:
5070 case Intrinsic::x86_mmx_psrai_d: {
5071 SDOperand ShAmt = Op.getOperand(2);
5072 if (isa<ConstantSDNode>(ShAmt))
5075 unsigned NewIntNo = 0;
5076 MVT::ValueType ShAmtVT = MVT::v4i32;
5078 case Intrinsic::x86_sse2_pslli_w:
5079 NewIntNo = Intrinsic::x86_sse2_psll_w;
5081 case Intrinsic::x86_sse2_pslli_d:
5082 NewIntNo = Intrinsic::x86_sse2_psll_d;
5084 case Intrinsic::x86_sse2_pslli_q:
5085 NewIntNo = Intrinsic::x86_sse2_psll_q;
5087 case Intrinsic::x86_sse2_psrli_w:
5088 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5090 case Intrinsic::x86_sse2_psrli_d:
5091 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5093 case Intrinsic::x86_sse2_psrli_q:
5094 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5096 case Intrinsic::x86_sse2_psrai_w:
5097 NewIntNo = Intrinsic::x86_sse2_psra_w;
5099 case Intrinsic::x86_sse2_psrai_d:
5100 NewIntNo = Intrinsic::x86_sse2_psra_d;
5103 ShAmtVT = MVT::v2i32;
5105 case Intrinsic::x86_mmx_pslli_w:
5106 NewIntNo = Intrinsic::x86_mmx_psll_w;
5108 case Intrinsic::x86_mmx_pslli_d:
5109 NewIntNo = Intrinsic::x86_mmx_psll_d;
5111 case Intrinsic::x86_mmx_pslli_q:
5112 NewIntNo = Intrinsic::x86_mmx_psll_q;
5114 case Intrinsic::x86_mmx_psrli_w:
5115 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5117 case Intrinsic::x86_mmx_psrli_d:
5118 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5120 case Intrinsic::x86_mmx_psrli_q:
5121 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5123 case Intrinsic::x86_mmx_psrai_w:
5124 NewIntNo = Intrinsic::x86_mmx_psra_w;
5126 case Intrinsic::x86_mmx_psrai_d:
5127 NewIntNo = Intrinsic::x86_mmx_psra_d;
5129 default: abort(); // Can't reach here.
5134 MVT::ValueType VT = Op.getValueType();
5135 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5136 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5137 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5138 DAG.getConstant(NewIntNo, MVT::i32),
5139 Op.getOperand(1), ShAmt);
5144 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5145 // Depths > 0 not supported yet!
5146 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5149 // Just load the return address
5150 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5151 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5154 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5155 // Depths > 0 not supported yet!
5156 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5159 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5160 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5161 DAG.getIntPtrConstant(4));
5164 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5165 SelectionDAG &DAG) {
5166 // Is not yet supported on x86-64
5167 if (Subtarget->is64Bit())
5170 return DAG.getIntPtrConstant(8);
5173 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5175 assert(!Subtarget->is64Bit() &&
5176 "Lowering of eh_return builtin is not supported yet on x86-64");
5178 MachineFunction &MF = DAG.getMachineFunction();
5179 SDOperand Chain = Op.getOperand(0);
5180 SDOperand Offset = Op.getOperand(1);
5181 SDOperand Handler = Op.getOperand(2);
5183 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5186 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5187 DAG.getIntPtrConstant(-4UL));
5188 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5189 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5190 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5191 MF.getRegInfo().addLiveOut(X86::ECX);
5193 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5194 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5197 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5198 SelectionDAG &DAG) {
5199 SDOperand Root = Op.getOperand(0);
5200 SDOperand Trmp = Op.getOperand(1); // trampoline
5201 SDOperand FPtr = Op.getOperand(2); // nested function
5202 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5204 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5206 const X86InstrInfo *TII =
5207 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5209 if (Subtarget->is64Bit()) {
5210 SDOperand OutChains[6];
5212 // Large code-model.
5214 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5215 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5217 const unsigned char N86R10 =
5218 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5219 const unsigned char N86R11 =
5220 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5222 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5224 // Load the pointer to the nested function into R11.
5225 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5226 SDOperand Addr = Trmp;
5227 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5230 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5231 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5233 // Load the 'nest' parameter value into R10.
5234 // R10 is specified in X86CallingConv.td
5235 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5236 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5237 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5240 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5241 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5243 // Jump to the nested function.
5244 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5245 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5246 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5249 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5250 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5251 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5255 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5256 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5258 const Function *Func =
5259 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5260 unsigned CC = Func->getCallingConv();
5265 assert(0 && "Unsupported calling convention");
5266 case CallingConv::C:
5267 case CallingConv::X86_StdCall: {
5268 // Pass 'nest' parameter in ECX.
5269 // Must be kept in sync with X86CallingConv.td
5272 // Check that ECX wasn't needed by an 'inreg' parameter.
5273 const FunctionType *FTy = Func->getFunctionType();
5274 const PAListPtr &Attrs = Func->getParamAttrs();
5276 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5277 unsigned InRegCount = 0;
5280 for (FunctionType::param_iterator I = FTy->param_begin(),
5281 E = FTy->param_end(); I != E; ++I, ++Idx)
5282 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5283 // FIXME: should only count parameters that are lowered to integers.
5284 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5286 if (InRegCount > 2) {
5287 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5293 case CallingConv::X86_FastCall:
5294 // Pass 'nest' parameter in EAX.
5295 // Must be kept in sync with X86CallingConv.td
5300 SDOperand OutChains[4];
5301 SDOperand Addr, Disp;
5303 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5304 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5306 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5307 const unsigned char N86Reg =
5308 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5309 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5312 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5313 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5315 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5316 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5317 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5318 TrmpAddr, 5, false, 1);
5320 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5321 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5324 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5325 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5329 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5331 The rounding mode is in bits 11:10 of FPSR, and has the following
5338 FLT_ROUNDS, on the other hand, expects the following:
5345 To perform the conversion, we do:
5346 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5349 MachineFunction &MF = DAG.getMachineFunction();
5350 const TargetMachine &TM = MF.getTarget();
5351 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5352 unsigned StackAlignment = TFI.getStackAlignment();
5353 MVT::ValueType VT = Op.getValueType();
5355 // Save FP Control Word to stack slot
5356 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5357 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5359 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5360 DAG.getEntryNode(), StackSlot);
5362 // Load FP Control Word from stack slot
5363 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5365 // Transform as necessary
5367 DAG.getNode(ISD::SRL, MVT::i16,
5368 DAG.getNode(ISD::AND, MVT::i16,
5369 CWD, DAG.getConstant(0x800, MVT::i16)),
5370 DAG.getConstant(11, MVT::i8));
5372 DAG.getNode(ISD::SRL, MVT::i16,
5373 DAG.getNode(ISD::AND, MVT::i16,
5374 CWD, DAG.getConstant(0x400, MVT::i16)),
5375 DAG.getConstant(9, MVT::i8));
5378 DAG.getNode(ISD::AND, MVT::i16,
5379 DAG.getNode(ISD::ADD, MVT::i16,
5380 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5381 DAG.getConstant(1, MVT::i16)),
5382 DAG.getConstant(3, MVT::i16));
5385 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5386 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5389 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5390 MVT::ValueType VT = Op.getValueType();
5391 MVT::ValueType OpVT = VT;
5392 unsigned NumBits = MVT::getSizeInBits(VT);
5394 Op = Op.getOperand(0);
5395 if (VT == MVT::i8) {
5396 // Zero extend to i32 since there is not an i8 bsr.
5398 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5401 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5402 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5403 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5405 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5406 SmallVector<SDOperand, 4> Ops;
5408 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5409 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5410 Ops.push_back(Op.getValue(1));
5411 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5413 // Finally xor with NumBits-1.
5414 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5417 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5421 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5422 MVT::ValueType VT = Op.getValueType();
5423 MVT::ValueType OpVT = VT;
5424 unsigned NumBits = MVT::getSizeInBits(VT);
5426 Op = Op.getOperand(0);
5427 if (VT == MVT::i8) {
5429 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5432 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5433 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5434 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5436 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5437 SmallVector<SDOperand, 4> Ops;
5439 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5440 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5441 Ops.push_back(Op.getValue(1));
5442 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5445 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5449 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5450 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5454 case MVT::i8: Reg = X86::AL; size = 1; break;
5455 case MVT::i16: Reg = X86::AX; size = 2; break;
5456 case MVT::i32: Reg = X86::EAX; size = 4; break;
5458 if (Subtarget->is64Bit()) {
5459 Reg = X86::RAX; size = 8;
5460 } else //Should go away when LowerType stuff lands
5461 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5464 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5465 Op.getOperand(3), SDOperand());
5466 SDOperand Ops[] = { cpIn.getValue(0),
5469 DAG.getTargetConstant(size, MVT::i8),
5471 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5472 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5474 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5478 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5479 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5480 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5481 SDOperand cpInL, cpInH;
5482 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5483 DAG.getConstant(0, MVT::i32));
5484 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5485 DAG.getConstant(1, MVT::i32));
5486 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5487 cpInL, SDOperand());
5488 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5489 cpInH, cpInL.getValue(1));
5490 SDOperand swapInL, swapInH;
5491 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5492 DAG.getConstant(0, MVT::i32));
5493 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5494 DAG.getConstant(1, MVT::i32));
5495 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5496 swapInL, cpInH.getValue(1));
5497 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5498 swapInH, swapInL.getValue(1));
5499 SDOperand Ops[] = { swapInH.getValue(0),
5501 swapInH.getValue(1)};
5502 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5503 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5504 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5505 Result.getValue(1));
5506 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5507 cpOutL.getValue(2));
5508 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5509 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5510 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5511 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5514 /// LowerOperation - Provide custom lowering hooks for some operations.
5516 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5517 switch (Op.getOpcode()) {
5518 default: assert(0 && "Should not custom lower this!");
5519 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5520 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5521 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5522 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5523 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5524 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5525 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5526 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5527 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5528 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5529 case ISD::SHL_PARTS:
5530 case ISD::SRA_PARTS:
5531 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5532 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5533 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5534 case ISD::FABS: return LowerFABS(Op, DAG);
5535 case ISD::FNEG: return LowerFNEG(Op, DAG);
5536 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5537 case ISD::SETCC: return LowerSETCC(Op, DAG);
5538 case ISD::SELECT: return LowerSELECT(Op, DAG);
5539 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5540 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5541 case ISD::CALL: return LowerCALL(Op, DAG);
5542 case ISD::RET: return LowerRET(Op, DAG);
5543 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5544 case ISD::VASTART: return LowerVASTART(Op, DAG);
5545 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5546 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5547 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5548 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5549 case ISD::FRAME_TO_ARGS_OFFSET:
5550 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5551 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5552 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5553 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5554 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5555 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5556 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5558 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5559 case ISD::READCYCLECOUNTER:
5560 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5564 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5565 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5566 switch (N->getOpcode()) {
5567 default: assert(0 && "Should not custom lower this!");
5568 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5569 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5570 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5574 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5576 default: return NULL;
5577 case X86ISD::BSF: return "X86ISD::BSF";
5578 case X86ISD::BSR: return "X86ISD::BSR";
5579 case X86ISD::SHLD: return "X86ISD::SHLD";
5580 case X86ISD::SHRD: return "X86ISD::SHRD";
5581 case X86ISD::FAND: return "X86ISD::FAND";
5582 case X86ISD::FOR: return "X86ISD::FOR";
5583 case X86ISD::FXOR: return "X86ISD::FXOR";
5584 case X86ISD::FSRL: return "X86ISD::FSRL";
5585 case X86ISD::FILD: return "X86ISD::FILD";
5586 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5587 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5588 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5589 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5590 case X86ISD::FLD: return "X86ISD::FLD";
5591 case X86ISD::FST: return "X86ISD::FST";
5592 case X86ISD::CALL: return "X86ISD::CALL";
5593 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5594 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5595 case X86ISD::CMP: return "X86ISD::CMP";
5596 case X86ISD::COMI: return "X86ISD::COMI";
5597 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5598 case X86ISD::SETCC: return "X86ISD::SETCC";
5599 case X86ISD::CMOV: return "X86ISD::CMOV";
5600 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5601 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5602 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5603 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5604 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5605 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5606 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5607 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5608 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5609 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5610 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5611 case X86ISD::FMAX: return "X86ISD::FMAX";
5612 case X86ISD::FMIN: return "X86ISD::FMIN";
5613 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5614 case X86ISD::FRCP: return "X86ISD::FRCP";
5615 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5616 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5617 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5618 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5619 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5620 case X86ISD::LCMPXCHG_DAG: return "x86ISD::LCMPXCHG_DAG";
5621 case X86ISD::LCMPXCHG8_DAG: return "x86ISD::LCMPXCHG8_DAG";
5625 // isLegalAddressingMode - Return true if the addressing mode represented
5626 // by AM is legal for this target, for a load/store of the specified type.
5627 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5628 const Type *Ty) const {
5629 // X86 supports extremely general addressing modes.
5631 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5632 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5636 // We can only fold this if we don't need an extra load.
5637 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5640 // X86-64 only supports addr of globals in small code model.
5641 if (Subtarget->is64Bit()) {
5642 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5644 // If lower 4G is not available, then we must use rip-relative addressing.
5645 if (AM.BaseOffs || AM.Scale > 1)
5656 // These scales always work.
5661 // These scales are formed with basereg+scalereg. Only accept if there is
5666 default: // Other stuff never works.
5674 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5675 if (!Ty1->isInteger() || !Ty2->isInteger())
5677 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5678 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5679 if (NumBits1 <= NumBits2)
5681 return Subtarget->is64Bit() || NumBits1 < 64;
5684 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5685 MVT::ValueType VT2) const {
5686 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5688 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5689 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5690 if (NumBits1 <= NumBits2)
5692 return Subtarget->is64Bit() || NumBits1 < 64;
5695 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5696 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5697 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5698 /// are assumed to be legal.
5700 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5701 // Only do shuffles on 128-bit vector types for now.
5702 if (MVT::getSizeInBits(VT) == 64) return false;
5703 return (Mask.Val->getNumOperands() <= 4 ||
5704 isIdentityMask(Mask.Val) ||
5705 isIdentityMask(Mask.Val, true) ||
5706 isSplatMask(Mask.Val) ||
5707 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5708 X86::isUNPCKLMask(Mask.Val) ||
5709 X86::isUNPCKHMask(Mask.Val) ||
5710 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5711 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5715 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5717 SelectionDAG &DAG) const {
5718 unsigned NumElts = BVOps.size();
5719 // Only do shuffles on 128-bit vector types for now.
5720 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5721 if (NumElts == 2) return true;
5723 return (isMOVLMask(&BVOps[0], 4) ||
5724 isCommutedMOVL(&BVOps[0], 4, true) ||
5725 isSHUFPMask(&BVOps[0], 4) ||
5726 isCommutedSHUFP(&BVOps[0], 4));
5731 //===----------------------------------------------------------------------===//
5732 // X86 Scheduler Hooks
5733 //===----------------------------------------------------------------------===//
5736 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5737 MachineBasicBlock *BB) {
5738 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5739 switch (MI->getOpcode()) {
5740 default: assert(false && "Unexpected instr type to insert");
5741 case X86::CMOV_FR32:
5742 case X86::CMOV_FR64:
5743 case X86::CMOV_V4F32:
5744 case X86::CMOV_V2F64:
5745 case X86::CMOV_V2I64: {
5746 // To "insert" a SELECT_CC instruction, we actually have to insert the
5747 // diamond control-flow pattern. The incoming instruction knows the
5748 // destination vreg to set, the condition code register to branch on, the
5749 // true/false values to select between, and a branch opcode to use.
5750 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5751 ilist<MachineBasicBlock>::iterator It = BB;
5757 // cmpTY ccX, r1, r2
5759 // fallthrough --> copy0MBB
5760 MachineBasicBlock *thisMBB = BB;
5761 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5762 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5764 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5765 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5766 MachineFunction *F = BB->getParent();
5767 F->getBasicBlockList().insert(It, copy0MBB);
5768 F->getBasicBlockList().insert(It, sinkMBB);
5769 // Update machine-CFG edges by first adding all successors of the current
5770 // block to the new block which will contain the Phi node for the select.
5771 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5772 e = BB->succ_end(); i != e; ++i)
5773 sinkMBB->addSuccessor(*i);
5774 // Next, remove all successors of the current block, and add the true
5775 // and fallthrough blocks as its successors.
5776 while(!BB->succ_empty())
5777 BB->removeSuccessor(BB->succ_begin());
5778 BB->addSuccessor(copy0MBB);
5779 BB->addSuccessor(sinkMBB);
5782 // %FalseValue = ...
5783 // # fallthrough to sinkMBB
5786 // Update machine-CFG edges
5787 BB->addSuccessor(sinkMBB);
5790 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5793 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5794 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5795 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5797 delete MI; // The pseudo instruction is gone now.
5801 case X86::FP32_TO_INT16_IN_MEM:
5802 case X86::FP32_TO_INT32_IN_MEM:
5803 case X86::FP32_TO_INT64_IN_MEM:
5804 case X86::FP64_TO_INT16_IN_MEM:
5805 case X86::FP64_TO_INT32_IN_MEM:
5806 case X86::FP64_TO_INT64_IN_MEM:
5807 case X86::FP80_TO_INT16_IN_MEM:
5808 case X86::FP80_TO_INT32_IN_MEM:
5809 case X86::FP80_TO_INT64_IN_MEM: {
5810 // Change the floating point control register to use "round towards zero"
5811 // mode when truncating to an integer value.
5812 MachineFunction *F = BB->getParent();
5813 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5814 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5816 // Load the old value of the high byte of the control word...
5818 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5819 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5821 // Set the high part to be round to zero...
5822 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5825 // Reload the modified control word now...
5826 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5828 // Restore the memory image of control word to original value
5829 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5832 // Get the X86 opcode to use.
5834 switch (MI->getOpcode()) {
5835 default: assert(0 && "illegal opcode!");
5836 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5837 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5838 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5839 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5840 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5841 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5842 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5843 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5844 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5848 MachineOperand &Op = MI->getOperand(0);
5849 if (Op.isRegister()) {
5850 AM.BaseType = X86AddressMode::RegBase;
5851 AM.Base.Reg = Op.getReg();
5853 AM.BaseType = X86AddressMode::FrameIndexBase;
5854 AM.Base.FrameIndex = Op.getIndex();
5856 Op = MI->getOperand(1);
5857 if (Op.isImmediate())
5858 AM.Scale = Op.getImm();
5859 Op = MI->getOperand(2);
5860 if (Op.isImmediate())
5861 AM.IndexReg = Op.getImm();
5862 Op = MI->getOperand(3);
5863 if (Op.isGlobalAddress()) {
5864 AM.GV = Op.getGlobal();
5866 AM.Disp = Op.getImm();
5868 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5869 .addReg(MI->getOperand(4).getReg());
5871 // Reload the original control word now.
5872 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5874 delete MI; // The pseudo instruction is gone now.
5880 //===----------------------------------------------------------------------===//
5881 // X86 Optimization Hooks
5882 //===----------------------------------------------------------------------===//
5884 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5888 const SelectionDAG &DAG,
5889 unsigned Depth) const {
5890 unsigned Opc = Op.getOpcode();
5891 assert((Opc >= ISD::BUILTIN_OP_END ||
5892 Opc == ISD::INTRINSIC_WO_CHAIN ||
5893 Opc == ISD::INTRINSIC_W_CHAIN ||
5894 Opc == ISD::INTRINSIC_VOID) &&
5895 "Should use MaskedValueIsZero if you don't know whether Op"
5896 " is a target node!");
5898 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5902 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5903 Mask.getBitWidth() - 1);
5908 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5909 /// element of the result of the vector shuffle.
5910 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5911 MVT::ValueType VT = N->getValueType(0);
5912 SDOperand PermMask = N->getOperand(2);
5913 unsigned NumElems = PermMask.getNumOperands();
5914 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5916 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5918 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5919 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5920 SDOperand Idx = PermMask.getOperand(i);
5921 if (Idx.getOpcode() == ISD::UNDEF)
5922 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5923 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5928 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5929 /// node is a GlobalAddress + an offset.
5930 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5931 unsigned Opc = N->getOpcode();
5932 if (Opc == X86ISD::Wrapper) {
5933 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5934 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5937 } else if (Opc == ISD::ADD) {
5938 SDOperand N1 = N->getOperand(0);
5939 SDOperand N2 = N->getOperand(1);
5940 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5941 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5943 Offset += V->getSignExtended();
5946 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5947 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5949 Offset += V->getSignExtended();
5957 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5959 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5960 MachineFrameInfo *MFI) {
5961 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5964 SDOperand Loc = N->getOperand(1);
5965 SDOperand BaseLoc = Base->getOperand(1);
5966 if (Loc.getOpcode() == ISD::FrameIndex) {
5967 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5969 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5970 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5971 int FS = MFI->getObjectSize(FI);
5972 int BFS = MFI->getObjectSize(BFI);
5973 if (FS != BFS || FS != Size) return false;
5974 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5976 GlobalValue *GV1 = NULL;
5977 GlobalValue *GV2 = NULL;
5978 int64_t Offset1 = 0;
5979 int64_t Offset2 = 0;
5980 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5981 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5982 if (isGA1 && isGA2 && GV1 == GV2)
5983 return Offset1 == (Offset2 + Dist*Size);
5989 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5990 const X86Subtarget *Subtarget) {
5993 if (isGAPlusOffset(Base, GV, Offset))
5994 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5995 // DAG combine handles the stack object case.
6000 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6001 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6002 /// if the load addresses are consecutive, non-overlapping, and in the right
6004 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6005 const X86Subtarget *Subtarget) {
6006 MachineFunction &MF = DAG.getMachineFunction();
6007 MachineFrameInfo *MFI = MF.getFrameInfo();
6008 MVT::ValueType VT = N->getValueType(0);
6009 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6010 SDOperand PermMask = N->getOperand(2);
6011 int NumElems = (int)PermMask.getNumOperands();
6012 SDNode *Base = NULL;
6013 for (int i = 0; i < NumElems; ++i) {
6014 SDOperand Idx = PermMask.getOperand(i);
6015 if (Idx.getOpcode() == ISD::UNDEF) {
6016 if (!Base) return SDOperand();
6019 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
6020 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
6024 else if (!isConsecutiveLoad(Arg.Val, Base,
6025 i, MVT::getSizeInBits(EVT)/8,MFI))
6030 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
6031 LoadSDNode *LD = cast<LoadSDNode>(Base);
6033 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6034 LD->getSrcValueOffset(), LD->isVolatile());
6036 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6037 LD->getSrcValueOffset(), LD->isVolatile(),
6038 LD->getAlignment());
6042 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6043 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6044 const X86Subtarget *Subtarget) {
6045 SDOperand Cond = N->getOperand(0);
6047 // If we have SSE[12] support, try to form min/max nodes.
6048 if (Subtarget->hasSSE2() &&
6049 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6050 if (Cond.getOpcode() == ISD::SETCC) {
6051 // Get the LHS/RHS of the select.
6052 SDOperand LHS = N->getOperand(1);
6053 SDOperand RHS = N->getOperand(2);
6054 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6056 unsigned Opcode = 0;
6057 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6060 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6063 if (!UnsafeFPMath) break;
6065 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6067 Opcode = X86ISD::FMIN;
6070 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6073 if (!UnsafeFPMath) break;
6075 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6077 Opcode = X86ISD::FMAX;
6080 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6083 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6086 if (!UnsafeFPMath) break;
6088 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6090 Opcode = X86ISD::FMIN;
6093 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6096 if (!UnsafeFPMath) break;
6098 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6100 Opcode = X86ISD::FMAX;
6106 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6114 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6115 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
6116 const X86Subtarget *Subtarget) {
6117 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6118 // the FP state in cases where an emms may be missing.
6119 // A preferable solution to the general problem is to figure out the right
6120 // places to insert EMMS. This qualifies as a quick hack.
6121 if (MVT::isVector(St->getValue().getValueType()) &&
6122 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6123 isa<LoadSDNode>(St->getValue()) &&
6124 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6125 St->getChain().hasOneUse() && !St->isVolatile()) {
6126 SDNode* LdVal = St->getValue().Val;
6128 int TokenFactorIndex = -1;
6129 SmallVector<SDOperand, 8> Ops;
6130 SDNode* ChainVal = St->getChain().Val;
6131 // Must be a store of a load. We currently handle two cases: the load
6132 // is a direct child, and it's under an intervening TokenFactor. It is
6133 // possible to dig deeper under nested TokenFactors.
6134 if (ChainVal == LdVal)
6135 Ld = cast<LoadSDNode>(St->getChain());
6136 else if (St->getValue().hasOneUse() &&
6137 ChainVal->getOpcode() == ISD::TokenFactor) {
6138 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6139 if (ChainVal->getOperand(i).Val == LdVal) {
6140 TokenFactorIndex = i;
6141 Ld = cast<LoadSDNode>(St->getValue());
6143 Ops.push_back(ChainVal->getOperand(i));
6147 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6148 if (Subtarget->is64Bit()) {
6149 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6150 Ld->getBasePtr(), Ld->getSrcValue(),
6151 Ld->getSrcValueOffset(), Ld->isVolatile(),
6152 Ld->getAlignment());
6153 SDOperand NewChain = NewLd.getValue(1);
6154 if (TokenFactorIndex != -1) {
6155 Ops.push_back(NewChain);
6156 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6159 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6160 St->getSrcValue(), St->getSrcValueOffset(),
6161 St->isVolatile(), St->getAlignment());
6164 // Otherwise, lower to two 32-bit copies.
6165 SDOperand LoAddr = Ld->getBasePtr();
6166 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6167 DAG.getConstant(MVT::i32, 4));
6169 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6170 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6171 Ld->isVolatile(), Ld->getAlignment());
6172 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6173 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6175 MinAlign(Ld->getAlignment(), 4));
6177 SDOperand NewChain = LoLd.getValue(1);
6178 if (TokenFactorIndex != -1) {
6179 Ops.push_back(LoLd);
6180 Ops.push_back(HiLd);
6181 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6185 LoAddr = St->getBasePtr();
6186 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6187 DAG.getConstant(MVT::i32, 4));
6189 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6190 St->getSrcValue(), St->getSrcValueOffset(),
6191 St->isVolatile(), St->getAlignment());
6192 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6193 St->getSrcValue(), St->getSrcValueOffset()+4,
6195 MinAlign(St->getAlignment(), 4));
6196 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6202 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6203 /// X86ISD::FXOR nodes.
6204 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6205 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6206 // F[X]OR(0.0, x) -> x
6207 // F[X]OR(x, 0.0) -> x
6208 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6209 if (C->getValueAPF().isPosZero())
6210 return N->getOperand(1);
6211 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6212 if (C->getValueAPF().isPosZero())
6213 return N->getOperand(0);
6217 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6218 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6219 // FAND(0.0, x) -> 0.0
6220 // FAND(x, 0.0) -> 0.0
6221 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6222 if (C->getValueAPF().isPosZero())
6223 return N->getOperand(0);
6224 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6225 if (C->getValueAPF().isPosZero())
6226 return N->getOperand(1);
6231 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6232 DAGCombinerInfo &DCI) const {
6233 SelectionDAG &DAG = DCI.DAG;
6234 switch (N->getOpcode()) {
6236 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6237 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6239 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6241 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6242 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6248 //===----------------------------------------------------------------------===//
6249 // X86 Inline Assembly Support
6250 //===----------------------------------------------------------------------===//
6252 /// getConstraintType - Given a constraint letter, return the type of
6253 /// constraint it is for this target.
6254 X86TargetLowering::ConstraintType
6255 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6256 if (Constraint.size() == 1) {
6257 switch (Constraint[0]) {
6268 return C_RegisterClass;
6273 return TargetLowering::getConstraintType(Constraint);
6276 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6277 /// with another that has more specific requirements based on the type of the
6278 /// corresponding operand.
6279 const char *X86TargetLowering::
6280 LowerXConstraint(MVT::ValueType ConstraintVT) const {
6281 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6282 // 'f' like normal targets.
6283 if (MVT::isFloatingPoint(ConstraintVT)) {
6284 if (Subtarget->hasSSE2())
6286 if (Subtarget->hasSSE1())
6290 return TargetLowering::LowerXConstraint(ConstraintVT);
6293 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6294 /// vector. If it is invalid, don't add anything to Ops.
6295 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6297 std::vector<SDOperand>&Ops,
6298 SelectionDAG &DAG) const {
6299 SDOperand Result(0, 0);
6301 switch (Constraint) {
6304 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6305 if (C->getValue() <= 31) {
6306 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6312 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6313 if (C->getValue() <= 255) {
6314 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6320 // Literal immediates are always ok.
6321 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6322 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6326 // If we are in non-pic codegen mode, we allow the address of a global (with
6327 // an optional displacement) to be used with 'i'.
6328 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6331 // Match either (GA) or (GA+C)
6333 Offset = GA->getOffset();
6334 } else if (Op.getOpcode() == ISD::ADD) {
6335 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6336 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6338 Offset = GA->getOffset()+C->getValue();
6340 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6341 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6343 Offset = GA->getOffset()+C->getValue();
6350 // If addressing this global requires a load (e.g. in PIC mode), we can't
6352 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6356 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6362 // Otherwise, not valid for this mode.
6368 Ops.push_back(Result);
6371 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6374 std::vector<unsigned> X86TargetLowering::
6375 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6376 MVT::ValueType VT) const {
6377 if (Constraint.size() == 1) {
6378 // FIXME: not handling fp-stack yet!
6379 switch (Constraint[0]) { // GCC X86 Constraint Letters
6380 default: break; // Unknown constraint letter
6381 case 'A': // EAX/EDX
6382 if (VT == MVT::i32 || VT == MVT::i64)
6383 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6385 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6388 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6389 else if (VT == MVT::i16)
6390 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6391 else if (VT == MVT::i8)
6392 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6393 else if (VT == MVT::i64)
6394 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6399 return std::vector<unsigned>();
6402 std::pair<unsigned, const TargetRegisterClass*>
6403 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6404 MVT::ValueType VT) const {
6405 // First, see if this is a constraint that directly corresponds to an LLVM
6407 if (Constraint.size() == 1) {
6408 // GCC Constraint Letters
6409 switch (Constraint[0]) {
6411 case 'r': // GENERAL_REGS
6412 case 'R': // LEGACY_REGS
6413 case 'l': // INDEX_REGS
6414 if (VT == MVT::i64 && Subtarget->is64Bit())
6415 return std::make_pair(0U, X86::GR64RegisterClass);
6417 return std::make_pair(0U, X86::GR32RegisterClass);
6418 else if (VT == MVT::i16)
6419 return std::make_pair(0U, X86::GR16RegisterClass);
6420 else if (VT == MVT::i8)
6421 return std::make_pair(0U, X86::GR8RegisterClass);
6423 case 'f': // FP Stack registers.
6424 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6425 // value to the correct fpstack register class.
6426 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6427 return std::make_pair(0U, X86::RFP32RegisterClass);
6428 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6429 return std::make_pair(0U, X86::RFP64RegisterClass);
6430 return std::make_pair(0U, X86::RFP80RegisterClass);
6431 case 'y': // MMX_REGS if MMX allowed.
6432 if (!Subtarget->hasMMX()) break;
6433 return std::make_pair(0U, X86::VR64RegisterClass);
6435 case 'Y': // SSE_REGS if SSE2 allowed
6436 if (!Subtarget->hasSSE2()) break;
6438 case 'x': // SSE_REGS if SSE1 allowed
6439 if (!Subtarget->hasSSE1()) break;
6443 // Scalar SSE types.
6446 return std::make_pair(0U, X86::FR32RegisterClass);
6449 return std::make_pair(0U, X86::FR64RegisterClass);
6457 return std::make_pair(0U, X86::VR128RegisterClass);
6463 // Use the default implementation in TargetLowering to convert the register
6464 // constraint into a member of a register class.
6465 std::pair<unsigned, const TargetRegisterClass*> Res;
6466 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6468 // Not found as a standard register?
6469 if (Res.second == 0) {
6470 // GCC calls "st(0)" just plain "st".
6471 if (StringsEqualNoCase("{st}", Constraint)) {
6472 Res.first = X86::ST0;
6473 Res.second = X86::RFP80RegisterClass;
6479 // Otherwise, check to see if this is a register class of the wrong value
6480 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6481 // turn into {ax},{dx}.
6482 if (Res.second->hasType(VT))
6483 return Res; // Correct type already, nothing to do.
6485 // All of the single-register GCC register classes map their values onto
6486 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6487 // really want an 8-bit or 32-bit register, map to the appropriate register
6488 // class and return the appropriate register.
6489 if (Res.second != X86::GR16RegisterClass)
6492 if (VT == MVT::i8) {
6493 unsigned DestReg = 0;
6494 switch (Res.first) {
6496 case X86::AX: DestReg = X86::AL; break;
6497 case X86::DX: DestReg = X86::DL; break;
6498 case X86::CX: DestReg = X86::CL; break;
6499 case X86::BX: DestReg = X86::BL; break;
6502 Res.first = DestReg;
6503 Res.second = Res.second = X86::GR8RegisterClass;
6505 } else if (VT == MVT::i32) {
6506 unsigned DestReg = 0;
6507 switch (Res.first) {
6509 case X86::AX: DestReg = X86::EAX; break;
6510 case X86::DX: DestReg = X86::EDX; break;
6511 case X86::CX: DestReg = X86::ECX; break;
6512 case X86::BX: DestReg = X86::EBX; break;
6513 case X86::SI: DestReg = X86::ESI; break;
6514 case X86::DI: DestReg = X86::EDI; break;
6515 case X86::BP: DestReg = X86::EBP; break;
6516 case X86::SP: DestReg = X86::ESP; break;
6519 Res.first = DestReg;
6520 Res.second = Res.second = X86::GR32RegisterClass;
6522 } else if (VT == MVT::i64) {
6523 unsigned DestReg = 0;
6524 switch (Res.first) {
6526 case X86::AX: DestReg = X86::RAX; break;
6527 case X86::DX: DestReg = X86::RDX; break;
6528 case X86::CX: DestReg = X86::RCX; break;
6529 case X86::BX: DestReg = X86::RBX; break;
6530 case X86::SI: DestReg = X86::RSI; break;
6531 case X86::DI: DestReg = X86::RDI; break;
6532 case X86::BP: DestReg = X86::RBP; break;
6533 case X86::SP: DestReg = X86::RSP; break;
6536 Res.first = DestReg;
6537 Res.second = Res.second = X86::GR64RegisterClass;