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"
42 #include "llvm/ParamAttrsList.h"
45 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
46 : TargetLowering(TM) {
47 Subtarget = &TM.getSubtarget<X86Subtarget>();
48 X86ScalarSSEf64 = Subtarget->hasSSE2();
49 X86ScalarSSEf32 = Subtarget->hasSSE1();
50 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
54 RegInfo = TM.getRegisterInfo();
56 // Set up the TargetLowering object.
58 // X86 is weird, it always uses i8 for shift amounts and setcc results.
59 setShiftAmountType(MVT::i8);
60 setSetCCResultType(MVT::i8);
61 setSetCCResultContents(ZeroOrOneSetCCResult);
62 setSchedulingPreference(SchedulingForRegPressure);
63 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
64 setStackPointerRegisterToSaveRestore(X86StackPtr);
66 if (Subtarget->isTargetDarwin()) {
67 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
68 setUseUnderscoreSetJmp(false);
69 setUseUnderscoreLongJmp(false);
70 } else if (Subtarget->isTargetMingw()) {
71 // MS runtime is weird: it exports _setjmp, but longjmp!
72 setUseUnderscoreSetJmp(true);
73 setUseUnderscoreLongJmp(false);
75 setUseUnderscoreSetJmp(true);
76 setUseUnderscoreLongJmp(true);
79 // Set up the register classes.
80 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
81 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
82 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
83 if (Subtarget->is64Bit())
84 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
86 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
88 // We don't accept any truncstore of integer registers.
89 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
90 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
92 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
93 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
94 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
96 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
98 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
99 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
102 if (Subtarget->is64Bit()) {
103 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
104 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
107 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
108 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
110 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
113 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
115 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
116 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
117 // SSE has no i16 to fp conversion, only i32
118 if (X86ScalarSSEf32) {
119 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
120 // f32 and f64 cases are Legal, f80 case is not
121 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
123 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
124 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
127 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
128 // are Legal, f80 is custom lowered.
129 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
130 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
132 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
134 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
135 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
137 if (X86ScalarSSEf32) {
138 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
139 // f32 and f64 cases are Legal, f80 case is not
140 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
142 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
143 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
146 // Handle FP_TO_UINT by promoting the destination to a larger signed
148 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
149 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
150 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
152 if (Subtarget->is64Bit()) {
153 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
154 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
156 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
157 // Expand FP_TO_UINT into a select.
158 // FIXME: We would like to use a Custom expander here eventually to do
159 // the optimal thing for SSE vs. the default expansion in the legalizer.
160 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
162 // With SSE3 we can use fisttpll to convert to a signed i64.
163 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
166 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
167 if (!X86ScalarSSEf64) {
168 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
169 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
172 // Scalar integer divide and remainder are lowered to use operations that
173 // produce two results, to match the available instructions. This exposes
174 // the two-result form to trivial CSE, which is able to combine x/y and x%y
175 // into a single instruction.
177 // Scalar integer multiply-high is also lowered to use two-result
178 // operations, to match the available instructions. However, plain multiply
179 // (low) operations are left as Legal, as there are single-result
180 // instructions for this in x86. Using the two-result multiply instructions
181 // when both high and low results are needed must be arranged by dagcombine.
182 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
183 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
184 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
185 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
186 setOperationAction(ISD::SREM , MVT::i8 , Expand);
187 setOperationAction(ISD::UREM , MVT::i8 , Expand);
188 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
189 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
190 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
191 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
192 setOperationAction(ISD::SREM , MVT::i16 , Expand);
193 setOperationAction(ISD::UREM , MVT::i16 , Expand);
194 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
195 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
196 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
197 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
198 setOperationAction(ISD::SREM , MVT::i32 , Expand);
199 setOperationAction(ISD::UREM , MVT::i32 , Expand);
200 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
201 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
202 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
203 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::SREM , MVT::i64 , Expand);
205 setOperationAction(ISD::UREM , MVT::i64 , Expand);
207 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
208 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
209 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
210 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
211 setOperationAction(ISD::MEMMOVE , 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::f64 , Expand);
219 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
221 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
222 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
223 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
224 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
225 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
226 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
227 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
228 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
229 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
230 if (Subtarget->is64Bit()) {
231 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
232 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
233 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
236 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
237 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
239 // These should be promoted to a larger select which is supported.
240 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
241 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
242 // X86 wants to expand cmov itself.
243 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
244 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
245 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
246 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
248 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
249 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
251 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
252 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
256 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
258 // X86 ret instruction may pop stack.
259 setOperationAction(ISD::RET , MVT::Other, Custom);
260 if (!Subtarget->is64Bit())
261 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
264 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
265 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
266 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
268 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
269 if (Subtarget->is64Bit()) {
270 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
271 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
272 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
273 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
275 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
276 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
277 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
278 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
279 // X86 wants to expand memset / memcpy itself.
280 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
281 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
283 if (!Subtarget->hasSSE2())
284 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
287 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
288 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
289 // FIXME - use subtarget debug flags
290 if (!Subtarget->isTargetDarwin() &&
291 !Subtarget->isTargetELF() &&
292 !Subtarget->isTargetCygMing())
293 setOperationAction(ISD::LABEL, MVT::Other, Expand);
295 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
296 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
297 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
298 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
299 if (Subtarget->is64Bit()) {
301 setExceptionPointerRegister(X86::RAX);
302 setExceptionSelectorRegister(X86::RDX);
304 setExceptionPointerRegister(X86::EAX);
305 setExceptionSelectorRegister(X86::EDX);
307 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
309 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
311 setOperationAction(ISD::TRAP, MVT::Other, Legal);
313 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
314 setOperationAction(ISD::VASTART , MVT::Other, Custom);
315 setOperationAction(ISD::VAARG , MVT::Other, Expand);
316 setOperationAction(ISD::VAEND , MVT::Other, Expand);
317 if (Subtarget->is64Bit())
318 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
320 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
322 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
323 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
324 if (Subtarget->is64Bit())
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
326 if (Subtarget->isTargetCygMing())
327 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
331 if (X86ScalarSSEf64) {
332 // f32 and f64 use SSE.
333 // Set up the FP register classes.
334 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
335 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
337 // Use ANDPD to simulate FABS.
338 setOperationAction(ISD::FABS , MVT::f64, Custom);
339 setOperationAction(ISD::FABS , MVT::f32, Custom);
341 // Use XORP to simulate FNEG.
342 setOperationAction(ISD::FNEG , MVT::f64, Custom);
343 setOperationAction(ISD::FNEG , MVT::f32, Custom);
345 // Use ANDPD and ORPD to simulate FCOPYSIGN.
346 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
347 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
349 // We don't support sin/cos/fmod
350 setOperationAction(ISD::FSIN , MVT::f64, Expand);
351 setOperationAction(ISD::FCOS , MVT::f64, Expand);
352 setOperationAction(ISD::FREM , MVT::f64, Expand);
353 setOperationAction(ISD::FSIN , MVT::f32, Expand);
354 setOperationAction(ISD::FCOS , MVT::f32, Expand);
355 setOperationAction(ISD::FREM , MVT::f32, Expand);
357 // Expand FP immediates into loads from the stack, except for the special
359 addLegalFPImmediate(APFloat(+0.0)); // xorpd
360 addLegalFPImmediate(APFloat(+0.0f)); // xorps
362 // Floating truncations from f80 and extensions to f80 go through memory.
363 // If optimizing, we lie about this though and handle it in
364 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
366 setConvertAction(MVT::f32, MVT::f80, Expand);
367 setConvertAction(MVT::f64, MVT::f80, Expand);
368 setConvertAction(MVT::f80, MVT::f32, Expand);
369 setConvertAction(MVT::f80, MVT::f64, Expand);
371 } else if (X86ScalarSSEf32) {
372 // Use SSE for f32, x87 for f64.
373 // Set up the FP register classes.
374 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
375 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
377 // Use ANDPS to simulate FABS.
378 setOperationAction(ISD::FABS , MVT::f32, Custom);
380 // Use XORP to simulate FNEG.
381 setOperationAction(ISD::FNEG , MVT::f32, Custom);
383 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
385 // Use ANDPS and ORPS to simulate FCOPYSIGN.
386 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
387 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
389 // We don't support sin/cos/fmod
390 setOperationAction(ISD::FSIN , MVT::f32, Expand);
391 setOperationAction(ISD::FCOS , MVT::f32, Expand);
392 setOperationAction(ISD::FREM , MVT::f32, Expand);
394 // Special cases we handle for FP constants.
395 addLegalFPImmediate(APFloat(+0.0f)); // xorps
396 addLegalFPImmediate(APFloat(+0.0)); // FLD0
397 addLegalFPImmediate(APFloat(+1.0)); // FLD1
398 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
399 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
401 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
402 // this though and handle it in InstructionSelectPreprocess so that
403 // dagcombine2 can hack on these.
405 setConvertAction(MVT::f32, MVT::f64, Expand);
406 setConvertAction(MVT::f32, MVT::f80, Expand);
407 setConvertAction(MVT::f80, MVT::f32, Expand);
408 setConvertAction(MVT::f64, MVT::f32, Expand);
409 // And x87->x87 truncations also.
410 setConvertAction(MVT::f80, MVT::f64, Expand);
414 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
415 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
418 // f32 and f64 in x87.
419 // Set up the FP register classes.
420 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
421 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
423 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
424 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
425 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
426 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
428 // Floating truncations go through memory. If optimizing, we lie about
429 // this though and handle it in InstructionSelectPreprocess so that
430 // dagcombine2 can hack on these.
432 setConvertAction(MVT::f80, MVT::f32, Expand);
433 setConvertAction(MVT::f64, MVT::f32, Expand);
434 setConvertAction(MVT::f80, MVT::f64, Expand);
438 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
439 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
441 addLegalFPImmediate(APFloat(+0.0)); // FLD0
442 addLegalFPImmediate(APFloat(+1.0)); // FLD1
443 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
444 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
445 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
446 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
447 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
448 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
451 // Long double always uses X87.
452 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
453 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
454 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
456 APFloat TmpFlt(+0.0);
457 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
458 addLegalFPImmediate(TmpFlt); // FLD0
460 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
461 APFloat TmpFlt2(+1.0);
462 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
463 addLegalFPImmediate(TmpFlt2); // FLD1
464 TmpFlt2.changeSign();
465 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
469 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
470 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
473 // Always use a library call for pow.
474 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
475 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
476 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
478 // First set operation action for all vector types to expand. Then we
479 // will selectively turn on ones that can be effectively codegen'd.
480 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
481 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
482 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
483 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
486 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
487 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
488 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
492 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
521 if (Subtarget->hasMMX()) {
522 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
523 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
524 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
525 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
527 // FIXME: add MMX packed arithmetics
529 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
530 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
531 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
532 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
534 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
535 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
536 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
537 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
539 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
540 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
542 setOperationAction(ISD::AND, MVT::v8i8, Promote);
543 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
544 setOperationAction(ISD::AND, MVT::v4i16, Promote);
545 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
546 setOperationAction(ISD::AND, MVT::v2i32, Promote);
547 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
548 setOperationAction(ISD::AND, MVT::v1i64, Legal);
550 setOperationAction(ISD::OR, MVT::v8i8, Promote);
551 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
552 setOperationAction(ISD::OR, MVT::v4i16, Promote);
553 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
554 setOperationAction(ISD::OR, MVT::v2i32, Promote);
555 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
556 setOperationAction(ISD::OR, MVT::v1i64, Legal);
558 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
559 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
560 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
561 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
562 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
563 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
564 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
566 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
567 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
568 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
569 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
570 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
571 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
572 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
574 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
575 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
576 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
577 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
579 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
580 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
581 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
582 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
584 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
585 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
586 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
589 if (Subtarget->hasSSE1()) {
590 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
592 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
593 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
594 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
595 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
596 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
597 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
598 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
599 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
600 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
601 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
602 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
605 if (Subtarget->hasSSE2()) {
606 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
607 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
608 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
609 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
610 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
612 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
613 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
614 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
615 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
616 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
617 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
618 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
619 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
620 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
621 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
622 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
623 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
624 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
625 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
626 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
628 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
630 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
631 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
632 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
634 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
635 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
636 // Do not attempt to custom lower non-power-of-2 vectors
637 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
639 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
640 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
641 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
643 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
644 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
647 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
648 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
649 if (Subtarget->is64Bit()) {
650 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
654 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
655 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
656 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
657 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
658 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
659 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
660 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
661 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
662 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
663 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
664 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
665 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
668 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
670 // Custom lower v2i64 and v2f64 selects.
671 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
672 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
673 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
674 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
677 if (Subtarget->hasSSE41()) {
678 // FIXME: Do we need to handle scalar-to-vector here?
679 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
681 // i8 and i16 vectors are custom , because the source register and source
682 // source memory operand types are not the same width. f32 vectors are
683 // custom since the immediate controlling the insert encodes additional
685 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
686 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
687 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
690 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
692 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
693 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
695 if (Subtarget->is64Bit()) {
696 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
697 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
701 // We want to custom lower some of our intrinsics.
702 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
704 // We have target-specific dag combine patterns for the following nodes:
705 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
706 setTargetDAGCombine(ISD::SELECT);
707 setTargetDAGCombine(ISD::STORE);
709 computeRegisterProperties();
711 // FIXME: These should be based on subtarget info. Plus, the values should
712 // be smaller when we are in optimizing for size mode.
713 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
714 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
715 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
716 allowUnalignedMemoryAccesses = true; // x86 supports it!
719 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
720 /// the desired ByVal argument alignment.
721 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
724 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
725 if (VTy->getBitWidth() == 128)
727 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
728 unsigned EltAlign = 0;
729 getMaxByValAlign(ATy->getElementType(), EltAlign);
730 if (EltAlign > MaxAlign)
732 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
733 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
734 unsigned EltAlign = 0;
735 getMaxByValAlign(STy->getElementType(i), EltAlign);
736 if (EltAlign > MaxAlign)
745 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
746 /// function arguments in the caller parameter area. For X86, aggregates
747 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
748 /// are at 4-byte boundaries.
749 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
750 if (Subtarget->is64Bit())
751 return getTargetData()->getABITypeAlignment(Ty);
753 if (Subtarget->hasSSE1())
754 getMaxByValAlign(Ty, Align);
758 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
760 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
761 SelectionDAG &DAG) const {
762 if (usesGlobalOffsetTable())
763 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
764 if (!Subtarget->isPICStyleRIPRel())
765 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
769 //===----------------------------------------------------------------------===//
770 // Return Value Calling Convention Implementation
771 //===----------------------------------------------------------------------===//
773 #include "X86GenCallingConv.inc"
775 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
776 /// exists skip possible ISD:TokenFactor.
777 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
778 if (Chain.getOpcode() == X86ISD::TAILCALL) {
780 } else if (Chain.getOpcode() == ISD::TokenFactor) {
781 if (Chain.getNumOperands() &&
782 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
783 return Chain.getOperand(0);
788 /// LowerRET - Lower an ISD::RET node.
789 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
790 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
792 SmallVector<CCValAssign, 16> RVLocs;
793 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
794 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
795 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
796 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
798 // If this is the first return lowered for this function, add the regs to the
799 // liveout set for the function.
800 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
801 for (unsigned i = 0; i != RVLocs.size(); ++i)
802 if (RVLocs[i].isRegLoc())
803 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
805 SDOperand Chain = Op.getOperand(0);
807 // Handle tail call return.
808 Chain = GetPossiblePreceedingTailCall(Chain);
809 if (Chain.getOpcode() == X86ISD::TAILCALL) {
810 SDOperand TailCall = Chain;
811 SDOperand TargetAddress = TailCall.getOperand(1);
812 SDOperand StackAdjustment = TailCall.getOperand(2);
813 assert(((TargetAddress.getOpcode() == ISD::Register &&
814 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
815 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
816 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
817 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
818 "Expecting an global address, external symbol, or register");
819 assert(StackAdjustment.getOpcode() == ISD::Constant &&
820 "Expecting a const value");
822 SmallVector<SDOperand,8> Operands;
823 Operands.push_back(Chain.getOperand(0));
824 Operands.push_back(TargetAddress);
825 Operands.push_back(StackAdjustment);
826 // Copy registers used by the call. Last operand is a flag so it is not
828 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
829 Operands.push_back(Chain.getOperand(i));
831 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
838 // Copy the result values into the output registers.
839 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
840 RVLocs[0].getLocReg() != X86::ST0) {
841 for (unsigned i = 0; i != RVLocs.size(); ++i) {
842 CCValAssign &VA = RVLocs[i];
843 assert(VA.isRegLoc() && "Can only return in registers!");
844 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
846 Flag = Chain.getValue(1);
849 // We need to handle a destination of ST0 specially, because it isn't really
851 SDOperand Value = Op.getOperand(1);
853 // an XMM register onto the fp-stack. Do this with an FP_EXTEND to f80.
854 // This will get legalized into a load/store if it can't get optimized away.
855 if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
856 Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
858 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
859 SDOperand Ops[] = { Chain, Value };
860 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
861 Flag = Chain.getValue(1);
864 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
866 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
868 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
872 /// LowerCallResult - Lower the result values of an ISD::CALL into the
873 /// appropriate copies out of appropriate physical registers. This assumes that
874 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
875 /// being lowered. The returns a SDNode with the same number of values as the
877 SDNode *X86TargetLowering::
878 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
879 unsigned CallingConv, SelectionDAG &DAG) {
881 // Assign locations to each value returned by this call.
882 SmallVector<CCValAssign, 16> RVLocs;
883 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
884 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
885 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
887 SmallVector<SDOperand, 8> ResultVals;
889 // Copy all of the result registers out of their specified physreg.
890 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
891 for (unsigned i = 0; i != RVLocs.size(); ++i) {
892 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
893 RVLocs[i].getValVT(), InFlag).getValue(1);
894 InFlag = Chain.getValue(2);
895 ResultVals.push_back(Chain.getValue(0));
898 // Copies from the FP stack are special, as ST0 isn't a valid register
899 // before the fp stackifier runs.
901 // Copy ST0 into an RFP register with FP_GET_RESULT. If this will end up
902 // in an SSE register, copy it out as F80 and do a truncate, otherwise use
903 // the specified value type.
904 MVT::ValueType GetResultTy = RVLocs[0].getValVT();
905 if (isScalarFPTypeInSSEReg(GetResultTy))
906 GetResultTy = MVT::f80;
907 SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
909 SDOperand GROps[] = { Chain, InFlag };
910 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
911 Chain = RetVal.getValue(1);
912 InFlag = RetVal.getValue(2);
914 // If we want the result in an SSE register, use an FP_TRUNCATE to get it
916 if (GetResultTy != RVLocs[0].getValVT())
917 RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
918 // This truncation won't change the value.
919 DAG.getIntPtrConstant(1));
921 ResultVals.push_back(RetVal);
924 // Merge everything together with a MERGE_VALUES node.
925 ResultVals.push_back(Chain);
926 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
927 &ResultVals[0], ResultVals.size()).Val;
930 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
931 /// ISD::CALL where the results are known to be in two 64-bit registers,
932 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
933 /// fixed stack slot allocated for StructRet.
934 SDNode *X86TargetLowering::
935 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
936 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
937 MVT::ValueType VT, SelectionDAG &DAG) {
938 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
939 Chain = RetVal1.getValue(1);
940 InFlag = RetVal1.getValue(2);
941 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
942 Chain = RetVal2.getValue(1);
943 InFlag = RetVal2.getValue(2);
944 SDOperand FIN = TheCall->getOperand(5);
945 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
946 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
947 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
951 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
952 /// where the results are known to be in ST0 and ST1.
953 SDNode *X86TargetLowering::
954 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
955 SDNode *TheCall, SelectionDAG &DAG) {
956 SmallVector<SDOperand, 8> ResultVals;
957 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
958 SDVTList Tys = DAG.getVTList(VTs, 4);
959 SDOperand Ops[] = { Chain, InFlag };
960 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT2, Tys, Ops, 2);
961 Chain = RetVal.getValue(2);
962 SDOperand FIN = TheCall->getOperand(5);
963 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
964 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
965 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
969 //===----------------------------------------------------------------------===//
970 // C & StdCall & Fast Calling Convention implementation
971 //===----------------------------------------------------------------------===//
972 // StdCall calling convention seems to be standard for many Windows' API
973 // routines and around. It differs from C calling convention just a little:
974 // callee should clean up the stack, not caller. Symbols should be also
975 // decorated in some fancy way :) It doesn't support any vector arguments.
976 // For info on fast calling convention see Fast Calling Convention (tail call)
977 // implementation LowerX86_32FastCCCallTo.
979 /// AddLiveIn - This helper function adds the specified physical register to the
980 /// MachineFunction as a live in value. It also creates a corresponding virtual
982 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
983 const TargetRegisterClass *RC) {
984 assert(RC->contains(PReg) && "Not the correct regclass!");
985 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
986 MF.getRegInfo().addLiveIn(PReg, VReg);
990 // Determines whether a CALL node uses struct return semantics.
991 static bool CallIsStructReturn(SDOperand Op) {
992 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
996 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
997 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1000 // Determines whether a FORMAL_ARGUMENTS node uses struct return semantics.
1001 static bool ArgsAreStructReturn(SDOperand Op) {
1002 unsigned NumArgs = Op.Val->getNumValues() - 1;
1006 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1007 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1010 // Determines whether a CALL or FORMAL_ARGUMENTS node requires the callee to pop
1011 // its own arguments. Callee pop is necessary to support tail calls.
1012 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1013 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1017 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1020 case CallingConv::X86_StdCall:
1021 return !Subtarget->is64Bit();
1022 case CallingConv::X86_FastCall:
1023 return !Subtarget->is64Bit();
1024 case CallingConv::Fast:
1025 return PerformTailCallOpt;
1029 // Selects the correct CCAssignFn for a CALL or FORMAL_ARGUMENTS node.
1030 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1031 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1033 if (Subtarget->is64Bit()) {
1034 if (CC == CallingConv::Fast && PerformTailCallOpt)
1035 return CC_X86_64_TailCall;
1040 if (CC == CallingConv::X86_FastCall)
1041 return CC_X86_32_FastCall;
1042 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1043 return CC_X86_32_TailCall;
1048 // Selects the appropriate decoration to apply to a MachineFunction containing a
1049 // given FORMAL_ARGUMENTS node.
1051 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1052 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1053 if (CC == CallingConv::X86_FastCall)
1055 else if (CC == CallingConv::X86_StdCall)
1061 // IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could possibly
1062 // be overwritten when lowering the outgoing arguments in a tail call. Currently
1063 // the implementation of this call is very conservative and assumes all
1064 // arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with virtual
1065 // registers would be overwritten by direct lowering.
1066 // Possible improvement:
1067 // Check FORMAL_ARGUMENTS corresponding MERGE_VALUES for CopyFromReg nodes
1068 // indicating inreg passed arguments which also need not be lowered to a safe
1070 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op) {
1071 RegisterSDNode * OpReg = NULL;
1072 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1073 (Op.getOpcode()== ISD::CopyFromReg &&
1074 (OpReg = cast<RegisterSDNode>(Op.getOperand(1))) &&
1075 OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister))
1080 // CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1081 // by "Src" to address "Dst" with size and alignment information specified by
1082 // the specific parameter attribute. The copy will be passed as a byval function
1085 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1086 unsigned Flags, SelectionDAG &DAG) {
1087 unsigned Align = 1 <<
1088 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1089 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1090 ISD::ParamFlags::ByValSizeOffs;
1091 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1092 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1093 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1094 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1097 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1098 const CCValAssign &VA,
1099 MachineFrameInfo *MFI,
1100 SDOperand Root, unsigned i) {
1101 // Create the nodes corresponding to a load from this parameter slot.
1102 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1103 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1105 // FIXME: For now, all byval parameter objects are marked mutable. This
1106 // can be changed with more analysis.
1107 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1108 VA.getLocMemOffset(), !isByVal);
1109 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1112 return DAG.getLoad(VA.getValVT(), Root, FIN,
1113 PseudoSourceValue::getFixedStack(), FI);
1117 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1118 MachineFunction &MF = DAG.getMachineFunction();
1119 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1121 const Function* Fn = MF.getFunction();
1122 if (Fn->hasExternalLinkage() &&
1123 Subtarget->isTargetCygMing() &&
1124 Fn->getName() == "main")
1125 FuncInfo->setForceFramePointer(true);
1127 // Decorate the function name.
1128 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1130 MachineFrameInfo *MFI = MF.getFrameInfo();
1131 SDOperand Root = Op.getOperand(0);
1132 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1133 unsigned CC = MF.getFunction()->getCallingConv();
1134 bool Is64Bit = Subtarget->is64Bit();
1136 assert(!(isVarArg && CC == CallingConv::Fast) &&
1137 "Var args not supported with calling convention fastcc");
1139 // Assign locations to all of the incoming arguments.
1140 SmallVector<CCValAssign, 16> ArgLocs;
1141 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1142 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1144 SmallVector<SDOperand, 8> ArgValues;
1145 unsigned LastVal = ~0U;
1146 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1147 CCValAssign &VA = ArgLocs[i];
1148 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1150 assert(VA.getValNo() != LastVal &&
1151 "Don't support value assigned to multiple locs yet");
1152 LastVal = VA.getValNo();
1154 if (VA.isRegLoc()) {
1155 MVT::ValueType RegVT = VA.getLocVT();
1156 TargetRegisterClass *RC;
1157 if (RegVT == MVT::i32)
1158 RC = X86::GR32RegisterClass;
1159 else if (Is64Bit && RegVT == MVT::i64)
1160 RC = X86::GR64RegisterClass;
1161 else if (RegVT == MVT::f32)
1162 RC = X86::FR32RegisterClass;
1163 else if (RegVT == MVT::f64)
1164 RC = X86::FR64RegisterClass;
1166 assert(MVT::isVector(RegVT));
1167 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1168 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1171 RC = X86::VR128RegisterClass;
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() && RC == X86::GR64RegisterClass &&
1192 MVT::getSizeInBits(RegVT) == 64)
1193 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1195 ArgValues.push_back(ArgValue);
1197 assert(VA.isMemLoc());
1198 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1202 unsigned StackSize = CCInfo.getNextStackOffset();
1203 // align stack specially for tail calls
1204 if (CC == CallingConv::Fast)
1205 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1207 // If the function takes variable number of arguments, make a frame index for
1208 // the start of the first vararg value... for expansion of llvm.va_start.
1210 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1211 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1214 static const unsigned GPR64ArgRegs[] = {
1215 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1217 static const unsigned XMMArgRegs[] = {
1218 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1219 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1222 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1223 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1225 // For X86-64, if there are vararg parameters that are passed via
1226 // registers, then we must store them to their spots on the stack so they
1227 // may be loaded by deferencing the result of va_next.
1228 VarArgsGPOffset = NumIntRegs * 8;
1229 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1230 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1232 // Store the integer parameter registers.
1233 SmallVector<SDOperand, 8> MemOps;
1234 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1235 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1236 DAG.getIntPtrConstant(VarArgsGPOffset));
1237 for (; NumIntRegs != 6; ++NumIntRegs) {
1238 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1239 X86::GR64RegisterClass);
1240 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1242 DAG.getStore(Val.getValue(1), Val, FIN,
1243 PseudoSourceValue::getFixedStack(),
1245 MemOps.push_back(Store);
1246 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1247 DAG.getIntPtrConstant(8));
1250 // Now store the XMM (fp + vector) parameter registers.
1251 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1252 DAG.getIntPtrConstant(VarArgsFPOffset));
1253 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1254 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1255 X86::VR128RegisterClass);
1256 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1258 DAG.getStore(Val.getValue(1), Val, FIN,
1259 PseudoSourceValue::getFixedStack(),
1261 MemOps.push_back(Store);
1262 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1263 DAG.getIntPtrConstant(16));
1265 if (!MemOps.empty())
1266 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1267 &MemOps[0], MemOps.size());
1271 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1272 // arguments and the arguments after the retaddr has been pushed are
1274 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1275 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1276 (StackSize & 7) == 0)
1279 ArgValues.push_back(Root);
1281 // Some CCs need callee pop.
1282 if (IsCalleePop(Op)) {
1283 BytesToPopOnReturn = StackSize; // Callee pops everything.
1284 BytesCallerReserves = 0;
1286 BytesToPopOnReturn = 0; // Callee pops nothing.
1287 // If this is an sret function, the return should pop the hidden pointer.
1288 if (!Is64Bit && ArgsAreStructReturn(Op))
1289 BytesToPopOnReturn = 4;
1290 BytesCallerReserves = StackSize;
1294 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1295 if (CC == CallingConv::X86_FastCall)
1296 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1299 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1301 // Return the new list of results.
1302 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1303 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1307 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1308 const SDOperand &StackPtr,
1309 const CCValAssign &VA,
1312 unsigned LocMemOffset = VA.getLocMemOffset();
1313 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1314 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1315 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1316 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1317 if (Flags & ISD::ParamFlags::ByVal) {
1318 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1320 return DAG.getStore(Chain, Arg, PtrOff,
1321 PseudoSourceValue::getStack(), LocMemOffset);
1324 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1325 /// struct return call to the specified function. X86-64 ABI specifies
1326 /// some SRet calls are actually returned in registers. Since current
1327 /// LLVM cannot represent multi-value calls, they are represent as
1328 /// calls where the results are passed in a hidden struct provided by
1329 /// the caller. This function examines the type of the struct to
1330 /// determine the correct way to implement the call.
1332 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1333 // FIXME: Disabled for now.
1334 return X86::InMemory;
1336 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1337 const Type *RTy = PTy->getElementType();
1338 unsigned Size = getTargetData()->getABITypeSize(RTy);
1339 if (Size != 16 && Size != 32)
1340 return X86::InMemory;
1343 const StructType *STy = dyn_cast<StructType>(RTy);
1344 if (!STy) return X86::InMemory;
1345 if (STy->getNumElements() == 2 &&
1346 STy->getElementType(0) == Type::X86_FP80Ty &&
1347 STy->getElementType(1) == Type::X86_FP80Ty)
1352 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1354 const Type *STy = I->get();
1355 if (!STy->isFPOrFPVector()) {
1363 return X86::InGPR64;
1366 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1369 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1370 for (unsigned i = 1; i != NumOps; ++i) {
1371 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1372 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1373 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1374 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1375 cerr << "Call operand #" << i << " has unhandled type "
1376 << MVT::getValueTypeString(ArgVT) << "\n";
1382 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1383 MachineFunction &MF = DAG.getMachineFunction();
1384 SDOperand Chain = Op.getOperand(0);
1385 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1386 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1387 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1388 && CC == CallingConv::Fast && PerformTailCallOpt;
1389 SDOperand Callee = Op.getOperand(4);
1390 bool Is64Bit = Subtarget->is64Bit();
1391 bool IsStructRet = CallIsStructReturn(Op);
1393 assert(!(isVarArg && CC == CallingConv::Fast) &&
1394 "Var args not supported with calling convention fastcc");
1396 // Analyze operands of the call, assigning locations to each operand.
1397 SmallVector<CCValAssign, 16> ArgLocs;
1398 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1399 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1401 X86::X86_64SRet SRetMethod = X86::InMemory;
1402 if (Is64Bit && IsStructRet)
1403 // FIXME: We can't figure out type of the sret structure for indirect
1404 // calls. We need to copy more information from CallSite to the ISD::CALL
1406 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1408 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1410 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1411 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1413 if (SRetMethod != X86::InMemory)
1414 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1416 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1418 // Get a count of how many bytes are to be pushed on the stack.
1419 unsigned NumBytes = CCInfo.getNextStackOffset();
1420 if (CC == CallingConv::Fast)
1421 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1423 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1424 // arguments and the arguments after the retaddr has been pushed are aligned.
1425 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1426 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1427 (NumBytes & 7) == 0)
1432 // Lower arguments at fp - stackoffset + fpdiff.
1433 unsigned NumBytesCallerPushed =
1434 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1435 FPDiff = NumBytesCallerPushed - NumBytes;
1437 // Set the delta of movement of the returnaddr stackslot.
1438 // But only set if delta is greater than previous delta.
1439 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1440 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1443 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1445 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1447 // Adjust the Return address stack slot.
1449 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1450 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1451 // Load the "old" Return address.
1453 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1454 // Calculate the new stack slot for the return address.
1455 int SlotSize = Is64Bit ? 8 : 4;
1456 int NewReturnAddrFI =
1457 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1458 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1459 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1463 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1464 SmallVector<SDOperand, 8> MemOpChains;
1468 // Walk the register/memloc assignments, inserting copies/loads. For tail
1469 // calls, lower arguments which could otherwise be possibly overwritten to the
1470 // stack slot where they would go on normal function calls.
1471 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1472 CCValAssign &VA = ArgLocs[i];
1473 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1475 // Promote the value if needed.
1476 switch (VA.getLocInfo()) {
1477 default: assert(0 && "Unknown loc info!");
1478 case CCValAssign::Full: break;
1479 case CCValAssign::SExt:
1480 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1482 case CCValAssign::ZExt:
1483 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1485 case CCValAssign::AExt:
1486 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1490 if (VA.isRegLoc()) {
1491 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1493 if (!IsTailCall || IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1494 assert(VA.isMemLoc());
1495 if (StackPtr.Val == 0)
1496 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1498 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1504 if (!MemOpChains.empty())
1505 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1506 &MemOpChains[0], MemOpChains.size());
1508 // Build a sequence of copy-to-reg nodes chained together with token chain
1509 // and flag operands which copy the outgoing args into registers.
1511 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1512 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1514 InFlag = Chain.getValue(1);
1518 InFlag = SDOperand(); // ??? Isn't this nuking the preceding loop's output?
1520 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1522 // Does not work with tail call since ebx is not restored correctly by
1523 // tailcaller. TODO: at least for x86 - verify for x86-64
1524 if (!IsTailCall && !Is64Bit &&
1525 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1526 Subtarget->isPICStyleGOT()) {
1527 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1528 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1530 InFlag = Chain.getValue(1);
1533 if (Is64Bit && isVarArg) {
1534 // From AMD64 ABI document:
1535 // For calls that may call functions that use varargs or stdargs
1536 // (prototype-less calls or calls to functions containing ellipsis (...) in
1537 // the declaration) %al is used as hidden argument to specify the number
1538 // of SSE registers used. The contents of %al do not need to match exactly
1539 // the number of registers, but must be an ubound on the number of SSE
1540 // registers used and is in the range 0 - 8 inclusive.
1542 // Count the number of XMM registers allocated.
1543 static const unsigned XMMArgRegs[] = {
1544 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1545 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1547 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1549 Chain = DAG.getCopyToReg(Chain, X86::AL,
1550 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1551 InFlag = Chain.getValue(1);
1554 // For tail calls lower the arguments to the 'real' stack slot.
1556 SmallVector<SDOperand, 8> MemOpChains2;
1559 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1560 CCValAssign &VA = ArgLocs[i];
1561 if (!VA.isRegLoc()) {
1562 assert(VA.isMemLoc());
1563 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1564 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1565 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1566 // Create frame index.
1567 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1568 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1569 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1570 FIN = DAG.getFrameIndex(FI, MVT::i32);
1571 SDOperand Source = Arg;
1572 if (IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1573 // Copy from stack slots to stack slot of a tail called function. This
1574 // needs to be done because if we would lower the arguments directly
1575 // to their real stack slot we might end up overwriting each other.
1576 // Get source stack slot.
1577 Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1578 if (StackPtr.Val == 0)
1579 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1580 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1581 if ((Flags & ISD::ParamFlags::ByVal)==0)
1582 Source = DAG.getLoad(VA.getValVT(), Chain, Source, NULL, 0);
1585 if (Flags & ISD::ParamFlags::ByVal) {
1586 // Copy relative to framepointer.
1587 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1590 // Store relative to framepointer.
1591 MemOpChains2.push_back(
1592 DAG.getStore(Chain, Source, FIN,
1593 PseudoSourceValue::getFixedStack(), FI));
1598 if (!MemOpChains2.empty())
1599 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1600 &MemOpChains2[0], MemOpChains2.size());
1602 // Store the return address to the appropriate stack slot.
1604 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1607 // If the callee is a GlobalAddress node (quite common, every direct call is)
1608 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1609 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1610 // We should use extra load for direct calls to dllimported functions in
1612 if ((IsTailCall || !Is64Bit ||
1613 getTargetMachine().getCodeModel() != CodeModel::Large)
1614 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1615 getTargetMachine(), true))
1616 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1617 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1618 if (IsTailCall || !Is64Bit ||
1619 getTargetMachine().getCodeModel() != CodeModel::Large)
1620 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1621 } else if (IsTailCall) {
1622 assert(Callee.getOpcode() == ISD::LOAD &&
1623 "Function destination must be loaded into virtual register");
1624 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1626 Chain = DAG.getCopyToReg(Chain,
1627 DAG.getRegister(Opc, getPointerTy()) ,
1629 Callee = DAG.getRegister(Opc, getPointerTy());
1630 // Add register as live out.
1631 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1634 // Returns a chain & a flag for retval copy to use.
1635 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1636 SmallVector<SDOperand, 8> Ops;
1639 Ops.push_back(Chain);
1640 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1641 Ops.push_back(DAG.getIntPtrConstant(0));
1643 Ops.push_back(InFlag);
1644 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1645 InFlag = Chain.getValue(1);
1647 // Returns a chain & a flag for retval copy to use.
1648 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1652 Ops.push_back(Chain);
1653 Ops.push_back(Callee);
1656 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1658 // Add an implicit use GOT pointer in EBX.
1659 if (!IsTailCall && !Is64Bit &&
1660 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1661 Subtarget->isPICStyleGOT())
1662 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1664 // Add argument registers to the end of the list so that they are known live
1666 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1667 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1668 RegsToPass[i].second.getValueType()));
1671 Ops.push_back(InFlag);
1674 assert(InFlag.Val &&
1675 "Flag must be set. Depend on flag being set in LowerRET");
1676 Chain = DAG.getNode(X86ISD::TAILCALL,
1677 Op.Val->getVTList(), &Ops[0], Ops.size());
1679 return SDOperand(Chain.Val, Op.ResNo);
1682 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1683 InFlag = Chain.getValue(1);
1685 // Create the CALLSEQ_END node.
1686 unsigned NumBytesForCalleeToPush;
1687 if (IsCalleePop(Op))
1688 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1689 else if (!Is64Bit && IsStructRet)
1690 // If this is is a call to a struct-return function, the callee
1691 // pops the hidden struct pointer, so we have to push it back.
1692 // This is common for Darwin/X86, Linux & Mingw32 targets.
1693 NumBytesForCalleeToPush = 4;
1695 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1697 // Returns a flag for retval copy to use.
1698 Chain = DAG.getCALLSEQ_END(Chain,
1699 DAG.getIntPtrConstant(NumBytes),
1700 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1702 InFlag = Chain.getValue(1);
1704 // Handle result values, copying them out of physregs into vregs that we
1706 switch (SRetMethod) {
1708 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1710 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1712 MVT::i64, DAG), Op.ResNo);
1714 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1715 X86::XMM0, X86::XMM1,
1716 MVT::f64, DAG), Op.ResNo);
1718 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1724 //===----------------------------------------------------------------------===//
1725 // Fast Calling Convention (tail call) implementation
1726 //===----------------------------------------------------------------------===//
1728 // Like std call, callee cleans arguments, convention except that ECX is
1729 // reserved for storing the tail called function address. Only 2 registers are
1730 // free for argument passing (inreg). Tail call optimization is performed
1732 // * tailcallopt is enabled
1733 // * caller/callee are fastcc
1734 // * elf/pic is disabled OR
1735 // * elf/pic enabled + callee is in module + callee has
1736 // visibility protected or hidden
1737 // To keep the stack aligned according to platform abi the function
1738 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1739 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1740 // If a tail called function callee has more arguments than the caller the
1741 // caller needs to make sure that there is room to move the RETADDR to. This is
1742 // achieved by reserving an area the size of the argument delta right after the
1743 // original REtADDR, but before the saved framepointer or the spilled registers
1744 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1756 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1757 /// for a 16 byte align requirement.
1758 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1759 SelectionDAG& DAG) {
1760 if (PerformTailCallOpt) {
1761 MachineFunction &MF = DAG.getMachineFunction();
1762 const TargetMachine &TM = MF.getTarget();
1763 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1764 unsigned StackAlignment = TFI.getStackAlignment();
1765 uint64_t AlignMask = StackAlignment - 1;
1766 int64_t Offset = StackSize;
1767 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1768 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1769 // Number smaller than 12 so just add the difference.
1770 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1772 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1773 Offset = ((~AlignMask) & Offset) + StackAlignment +
1774 (StackAlignment-SlotSize);
1781 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1782 /// following the call is a return. A function is eligible if caller/callee
1783 /// calling conventions match, currently only fastcc supports tail calls, and
1784 /// the function CALL is immediatly followed by a RET.
1785 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1787 SelectionDAG& DAG) const {
1788 if (!PerformTailCallOpt)
1791 // Check whether CALL node immediatly preceeds the RET node and whether the
1792 // return uses the result of the node or is a void return.
1793 unsigned NumOps = Ret.getNumOperands();
1795 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1796 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1798 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1799 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1800 MachineFunction &MF = DAG.getMachineFunction();
1801 unsigned CallerCC = MF.getFunction()->getCallingConv();
1802 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1803 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1804 SDOperand Callee = Call.getOperand(4);
1805 // On elf/pic %ebx needs to be livein.
1806 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1807 !Subtarget->isPICStyleGOT())
1810 // Can only do local tail calls with PIC.
1811 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1812 return G->getGlobal()->hasHiddenVisibility()
1813 || G->getGlobal()->hasProtectedVisibility();
1820 //===----------------------------------------------------------------------===//
1821 // Other Lowering Hooks
1822 //===----------------------------------------------------------------------===//
1825 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1826 MachineFunction &MF = DAG.getMachineFunction();
1827 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1828 int ReturnAddrIndex = FuncInfo->getRAIndex();
1830 if (ReturnAddrIndex == 0) {
1831 // Set up a frame object for the return address.
1832 if (Subtarget->is64Bit())
1833 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1835 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1837 FuncInfo->setRAIndex(ReturnAddrIndex);
1840 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1845 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1846 /// specific condition code. It returns a false if it cannot do a direct
1847 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1849 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1850 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1851 SelectionDAG &DAG) {
1852 X86CC = X86::COND_INVALID;
1854 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1855 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1856 // X > -1 -> X == 0, jump !sign.
1857 RHS = DAG.getConstant(0, RHS.getValueType());
1858 X86CC = X86::COND_NS;
1860 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1861 // X < 0 -> X == 0, jump on sign.
1862 X86CC = X86::COND_S;
1864 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1866 RHS = DAG.getConstant(0, RHS.getValueType());
1867 X86CC = X86::COND_LE;
1872 switch (SetCCOpcode) {
1874 case ISD::SETEQ: X86CC = X86::COND_E; break;
1875 case ISD::SETGT: X86CC = X86::COND_G; break;
1876 case ISD::SETGE: X86CC = X86::COND_GE; break;
1877 case ISD::SETLT: X86CC = X86::COND_L; break;
1878 case ISD::SETLE: X86CC = X86::COND_LE; break;
1879 case ISD::SETNE: X86CC = X86::COND_NE; break;
1880 case ISD::SETULT: X86CC = X86::COND_B; break;
1881 case ISD::SETUGT: X86CC = X86::COND_A; break;
1882 case ISD::SETULE: X86CC = X86::COND_BE; break;
1883 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1886 // On a floating point condition, the flags are set as follows:
1888 // 0 | 0 | 0 | X > Y
1889 // 0 | 0 | 1 | X < Y
1890 // 1 | 0 | 0 | X == Y
1891 // 1 | 1 | 1 | unordered
1893 switch (SetCCOpcode) {
1896 case ISD::SETEQ: X86CC = X86::COND_E; break;
1897 case ISD::SETOLT: Flip = true; // Fallthrough
1899 case ISD::SETGT: X86CC = X86::COND_A; break;
1900 case ISD::SETOLE: Flip = true; // Fallthrough
1902 case ISD::SETGE: X86CC = X86::COND_AE; break;
1903 case ISD::SETUGT: Flip = true; // Fallthrough
1905 case ISD::SETLT: X86CC = X86::COND_B; break;
1906 case ISD::SETUGE: Flip = true; // Fallthrough
1908 case ISD::SETLE: X86CC = X86::COND_BE; break;
1910 case ISD::SETNE: X86CC = X86::COND_NE; break;
1911 case ISD::SETUO: X86CC = X86::COND_P; break;
1912 case ISD::SETO: X86CC = X86::COND_NP; break;
1915 std::swap(LHS, RHS);
1918 return X86CC != X86::COND_INVALID;
1921 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1922 /// code. Current x86 isa includes the following FP cmov instructions:
1923 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1924 static bool hasFPCMov(unsigned X86CC) {
1940 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1941 /// true if Op is undef or if its value falls within the specified range (L, H].
1942 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1943 if (Op.getOpcode() == ISD::UNDEF)
1946 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1947 return (Val >= Low && Val < Hi);
1950 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1951 /// true if Op is undef or if its value equal to the specified value.
1952 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1953 if (Op.getOpcode() == ISD::UNDEF)
1955 return cast<ConstantSDNode>(Op)->getValue() == Val;
1958 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1959 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1960 bool X86::isPSHUFDMask(SDNode *N) {
1961 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1963 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1966 // Check if the value doesn't reference the second vector.
1967 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1968 SDOperand Arg = N->getOperand(i);
1969 if (Arg.getOpcode() == ISD::UNDEF) continue;
1970 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1971 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1978 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1979 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1980 bool X86::isPSHUFHWMask(SDNode *N) {
1981 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1983 if (N->getNumOperands() != 8)
1986 // Lower quadword copied in order.
1987 for (unsigned i = 0; i != 4; ++i) {
1988 SDOperand Arg = N->getOperand(i);
1989 if (Arg.getOpcode() == ISD::UNDEF) continue;
1990 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1991 if (cast<ConstantSDNode>(Arg)->getValue() != i)
1995 // Upper quadword shuffled.
1996 for (unsigned i = 4; i != 8; ++i) {
1997 SDOperand Arg = N->getOperand(i);
1998 if (Arg.getOpcode() == ISD::UNDEF) continue;
1999 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2000 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2001 if (Val < 4 || Val > 7)
2008 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2009 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2010 bool X86::isPSHUFLWMask(SDNode *N) {
2011 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2013 if (N->getNumOperands() != 8)
2016 // Upper quadword copied in order.
2017 for (unsigned i = 4; i != 8; ++i)
2018 if (!isUndefOrEqual(N->getOperand(i), i))
2021 // Lower quadword shuffled.
2022 for (unsigned i = 0; i != 4; ++i)
2023 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2029 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2030 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2031 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2032 if (NumElems != 2 && NumElems != 4) return false;
2034 unsigned Half = NumElems / 2;
2035 for (unsigned i = 0; i < Half; ++i)
2036 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2038 for (unsigned i = Half; i < NumElems; ++i)
2039 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2045 bool X86::isSHUFPMask(SDNode *N) {
2046 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2047 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2050 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2051 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2052 /// half elements to come from vector 1 (which would equal the dest.) and
2053 /// the upper half to come from vector 2.
2054 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2055 if (NumOps != 2 && NumOps != 4) return false;
2057 unsigned Half = NumOps / 2;
2058 for (unsigned i = 0; i < Half; ++i)
2059 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2061 for (unsigned i = Half; i < NumOps; ++i)
2062 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2067 static bool isCommutedSHUFP(SDNode *N) {
2068 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2069 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2072 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2073 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2074 bool X86::isMOVHLPSMask(SDNode *N) {
2075 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2077 if (N->getNumOperands() != 4)
2080 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2081 return isUndefOrEqual(N->getOperand(0), 6) &&
2082 isUndefOrEqual(N->getOperand(1), 7) &&
2083 isUndefOrEqual(N->getOperand(2), 2) &&
2084 isUndefOrEqual(N->getOperand(3), 3);
2087 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2088 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2090 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2091 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2093 if (N->getNumOperands() != 4)
2096 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2097 return isUndefOrEqual(N->getOperand(0), 2) &&
2098 isUndefOrEqual(N->getOperand(1), 3) &&
2099 isUndefOrEqual(N->getOperand(2), 2) &&
2100 isUndefOrEqual(N->getOperand(3), 3);
2103 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2104 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2105 bool X86::isMOVLPMask(SDNode *N) {
2106 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2108 unsigned NumElems = N->getNumOperands();
2109 if (NumElems != 2 && NumElems != 4)
2112 for (unsigned i = 0; i < NumElems/2; ++i)
2113 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2116 for (unsigned i = NumElems/2; i < NumElems; ++i)
2117 if (!isUndefOrEqual(N->getOperand(i), i))
2123 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2124 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2126 bool X86::isMOVHPMask(SDNode *N) {
2127 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2129 unsigned NumElems = N->getNumOperands();
2130 if (NumElems != 2 && NumElems != 4)
2133 for (unsigned i = 0; i < NumElems/2; ++i)
2134 if (!isUndefOrEqual(N->getOperand(i), i))
2137 for (unsigned i = 0; i < NumElems/2; ++i) {
2138 SDOperand Arg = N->getOperand(i + NumElems/2);
2139 if (!isUndefOrEqual(Arg, i + NumElems))
2146 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2147 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2148 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2149 bool V2IsSplat = false) {
2150 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2153 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2154 SDOperand BitI = Elts[i];
2155 SDOperand BitI1 = Elts[i+1];
2156 if (!isUndefOrEqual(BitI, j))
2159 if (isUndefOrEqual(BitI1, NumElts))
2162 if (!isUndefOrEqual(BitI1, j + NumElts))
2170 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2171 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2172 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2175 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2176 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2177 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2178 bool V2IsSplat = false) {
2179 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2182 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2183 SDOperand BitI = Elts[i];
2184 SDOperand BitI1 = Elts[i+1];
2185 if (!isUndefOrEqual(BitI, j + NumElts/2))
2188 if (isUndefOrEqual(BitI1, NumElts))
2191 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2199 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2200 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2201 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2204 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2205 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2207 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2208 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2210 unsigned NumElems = N->getNumOperands();
2211 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2214 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2215 SDOperand BitI = N->getOperand(i);
2216 SDOperand BitI1 = N->getOperand(i+1);
2218 if (!isUndefOrEqual(BitI, j))
2220 if (!isUndefOrEqual(BitI1, j))
2227 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2228 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2230 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2231 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2233 unsigned NumElems = N->getNumOperands();
2234 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2237 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2238 SDOperand BitI = N->getOperand(i);
2239 SDOperand BitI1 = N->getOperand(i + 1);
2241 if (!isUndefOrEqual(BitI, j))
2243 if (!isUndefOrEqual(BitI1, j))
2250 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2251 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2252 /// MOVSD, and MOVD, i.e. setting the lowest element.
2253 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2254 if (NumElts != 2 && NumElts != 4)
2257 if (!isUndefOrEqual(Elts[0], NumElts))
2260 for (unsigned i = 1; i < NumElts; ++i) {
2261 if (!isUndefOrEqual(Elts[i], i))
2268 bool X86::isMOVLMask(SDNode *N) {
2269 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2270 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2273 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2274 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2275 /// element of vector 2 and the other elements to come from vector 1 in order.
2276 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2277 bool V2IsSplat = false,
2278 bool V2IsUndef = false) {
2279 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2282 if (!isUndefOrEqual(Ops[0], 0))
2285 for (unsigned i = 1; i < NumOps; ++i) {
2286 SDOperand Arg = Ops[i];
2287 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2288 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2289 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2296 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2297 bool V2IsUndef = false) {
2298 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2299 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2300 V2IsSplat, V2IsUndef);
2303 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2304 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2305 bool X86::isMOVSHDUPMask(SDNode *N) {
2306 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2308 if (N->getNumOperands() != 4)
2311 // Expect 1, 1, 3, 3
2312 for (unsigned i = 0; i < 2; ++i) {
2313 SDOperand Arg = N->getOperand(i);
2314 if (Arg.getOpcode() == ISD::UNDEF) continue;
2315 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2316 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2317 if (Val != 1) return false;
2321 for (unsigned i = 2; i < 4; ++i) {
2322 SDOperand Arg = N->getOperand(i);
2323 if (Arg.getOpcode() == ISD::UNDEF) continue;
2324 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2325 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2326 if (Val != 3) return false;
2330 // Don't use movshdup if it can be done with a shufps.
2334 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2335 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2336 bool X86::isMOVSLDUPMask(SDNode *N) {
2337 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2339 if (N->getNumOperands() != 4)
2342 // Expect 0, 0, 2, 2
2343 for (unsigned i = 0; i < 2; ++i) {
2344 SDOperand Arg = N->getOperand(i);
2345 if (Arg.getOpcode() == ISD::UNDEF) continue;
2346 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2347 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2348 if (Val != 0) return false;
2352 for (unsigned i = 2; i < 4; ++i) {
2353 SDOperand Arg = N->getOperand(i);
2354 if (Arg.getOpcode() == ISD::UNDEF) continue;
2355 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2356 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2357 if (Val != 2) return false;
2361 // Don't use movshdup if it can be done with a shufps.
2365 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2366 /// specifies a identity operation on the LHS or RHS.
2367 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2368 unsigned NumElems = N->getNumOperands();
2369 for (unsigned i = 0; i < NumElems; ++i)
2370 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2375 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2376 /// a splat of a single element.
2377 static bool isSplatMask(SDNode *N) {
2378 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2380 // This is a splat operation if each element of the permute is the same, and
2381 // if the value doesn't reference the second vector.
2382 unsigned NumElems = N->getNumOperands();
2383 SDOperand ElementBase;
2385 for (; i != NumElems; ++i) {
2386 SDOperand Elt = N->getOperand(i);
2387 if (isa<ConstantSDNode>(Elt)) {
2393 if (!ElementBase.Val)
2396 for (; i != NumElems; ++i) {
2397 SDOperand Arg = N->getOperand(i);
2398 if (Arg.getOpcode() == ISD::UNDEF) continue;
2399 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2400 if (Arg != ElementBase) return false;
2403 // Make sure it is a splat of the first vector operand.
2404 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2407 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2408 /// a splat of a single element and it's a 2 or 4 element mask.
2409 bool X86::isSplatMask(SDNode *N) {
2410 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2412 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2413 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2415 return ::isSplatMask(N);
2418 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2419 /// specifies a splat of zero element.
2420 bool X86::isSplatLoMask(SDNode *N) {
2421 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2423 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2424 if (!isUndefOrEqual(N->getOperand(i), 0))
2429 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2430 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2432 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2433 unsigned NumOperands = N->getNumOperands();
2434 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2436 for (unsigned i = 0; i < NumOperands; ++i) {
2438 SDOperand Arg = N->getOperand(NumOperands-i-1);
2439 if (Arg.getOpcode() != ISD::UNDEF)
2440 Val = cast<ConstantSDNode>(Arg)->getValue();
2441 if (Val >= NumOperands) Val -= NumOperands;
2443 if (i != NumOperands - 1)
2450 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2451 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2453 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2455 // 8 nodes, but we only care about the last 4.
2456 for (unsigned i = 7; i >= 4; --i) {
2458 SDOperand Arg = N->getOperand(i);
2459 if (Arg.getOpcode() != ISD::UNDEF)
2460 Val = cast<ConstantSDNode>(Arg)->getValue();
2469 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2470 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2472 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2474 // 8 nodes, but we only care about the first 4.
2475 for (int i = 3; i >= 0; --i) {
2477 SDOperand Arg = N->getOperand(i);
2478 if (Arg.getOpcode() != ISD::UNDEF)
2479 Val = cast<ConstantSDNode>(Arg)->getValue();
2488 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2489 /// specifies a 8 element shuffle that can be broken into a pair of
2490 /// PSHUFHW and PSHUFLW.
2491 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2492 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2494 if (N->getNumOperands() != 8)
2497 // Lower quadword shuffled.
2498 for (unsigned i = 0; i != 4; ++i) {
2499 SDOperand Arg = N->getOperand(i);
2500 if (Arg.getOpcode() == ISD::UNDEF) continue;
2501 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2502 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2507 // Upper quadword shuffled.
2508 for (unsigned i = 4; i != 8; ++i) {
2509 SDOperand Arg = N->getOperand(i);
2510 if (Arg.getOpcode() == ISD::UNDEF) continue;
2511 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2512 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2513 if (Val < 4 || Val > 7)
2520 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2521 /// values in ther permute mask.
2522 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2523 SDOperand &V2, SDOperand &Mask,
2524 SelectionDAG &DAG) {
2525 MVT::ValueType VT = Op.getValueType();
2526 MVT::ValueType MaskVT = Mask.getValueType();
2527 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2528 unsigned NumElems = Mask.getNumOperands();
2529 SmallVector<SDOperand, 8> MaskVec;
2531 for (unsigned i = 0; i != NumElems; ++i) {
2532 SDOperand Arg = Mask.getOperand(i);
2533 if (Arg.getOpcode() == ISD::UNDEF) {
2534 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2537 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2538 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2540 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2542 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2546 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2547 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2550 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2551 /// the two vector operands have swapped position.
2553 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2554 MVT::ValueType MaskVT = Mask.getValueType();
2555 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2556 unsigned NumElems = Mask.getNumOperands();
2557 SmallVector<SDOperand, 8> MaskVec;
2558 for (unsigned i = 0; i != NumElems; ++i) {
2559 SDOperand Arg = Mask.getOperand(i);
2560 if (Arg.getOpcode() == ISD::UNDEF) {
2561 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2564 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2565 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2567 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2569 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2571 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2575 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2576 /// match movhlps. The lower half elements should come from upper half of
2577 /// V1 (and in order), and the upper half elements should come from the upper
2578 /// half of V2 (and in order).
2579 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2580 unsigned NumElems = Mask->getNumOperands();
2583 for (unsigned i = 0, e = 2; i != e; ++i)
2584 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2586 for (unsigned i = 2; i != 4; ++i)
2587 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2592 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2593 /// is promoted to a vector.
2594 static inline bool isScalarLoadToVector(SDNode *N) {
2595 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2596 N = N->getOperand(0).Val;
2597 return ISD::isNON_EXTLoad(N);
2602 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2603 /// match movlp{s|d}. The lower half elements should come from lower half of
2604 /// V1 (and in order), and the upper half elements should come from the upper
2605 /// half of V2 (and in order). And since V1 will become the source of the
2606 /// MOVLP, it must be either a vector load or a scalar load to vector.
2607 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2608 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2610 // Is V2 is a vector load, don't do this transformation. We will try to use
2611 // load folding shufps op.
2612 if (ISD::isNON_EXTLoad(V2))
2615 unsigned NumElems = Mask->getNumOperands();
2616 if (NumElems != 2 && NumElems != 4)
2618 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2619 if (!isUndefOrEqual(Mask->getOperand(i), i))
2621 for (unsigned i = NumElems/2; i != NumElems; ++i)
2622 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2627 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2629 static bool isSplatVector(SDNode *N) {
2630 if (N->getOpcode() != ISD::BUILD_VECTOR)
2633 SDOperand SplatValue = N->getOperand(0);
2634 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2635 if (N->getOperand(i) != SplatValue)
2640 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2642 static bool isUndefShuffle(SDNode *N) {
2643 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2646 SDOperand V1 = N->getOperand(0);
2647 SDOperand V2 = N->getOperand(1);
2648 SDOperand Mask = N->getOperand(2);
2649 unsigned NumElems = Mask.getNumOperands();
2650 for (unsigned i = 0; i != NumElems; ++i) {
2651 SDOperand Arg = Mask.getOperand(i);
2652 if (Arg.getOpcode() != ISD::UNDEF) {
2653 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2654 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2656 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2663 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2665 static inline bool isZeroNode(SDOperand Elt) {
2666 return ((isa<ConstantSDNode>(Elt) &&
2667 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2668 (isa<ConstantFPSDNode>(Elt) &&
2669 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2672 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2673 /// to an zero vector.
2674 static bool isZeroShuffle(SDNode *N) {
2675 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2678 SDOperand V1 = N->getOperand(0);
2679 SDOperand V2 = N->getOperand(1);
2680 SDOperand Mask = N->getOperand(2);
2681 unsigned NumElems = Mask.getNumOperands();
2682 for (unsigned i = 0; i != NumElems; ++i) {
2683 SDOperand Arg = Mask.getOperand(i);
2684 if (Arg.getOpcode() == ISD::UNDEF)
2687 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2688 if (Idx < NumElems) {
2689 unsigned Opc = V1.Val->getOpcode();
2690 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2692 if (Opc != ISD::BUILD_VECTOR ||
2693 !isZeroNode(V1.Val->getOperand(Idx)))
2695 } else if (Idx >= NumElems) {
2696 unsigned Opc = V2.Val->getOpcode();
2697 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2699 if (Opc != ISD::BUILD_VECTOR ||
2700 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2707 /// getZeroVector - Returns a vector of specified type with all zero elements.
2709 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2710 assert(MVT::isVector(VT) && "Expected a vector type");
2712 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2713 // type. This ensures they get CSE'd.
2714 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2716 if (MVT::getSizeInBits(VT) == 64) // MMX
2717 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2719 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2720 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2723 /// getOnesVector - Returns a vector of specified type with all bits set.
2725 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2726 assert(MVT::isVector(VT) && "Expected a vector type");
2728 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2729 // type. This ensures they get CSE'd.
2730 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2732 if (MVT::getSizeInBits(VT) == 64) // MMX
2733 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2735 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2736 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2740 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2741 /// that point to V2 points to its first element.
2742 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2743 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2745 bool Changed = false;
2746 SmallVector<SDOperand, 8> MaskVec;
2747 unsigned NumElems = Mask.getNumOperands();
2748 for (unsigned i = 0; i != NumElems; ++i) {
2749 SDOperand Arg = Mask.getOperand(i);
2750 if (Arg.getOpcode() != ISD::UNDEF) {
2751 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2752 if (Val > NumElems) {
2753 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2757 MaskVec.push_back(Arg);
2761 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2762 &MaskVec[0], MaskVec.size());
2766 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2767 /// operation of specified width.
2768 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2769 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2770 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2772 SmallVector<SDOperand, 8> MaskVec;
2773 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2774 for (unsigned i = 1; i != NumElems; ++i)
2775 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2776 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2779 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2780 /// of specified width.
2781 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2782 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2783 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2784 SmallVector<SDOperand, 8> MaskVec;
2785 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2786 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2787 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2789 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2792 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2793 /// of specified width.
2794 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2795 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2796 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2797 unsigned Half = NumElems/2;
2798 SmallVector<SDOperand, 8> MaskVec;
2799 for (unsigned i = 0; i != Half; ++i) {
2800 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2801 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2803 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2806 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2808 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2809 SDOperand V1 = Op.getOperand(0);
2810 SDOperand Mask = Op.getOperand(2);
2811 MVT::ValueType VT = Op.getValueType();
2812 unsigned NumElems = Mask.getNumOperands();
2813 Mask = getUnpacklMask(NumElems, DAG);
2814 while (NumElems != 4) {
2815 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2818 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2820 Mask = getZeroVector(MVT::v4i32, DAG);
2821 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2822 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2823 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2826 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2827 /// vector of zero or undef vector. This produces a shuffle where the low
2828 /// element of V2 is swizzled into the zero/undef vector, landing at element
2829 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2830 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2831 unsigned NumElems, unsigned Idx,
2832 bool isZero, SelectionDAG &DAG) {
2833 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2834 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2835 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2836 SmallVector<SDOperand, 16> MaskVec;
2837 for (unsigned i = 0; i != NumElems; ++i)
2838 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2839 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2841 MaskVec.push_back(DAG.getConstant(i, EVT));
2842 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2843 &MaskVec[0], MaskVec.size());
2844 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2847 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2849 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2850 unsigned NumNonZero, unsigned NumZero,
2851 SelectionDAG &DAG, TargetLowering &TLI) {
2857 for (unsigned i = 0; i < 16; ++i) {
2858 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2859 if (ThisIsNonZero && First) {
2861 V = getZeroVector(MVT::v8i16, DAG);
2863 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2868 SDOperand ThisElt(0, 0), LastElt(0, 0);
2869 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2870 if (LastIsNonZero) {
2871 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2873 if (ThisIsNonZero) {
2874 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2875 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2876 ThisElt, DAG.getConstant(8, MVT::i8));
2878 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2883 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2884 DAG.getIntPtrConstant(i/2));
2888 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2891 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2893 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2894 unsigned NumNonZero, unsigned NumZero,
2895 SelectionDAG &DAG, TargetLowering &TLI) {
2901 for (unsigned i = 0; i < 8; ++i) {
2902 bool isNonZero = (NonZeros & (1 << i)) != 0;
2906 V = getZeroVector(MVT::v8i16, DAG);
2908 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2911 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2912 DAG.getIntPtrConstant(i));
2920 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2921 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2922 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2923 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2924 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2925 // eliminated on x86-32 hosts.
2926 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2929 if (ISD::isBuildVectorAllOnes(Op.Val))
2930 return getOnesVector(Op.getValueType(), DAG);
2931 return getZeroVector(Op.getValueType(), DAG);
2934 MVT::ValueType VT = Op.getValueType();
2935 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2936 unsigned EVTBits = MVT::getSizeInBits(EVT);
2938 unsigned NumElems = Op.getNumOperands();
2939 unsigned NumZero = 0;
2940 unsigned NumNonZero = 0;
2941 unsigned NonZeros = 0;
2942 bool HasNonImms = false;
2943 SmallSet<SDOperand, 8> Values;
2944 for (unsigned i = 0; i < NumElems; ++i) {
2945 SDOperand Elt = Op.getOperand(i);
2946 if (Elt.getOpcode() == ISD::UNDEF)
2949 if (Elt.getOpcode() != ISD::Constant &&
2950 Elt.getOpcode() != ISD::ConstantFP)
2952 if (isZeroNode(Elt))
2955 NonZeros |= (1 << i);
2960 if (NumNonZero == 0) {
2961 // All undef vector. Return an UNDEF. All zero vectors were handled above.
2962 return DAG.getNode(ISD::UNDEF, VT);
2965 // Splat is obviously ok. Let legalizer expand it to a shuffle.
2966 if (Values.size() == 1)
2969 // Special case for single non-zero element.
2970 if (NumNonZero == 1 && NumElems <= 4) {
2971 unsigned Idx = CountTrailingZeros_32(NonZeros);
2972 SDOperand Item = Op.getOperand(Idx);
2973 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2975 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2976 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2978 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
2981 if (EVTBits == 32) {
2982 // Turn it into a shuffle of zero and zero-extended scalar to vector.
2983 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2985 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2986 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2987 SmallVector<SDOperand, 8> MaskVec;
2988 for (unsigned i = 0; i < NumElems; i++)
2989 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2990 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2991 &MaskVec[0], MaskVec.size());
2992 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2993 DAG.getNode(ISD::UNDEF, VT), Mask);
2997 // A vector full of immediates; various special cases are already
2998 // handled, so this is best done with a single constant-pool load.
3002 // Let legalizer expand 2-wide build_vectors.
3006 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3007 if (EVTBits == 8 && NumElems == 16) {
3008 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3010 if (V.Val) return V;
3013 if (EVTBits == 16 && NumElems == 8) {
3014 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3016 if (V.Val) return V;
3019 // If element VT is == 32 bits, turn it into a number of shuffles.
3020 SmallVector<SDOperand, 8> V;
3022 if (NumElems == 4 && NumZero > 0) {
3023 for (unsigned i = 0; i < 4; ++i) {
3024 bool isZero = !(NonZeros & (1 << i));
3026 V[i] = getZeroVector(VT, DAG);
3028 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3031 for (unsigned i = 0; i < 2; ++i) {
3032 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3035 V[i] = V[i*2]; // Must be a zero vector.
3038 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3039 getMOVLMask(NumElems, DAG));
3042 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3043 getMOVLMask(NumElems, DAG));
3046 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3047 getUnpacklMask(NumElems, DAG));
3052 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3053 // clears the upper bits.
3054 // FIXME: we can do the same for v4f32 case when we know both parts of
3055 // the lower half come from scalar_to_vector (loadf32). We should do
3056 // that in post legalizer dag combiner with target specific hooks.
3057 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3059 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3060 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3061 SmallVector<SDOperand, 8> MaskVec;
3062 bool Reverse = (NonZeros & 0x3) == 2;
3063 for (unsigned i = 0; i < 2; ++i)
3065 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3067 MaskVec.push_back(DAG.getConstant(i, EVT));
3068 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3069 for (unsigned i = 0; i < 2; ++i)
3071 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3073 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3074 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3075 &MaskVec[0], MaskVec.size());
3076 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3079 if (Values.size() > 2) {
3080 // Expand into a number of unpckl*.
3082 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3083 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3084 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3085 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3086 for (unsigned i = 0; i < NumElems; ++i)
3087 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3089 while (NumElems != 0) {
3090 for (unsigned i = 0; i < NumElems; ++i)
3091 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3102 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3103 SDOperand PermMask, SelectionDAG &DAG,
3104 TargetLowering &TLI) {
3106 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3107 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3108 MVT::ValueType PtrVT = TLI.getPointerTy();
3109 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3110 PermMask.Val->op_end());
3112 // First record which half of which vector the low elements come from.
3113 SmallVector<unsigned, 4> LowQuad(4);
3114 for (unsigned i = 0; i < 4; ++i) {
3115 SDOperand Elt = MaskElts[i];
3116 if (Elt.getOpcode() == ISD::UNDEF)
3118 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3119 int QuadIdx = EltIdx / 4;
3122 int BestLowQuad = -1;
3123 unsigned MaxQuad = 1;
3124 for (unsigned i = 0; i < 4; ++i) {
3125 if (LowQuad[i] > MaxQuad) {
3127 MaxQuad = LowQuad[i];
3131 // Record which half of which vector the high elements come from.
3132 SmallVector<unsigned, 4> HighQuad(4);
3133 for (unsigned i = 4; i < 8; ++i) {
3134 SDOperand Elt = MaskElts[i];
3135 if (Elt.getOpcode() == ISD::UNDEF)
3137 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3138 int QuadIdx = EltIdx / 4;
3139 ++HighQuad[QuadIdx];
3141 int BestHighQuad = -1;
3143 for (unsigned i = 0; i < 4; ++i) {
3144 if (HighQuad[i] > MaxQuad) {
3146 MaxQuad = HighQuad[i];
3150 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3151 if (BestLowQuad != -1 || BestHighQuad != -1) {
3152 // First sort the 4 chunks in order using shufpd.
3153 SmallVector<SDOperand, 8> MaskVec;
3154 if (BestLowQuad != -1)
3155 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3157 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3158 if (BestHighQuad != -1)
3159 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3161 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3162 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3163 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3164 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3165 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3166 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3168 // Now sort high and low parts separately.
3169 BitVector InOrder(8);
3170 if (BestLowQuad != -1) {
3171 // Sort lower half in order using PSHUFLW.
3173 bool AnyOutOrder = false;
3174 for (unsigned i = 0; i != 4; ++i) {
3175 SDOperand Elt = MaskElts[i];
3176 if (Elt.getOpcode() == ISD::UNDEF) {
3177 MaskVec.push_back(Elt);
3180 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3183 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3184 // If this element is in the right place after this shuffle, then
3186 if ((int)(EltIdx / 4) == BestLowQuad)
3191 for (unsigned i = 4; i != 8; ++i)
3192 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3193 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3194 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3198 if (BestHighQuad != -1) {
3199 // Sort high half in order using PSHUFHW if possible.
3201 for (unsigned i = 0; i != 4; ++i)
3202 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3203 bool AnyOutOrder = false;
3204 for (unsigned i = 4; i != 8; ++i) {
3205 SDOperand Elt = MaskElts[i];
3206 if (Elt.getOpcode() == ISD::UNDEF) {
3207 MaskVec.push_back(Elt);
3210 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3213 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3214 // If this element is in the right place after this shuffle, then
3216 if ((int)(EltIdx / 4) == BestHighQuad)
3221 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3222 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3226 // The other elements are put in the right place using pextrw and pinsrw.
3227 for (unsigned i = 0; i != 8; ++i) {
3230 SDOperand Elt = MaskElts[i];
3231 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3234 SDOperand ExtOp = (EltIdx < 8)
3235 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3236 DAG.getConstant(EltIdx, PtrVT))
3237 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3238 DAG.getConstant(EltIdx - 8, PtrVT));
3239 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3240 DAG.getConstant(i, PtrVT));
3245 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3246 ///as few as possible.
3247 // First, let's find out how many elements are already in the right order.
3248 unsigned V1InOrder = 0;
3249 unsigned V1FromV1 = 0;
3250 unsigned V2InOrder = 0;
3251 unsigned V2FromV2 = 0;
3252 SmallVector<SDOperand, 8> V1Elts;
3253 SmallVector<SDOperand, 8> V2Elts;
3254 for (unsigned i = 0; i < 8; ++i) {
3255 SDOperand Elt = MaskElts[i];
3256 if (Elt.getOpcode() == ISD::UNDEF) {
3257 V1Elts.push_back(Elt);
3258 V2Elts.push_back(Elt);
3263 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3265 V1Elts.push_back(Elt);
3266 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3268 } else if (EltIdx == i+8) {
3269 V1Elts.push_back(Elt);
3270 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3272 } else if (EltIdx < 8) {
3273 V1Elts.push_back(Elt);
3276 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3281 if (V2InOrder > V1InOrder) {
3282 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3284 std::swap(V1Elts, V2Elts);
3285 std::swap(V1FromV1, V2FromV2);
3288 if ((V1FromV1 + V1InOrder) != 8) {
3289 // Some elements are from V2.
3291 // If there are elements that are from V1 but out of place,
3292 // then first sort them in place
3293 SmallVector<SDOperand, 8> MaskVec;
3294 for (unsigned i = 0; i < 8; ++i) {
3295 SDOperand Elt = V1Elts[i];
3296 if (Elt.getOpcode() == ISD::UNDEF) {
3297 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3300 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3302 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3304 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3306 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3307 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3311 for (unsigned i = 0; i < 8; ++i) {
3312 SDOperand Elt = V1Elts[i];
3313 if (Elt.getOpcode() == ISD::UNDEF)
3315 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3318 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3319 DAG.getConstant(EltIdx - 8, PtrVT));
3320 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3321 DAG.getConstant(i, PtrVT));
3325 // All elements are from V1.
3327 for (unsigned i = 0; i < 8; ++i) {
3328 SDOperand Elt = V1Elts[i];
3329 if (Elt.getOpcode() == ISD::UNDEF)
3331 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3332 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3333 DAG.getConstant(EltIdx, PtrVT));
3334 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3335 DAG.getConstant(i, PtrVT));
3341 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3342 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3343 /// done when every pair / quad of shuffle mask elements point to elements in
3344 /// the right sequence. e.g.
3345 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3347 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3349 SDOperand PermMask, SelectionDAG &DAG,
3350 TargetLowering &TLI) {
3351 unsigned NumElems = PermMask.getNumOperands();
3352 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3353 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3354 MVT::ValueType NewVT = MaskVT;
3356 case MVT::v4f32: NewVT = MVT::v2f64; break;
3357 case MVT::v4i32: NewVT = MVT::v2i64; break;
3358 case MVT::v8i16: NewVT = MVT::v4i32; break;
3359 case MVT::v16i8: NewVT = MVT::v4i32; break;
3360 default: assert(false && "Unexpected!");
3363 if (NewWidth == 2) {
3364 if (MVT::isInteger(VT))
3369 unsigned Scale = NumElems / NewWidth;
3370 SmallVector<SDOperand, 8> MaskVec;
3371 for (unsigned i = 0; i < NumElems; i += Scale) {
3372 unsigned StartIdx = ~0U;
3373 for (unsigned j = 0; j < Scale; ++j) {
3374 SDOperand Elt = PermMask.getOperand(i+j);
3375 if (Elt.getOpcode() == ISD::UNDEF)
3377 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3378 if (StartIdx == ~0U)
3379 StartIdx = EltIdx - (EltIdx % Scale);
3380 if (EltIdx != StartIdx + j)
3383 if (StartIdx == ~0U)
3384 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3386 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3389 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3390 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3391 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3392 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3393 &MaskVec[0], MaskVec.size()));
3397 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3398 SDOperand V1 = Op.getOperand(0);
3399 SDOperand V2 = Op.getOperand(1);
3400 SDOperand PermMask = Op.getOperand(2);
3401 MVT::ValueType VT = Op.getValueType();
3402 unsigned NumElems = PermMask.getNumOperands();
3403 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3404 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3405 bool V1IsSplat = false;
3406 bool V2IsSplat = false;
3408 if (isUndefShuffle(Op.Val))
3409 return DAG.getNode(ISD::UNDEF, VT);
3411 if (isZeroShuffle(Op.Val))
3412 return getZeroVector(VT, DAG);
3414 if (isIdentityMask(PermMask.Val))
3416 else if (isIdentityMask(PermMask.Val, true))
3419 if (isSplatMask(PermMask.Val)) {
3420 if (NumElems <= 4) return Op;
3421 // Promote it to a v4i32 splat.
3422 return PromoteSplat(Op, DAG);
3425 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3427 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3428 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3430 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3431 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3432 // FIXME: Figure out a cleaner way to do this.
3433 // Try to make use of movq to zero out the top part.
3434 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3435 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3437 SDOperand NewV1 = NewOp.getOperand(0);
3438 SDOperand NewV2 = NewOp.getOperand(1);
3439 SDOperand NewMask = NewOp.getOperand(2);
3440 if (isCommutedMOVL(NewMask.Val, true, false)) {
3441 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3442 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3443 NewV1, NewV2, getMOVLMask(2, DAG));
3444 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3447 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3448 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3449 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3450 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3454 if (X86::isMOVLMask(PermMask.Val))
3455 return (V1IsUndef) ? V2 : Op;
3457 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3458 X86::isMOVSLDUPMask(PermMask.Val) ||
3459 X86::isMOVHLPSMask(PermMask.Val) ||
3460 X86::isMOVHPMask(PermMask.Val) ||
3461 X86::isMOVLPMask(PermMask.Val))
3464 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3465 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3466 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3468 bool Commuted = false;
3469 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3470 // 1,1,1,1 -> v8i16 though.
3471 V1IsSplat = isSplatVector(V1.Val);
3472 V2IsSplat = isSplatVector(V2.Val);
3474 // Canonicalize the splat or undef, if present, to be on the RHS.
3475 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3476 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3477 std::swap(V1IsSplat, V2IsSplat);
3478 std::swap(V1IsUndef, V2IsUndef);
3482 // FIXME: Figure out a cleaner way to do this.
3483 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3484 if (V2IsUndef) return V1;
3485 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3487 // V2 is a splat, so the mask may be malformed. That is, it may point
3488 // to any V2 element. The instruction selectior won't like this. Get
3489 // a corrected mask and commute to form a proper MOVS{S|D}.
3490 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3491 if (NewMask.Val != PermMask.Val)
3492 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3497 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3498 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3499 X86::isUNPCKLMask(PermMask.Val) ||
3500 X86::isUNPCKHMask(PermMask.Val))
3504 // Normalize mask so all entries that point to V2 points to its first
3505 // element then try to match unpck{h|l} again. If match, return a
3506 // new vector_shuffle with the corrected mask.
3507 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3508 if (NewMask.Val != PermMask.Val) {
3509 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3510 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3511 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3512 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3513 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3514 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3519 // Normalize the node to match x86 shuffle ops if needed
3520 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3521 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3524 // Commute is back and try unpck* again.
3525 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3526 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3527 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3528 X86::isUNPCKLMask(PermMask.Val) ||
3529 X86::isUNPCKHMask(PermMask.Val))
3533 // If VT is integer, try PSHUF* first, then SHUFP*.
3534 if (MVT::isInteger(VT)) {
3535 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3536 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3537 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3538 X86::isPSHUFDMask(PermMask.Val)) ||
3539 X86::isPSHUFHWMask(PermMask.Val) ||
3540 X86::isPSHUFLWMask(PermMask.Val)) {
3541 if (V2.getOpcode() != ISD::UNDEF)
3542 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3543 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3547 if (X86::isSHUFPMask(PermMask.Val) &&
3548 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3551 // Floating point cases in the other order.
3552 if (X86::isSHUFPMask(PermMask.Val))
3554 if (X86::isPSHUFDMask(PermMask.Val) ||
3555 X86::isPSHUFHWMask(PermMask.Val) ||
3556 X86::isPSHUFLWMask(PermMask.Val)) {
3557 if (V2.getOpcode() != ISD::UNDEF)
3558 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3559 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3564 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3565 if (VT == MVT::v8i16) {
3566 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3571 // Handle all 4 wide cases with a number of shuffles.
3572 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3573 // Don't do this for MMX.
3574 MVT::ValueType MaskVT = PermMask.getValueType();
3575 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3576 SmallVector<std::pair<int, int>, 8> Locs;
3577 Locs.reserve(NumElems);
3578 SmallVector<SDOperand, 8> Mask1(NumElems,
3579 DAG.getNode(ISD::UNDEF, MaskEVT));
3580 SmallVector<SDOperand, 8> Mask2(NumElems,
3581 DAG.getNode(ISD::UNDEF, MaskEVT));
3584 // If no more than two elements come from either vector. This can be
3585 // implemented with two shuffles. First shuffle gather the elements.
3586 // The second shuffle, which takes the first shuffle as both of its
3587 // vector operands, put the elements into the right order.
3588 for (unsigned i = 0; i != NumElems; ++i) {
3589 SDOperand Elt = PermMask.getOperand(i);
3590 if (Elt.getOpcode() == ISD::UNDEF) {
3591 Locs[i] = std::make_pair(-1, -1);
3593 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3594 if (Val < NumElems) {
3595 Locs[i] = std::make_pair(0, NumLo);
3599 Locs[i] = std::make_pair(1, NumHi);
3600 if (2+NumHi < NumElems)
3601 Mask1[2+NumHi] = Elt;
3606 if (NumLo <= 2 && NumHi <= 2) {
3607 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3608 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3609 &Mask1[0], Mask1.size()));
3610 for (unsigned i = 0; i != NumElems; ++i) {
3611 if (Locs[i].first == -1)
3614 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3615 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3616 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3620 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3621 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3622 &Mask2[0], Mask2.size()));
3625 // Break it into (shuffle shuffle_hi, shuffle_lo).
3627 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3628 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3629 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3630 unsigned MaskIdx = 0;
3632 unsigned HiIdx = NumElems/2;
3633 for (unsigned i = 0; i != NumElems; ++i) {
3634 if (i == NumElems/2) {
3640 SDOperand Elt = PermMask.getOperand(i);
3641 if (Elt.getOpcode() == ISD::UNDEF) {
3642 Locs[i] = std::make_pair(-1, -1);
3643 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3644 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3645 (*MaskPtr)[LoIdx] = Elt;
3648 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3649 (*MaskPtr)[HiIdx] = Elt;
3654 SDOperand LoShuffle =
3655 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3656 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3657 &LoMask[0], LoMask.size()));
3658 SDOperand HiShuffle =
3659 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3660 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3661 &HiMask[0], HiMask.size()));
3662 SmallVector<SDOperand, 8> MaskOps;
3663 for (unsigned i = 0; i != NumElems; ++i) {
3664 if (Locs[i].first == -1) {
3665 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3667 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3668 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3671 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3672 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3673 &MaskOps[0], MaskOps.size()));
3680 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3681 SelectionDAG &DAG) {
3682 MVT::ValueType VT = Op.getValueType();
3683 if (MVT::getSizeInBits(VT) == 8) {
3684 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3685 Op.getOperand(0), Op.getOperand(1));
3686 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3687 DAG.getValueType(VT));
3688 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3689 } else if (MVT::getSizeInBits(VT) == 16) {
3690 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3691 Op.getOperand(0), Op.getOperand(1));
3692 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3693 DAG.getValueType(VT));
3694 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3701 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3702 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3705 if (Subtarget->hasSSE41())
3706 return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3708 MVT::ValueType VT = Op.getValueType();
3709 // TODO: handle v16i8.
3710 if (MVT::getSizeInBits(VT) == 16) {
3711 SDOperand Vec = Op.getOperand(0);
3712 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3714 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3715 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3716 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3718 // Transform it so it match pextrw which produces a 32-bit result.
3719 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3720 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3721 Op.getOperand(0), Op.getOperand(1));
3722 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3723 DAG.getValueType(VT));
3724 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3725 } else if (MVT::getSizeInBits(VT) == 32) {
3726 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3729 // SHUFPS the element to the lowest double word, then movss.
3730 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3731 SmallVector<SDOperand, 8> IdxVec;
3733 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3735 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3737 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3739 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3740 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3741 &IdxVec[0], IdxVec.size());
3742 SDOperand Vec = Op.getOperand(0);
3743 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3744 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3745 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3746 DAG.getIntPtrConstant(0));
3747 } else if (MVT::getSizeInBits(VT) == 64) {
3748 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3749 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3750 // to match extract_elt for f64.
3751 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3755 // UNPCKHPD the element to the lowest double word, then movsd.
3756 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3757 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3758 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3759 SmallVector<SDOperand, 8> IdxVec;
3760 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3762 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3763 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3764 &IdxVec[0], IdxVec.size());
3765 SDOperand Vec = Op.getOperand(0);
3766 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3767 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3768 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3769 DAG.getIntPtrConstant(0));
3776 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3777 MVT::ValueType VT = Op.getValueType();
3778 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3780 SDOperand N0 = Op.getOperand(0);
3781 SDOperand N1 = Op.getOperand(1);
3782 SDOperand N2 = Op.getOperand(2);
3784 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3785 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3787 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3789 if (N1.getValueType() != MVT::i32)
3790 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3791 if (N2.getValueType() != MVT::i32)
3792 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3793 return DAG.getNode(Opc, VT, N0, N1, N2);
3794 } else if (EVT == MVT::f32) {
3795 // Bits [7:6] of the constant are the source select. This will always be
3796 // zero here. The DAG Combiner may combine an extract_elt index into these
3797 // bits. For example (insert (extract, 3), 2) could be matched by putting
3798 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3799 // Bits [5:4] of the constant are the destination select. This is the
3800 // value of the incoming immediate.
3801 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3802 // combine either bitwise AND or insert of float 0.0 to set these bits.
3803 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3804 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3810 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3811 MVT::ValueType VT = Op.getValueType();
3812 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3814 if (Subtarget->hasSSE41())
3815 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3820 SDOperand N0 = Op.getOperand(0);
3821 SDOperand N1 = Op.getOperand(1);
3822 SDOperand N2 = Op.getOperand(2);
3824 if (MVT::getSizeInBits(EVT) == 16) {
3825 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3826 // as its second argument.
3827 if (N1.getValueType() != MVT::i32)
3828 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3829 if (N2.getValueType() != MVT::i32)
3830 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3831 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3837 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3838 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3839 MVT::ValueType VT = MVT::v2i32;
3840 switch (Op.getValueType()) {
3847 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3848 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3851 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3852 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3853 // one of the above mentioned nodes. It has to be wrapped because otherwise
3854 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3855 // be used to form addressing mode. These wrapped nodes will be selected
3858 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3859 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3860 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3862 CP->getAlignment());
3863 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3864 // With PIC, the address is actually $g + Offset.
3865 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3866 !Subtarget->isPICStyleRIPRel()) {
3867 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3868 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3876 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3877 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3878 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3879 // If it's a debug information descriptor, don't mess with it.
3880 if (DAG.isVerifiedDebugInfoDesc(Op))
3882 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3883 // With PIC, the address is actually $g + Offset.
3884 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3885 !Subtarget->isPICStyleRIPRel()) {
3886 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3887 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3891 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3892 // load the value at address GV, not the value of GV itself. This means that
3893 // the GlobalAddress must be in the base or index register of the address, not
3894 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3895 // The same applies for external symbols during PIC codegen
3896 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3897 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3898 PseudoSourceValue::getGOT(), 0);
3903 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3905 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3906 const MVT::ValueType PtrVT) {
3908 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3909 DAG.getNode(X86ISD::GlobalBaseReg,
3911 InFlag = Chain.getValue(1);
3913 // emit leal symbol@TLSGD(,%ebx,1), %eax
3914 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3915 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3916 GA->getValueType(0),
3918 SDOperand Ops[] = { Chain, TGA, InFlag };
3919 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3920 InFlag = Result.getValue(2);
3921 Chain = Result.getValue(1);
3923 // call ___tls_get_addr. This function receives its argument in
3924 // the register EAX.
3925 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3926 InFlag = Chain.getValue(1);
3928 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3929 SDOperand Ops1[] = { Chain,
3930 DAG.getTargetExternalSymbol("___tls_get_addr",
3932 DAG.getRegister(X86::EAX, PtrVT),
3933 DAG.getRegister(X86::EBX, PtrVT),
3935 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3936 InFlag = Chain.getValue(1);
3938 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3941 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3942 // "local exec" model.
3944 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3945 const MVT::ValueType PtrVT) {
3946 // Get the Thread Pointer
3947 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3948 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3950 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3951 GA->getValueType(0),
3953 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3955 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3956 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
3957 PseudoSourceValue::getGOT(), 0);
3959 // The address of the thread local variable is the add of the thread
3960 // pointer with the offset of the variable.
3961 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3965 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3966 // TODO: implement the "local dynamic" model
3967 // TODO: implement the "initial exec"model for pic executables
3968 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3969 "TLS not implemented for non-ELF and 64-bit targets");
3970 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3971 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3972 // otherwise use the "Local Exec"TLS Model
3973 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3974 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3976 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3980 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3981 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3982 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3983 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3984 // With PIC, the address is actually $g + Offset.
3985 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3986 !Subtarget->isPICStyleRIPRel()) {
3987 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3988 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3995 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3996 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3997 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3998 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3999 // With PIC, the address is actually $g + Offset.
4000 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4001 !Subtarget->isPICStyleRIPRel()) {
4002 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4003 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4010 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4011 /// take a 2 x i32 value to shift plus a shift amount.
4012 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4013 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4014 "Not an i64 shift!");
4015 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4016 SDOperand ShOpLo = Op.getOperand(0);
4017 SDOperand ShOpHi = Op.getOperand(1);
4018 SDOperand ShAmt = Op.getOperand(2);
4019 SDOperand Tmp1 = isSRA ?
4020 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4021 DAG.getConstant(0, MVT::i32);
4023 SDOperand Tmp2, Tmp3;
4024 if (Op.getOpcode() == ISD::SHL_PARTS) {
4025 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4026 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4028 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4029 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4032 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4033 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4034 DAG.getConstant(32, MVT::i8));
4035 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4036 AndNode, DAG.getConstant(0, MVT::i8));
4039 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4040 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4041 SmallVector<SDOperand, 4> Ops;
4042 if (Op.getOpcode() == ISD::SHL_PARTS) {
4043 Ops.push_back(Tmp2);
4044 Ops.push_back(Tmp3);
4046 Ops.push_back(Cond);
4047 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4050 Ops.push_back(Tmp3);
4051 Ops.push_back(Tmp1);
4053 Ops.push_back(Cond);
4054 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4056 Ops.push_back(Tmp2);
4057 Ops.push_back(Tmp3);
4059 Ops.push_back(Cond);
4060 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4063 Ops.push_back(Tmp3);
4064 Ops.push_back(Tmp1);
4066 Ops.push_back(Cond);
4067 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4070 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4074 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4077 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4078 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4079 Op.getOperand(0).getValueType() >= MVT::i16 &&
4080 "Unknown SINT_TO_FP to lower!");
4083 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4084 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4085 MachineFunction &MF = DAG.getMachineFunction();
4086 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4087 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4088 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4090 PseudoSourceValue::getFixedStack(),
4093 // These are really Legal; caller falls through into that case.
4094 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4096 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4097 Subtarget->is64Bit())
4102 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4104 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4106 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4107 SmallVector<SDOperand, 8> Ops;
4108 Ops.push_back(Chain);
4109 Ops.push_back(StackSlot);
4110 Ops.push_back(DAG.getValueType(SrcVT));
4111 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4112 Tys, &Ops[0], Ops.size());
4115 Chain = Result.getValue(1);
4116 SDOperand InFlag = Result.getValue(2);
4118 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4119 // shouldn't be necessary except that RFP cannot be live across
4120 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4121 MachineFunction &MF = DAG.getMachineFunction();
4122 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4123 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4124 Tys = DAG.getVTList(MVT::Other);
4125 SmallVector<SDOperand, 8> Ops;
4126 Ops.push_back(Chain);
4127 Ops.push_back(Result);
4128 Ops.push_back(StackSlot);
4129 Ops.push_back(DAG.getValueType(Op.getValueType()));
4130 Ops.push_back(InFlag);
4131 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4132 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4133 PseudoSourceValue::getFixedStack(), SSFI);
4139 std::pair<SDOperand,SDOperand> X86TargetLowering::
4140 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4141 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4142 "Unknown FP_TO_SINT to lower!");
4144 // These are really Legal.
4145 if (Op.getValueType() == MVT::i32 &&
4146 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4147 return std::make_pair(SDOperand(), SDOperand());
4148 if (Subtarget->is64Bit() &&
4149 Op.getValueType() == MVT::i64 &&
4150 Op.getOperand(0).getValueType() != MVT::f80)
4151 return std::make_pair(SDOperand(), SDOperand());
4153 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4155 MachineFunction &MF = DAG.getMachineFunction();
4156 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4157 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4158 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4160 switch (Op.getValueType()) {
4161 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4162 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4163 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4164 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4167 SDOperand Chain = DAG.getEntryNode();
4168 SDOperand Value = Op.getOperand(0);
4169 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4170 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4171 Chain = DAG.getStore(Chain, Value, StackSlot,
4172 PseudoSourceValue::getFixedStack(), SSFI);
4173 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4175 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4177 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4178 Chain = Value.getValue(1);
4179 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4180 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4183 // Build the FP_TO_INT*_IN_MEM
4184 SDOperand Ops[] = { Chain, Value, StackSlot };
4185 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4187 return std::make_pair(FIST, StackSlot);
4190 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4191 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4192 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4193 if (FIST.Val == 0) return SDOperand();
4196 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4199 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4200 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4201 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4202 if (FIST.Val == 0) return 0;
4204 // Return an i64 load from the stack slot.
4205 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4207 // Use a MERGE_VALUES node to drop the chain result value.
4208 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4211 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4212 MVT::ValueType VT = Op.getValueType();
4213 MVT::ValueType EltVT = VT;
4214 if (MVT::isVector(VT))
4215 EltVT = MVT::getVectorElementType(VT);
4216 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4217 std::vector<Constant*> CV;
4218 if (EltVT == MVT::f64) {
4219 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4223 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4229 Constant *C = ConstantVector::get(CV);
4230 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4231 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4232 PseudoSourceValue::getConstantPool(), 0,
4234 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4237 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4238 MVT::ValueType VT = Op.getValueType();
4239 MVT::ValueType EltVT = VT;
4240 unsigned EltNum = 1;
4241 if (MVT::isVector(VT)) {
4242 EltVT = MVT::getVectorElementType(VT);
4243 EltNum = MVT::getVectorNumElements(VT);
4245 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4246 std::vector<Constant*> CV;
4247 if (EltVT == MVT::f64) {
4248 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4252 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4258 Constant *C = ConstantVector::get(CV);
4259 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4260 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4261 PseudoSourceValue::getConstantPool(), 0,
4263 if (MVT::isVector(VT)) {
4264 return DAG.getNode(ISD::BIT_CONVERT, VT,
4265 DAG.getNode(ISD::XOR, MVT::v2i64,
4266 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4267 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4269 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4273 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4274 SDOperand Op0 = Op.getOperand(0);
4275 SDOperand Op1 = Op.getOperand(1);
4276 MVT::ValueType VT = Op.getValueType();
4277 MVT::ValueType SrcVT = Op1.getValueType();
4278 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4280 // If second operand is smaller, extend it first.
4281 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4282 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4284 SrcTy = MVT::getTypeForValueType(SrcVT);
4286 // And if it is bigger, shrink it first.
4287 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4288 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4290 SrcTy = MVT::getTypeForValueType(SrcVT);
4293 // At this point the operands and the result should have the same
4294 // type, and that won't be f80 since that is not custom lowered.
4296 // First get the sign bit of second operand.
4297 std::vector<Constant*> CV;
4298 if (SrcVT == MVT::f64) {
4299 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4300 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4302 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4303 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4304 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4305 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4307 Constant *C = ConstantVector::get(CV);
4308 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4309 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4310 PseudoSourceValue::getConstantPool(), 0,
4312 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4314 // Shift sign bit right or left if the two operands have different types.
4315 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4316 // Op0 is MVT::f32, Op1 is MVT::f64.
4317 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4318 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4319 DAG.getConstant(32, MVT::i32));
4320 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4321 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4322 DAG.getIntPtrConstant(0));
4325 // Clear first operand sign bit.
4327 if (VT == MVT::f64) {
4328 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4329 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4331 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4332 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4333 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4334 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4336 C = ConstantVector::get(CV);
4337 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4338 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4339 PseudoSourceValue::getConstantPool(), 0,
4341 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4343 // Or the value with the sign bit.
4344 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4347 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4348 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4350 SDOperand Op0 = Op.getOperand(0);
4351 SDOperand Op1 = Op.getOperand(1);
4352 SDOperand CC = Op.getOperand(2);
4353 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4354 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4357 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4359 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4360 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4361 DAG.getConstant(X86CC, MVT::i8), Cond);
4364 assert(isFP && "Illegal integer SetCC!");
4366 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4367 switch (SetCCOpcode) {
4368 default: assert(false && "Illegal floating point SetCC!");
4369 case ISD::SETOEQ: { // !PF & ZF
4370 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4371 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4372 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4373 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4374 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4376 case ISD::SETUNE: { // PF | !ZF
4377 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4378 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4379 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4380 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4381 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4387 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4388 bool addTest = true;
4389 SDOperand Cond = Op.getOperand(0);
4392 if (Cond.getOpcode() == ISD::SETCC)
4393 Cond = LowerSETCC(Cond, DAG);
4395 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4396 // setting operand in place of the X86ISD::SETCC.
4397 if (Cond.getOpcode() == X86ISD::SETCC) {
4398 CC = Cond.getOperand(0);
4400 SDOperand Cmp = Cond.getOperand(1);
4401 unsigned Opc = Cmp.getOpcode();
4402 MVT::ValueType VT = Op.getValueType();
4404 bool IllegalFPCMov = false;
4405 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4406 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4407 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4409 if ((Opc == X86ISD::CMP ||
4410 Opc == X86ISD::COMI ||
4411 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4418 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4419 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4422 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4424 SmallVector<SDOperand, 4> Ops;
4425 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4426 // condition is true.
4427 Ops.push_back(Op.getOperand(2));
4428 Ops.push_back(Op.getOperand(1));
4430 Ops.push_back(Cond);
4431 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4434 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4435 bool addTest = true;
4436 SDOperand Chain = Op.getOperand(0);
4437 SDOperand Cond = Op.getOperand(1);
4438 SDOperand Dest = Op.getOperand(2);
4441 if (Cond.getOpcode() == ISD::SETCC)
4442 Cond = LowerSETCC(Cond, DAG);
4444 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4445 // setting operand in place of the X86ISD::SETCC.
4446 if (Cond.getOpcode() == X86ISD::SETCC) {
4447 CC = Cond.getOperand(0);
4449 SDOperand Cmp = Cond.getOperand(1);
4450 unsigned Opc = Cmp.getOpcode();
4451 if (Opc == X86ISD::CMP ||
4452 Opc == X86ISD::COMI ||
4453 Opc == X86ISD::UCOMI) {
4460 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4461 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4463 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4464 Chain, Op.getOperand(2), CC, Cond);
4468 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4469 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4470 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4471 // that the guard pages used by the OS virtual memory manager are allocated in
4472 // correct sequence.
4474 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4475 SelectionDAG &DAG) {
4476 assert(Subtarget->isTargetCygMing() &&
4477 "This should be used only on Cygwin/Mingw targets");
4480 SDOperand Chain = Op.getOperand(0);
4481 SDOperand Size = Op.getOperand(1);
4482 // FIXME: Ensure alignment here
4486 MVT::ValueType IntPtr = getPointerTy();
4487 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4489 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4490 Flag = Chain.getValue(1);
4492 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4493 SDOperand Ops[] = { Chain,
4494 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4495 DAG.getRegister(X86::EAX, IntPtr),
4497 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4498 Flag = Chain.getValue(1);
4500 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4502 std::vector<MVT::ValueType> Tys;
4503 Tys.push_back(SPTy);
4504 Tys.push_back(MVT::Other);
4505 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4506 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4509 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4510 SDOperand InFlag(0, 0);
4511 SDOperand Chain = Op.getOperand(0);
4513 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4514 if (Align == 0) Align = 1;
4516 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4517 // If not DWORD aligned or size is more than the threshold, call memset.
4518 // The libc version is likely to be faster for these cases. It can use the
4519 // address value and run time information about the CPU.
4520 if ((Align & 3) != 0 ||
4521 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4522 MVT::ValueType IntPtr = getPointerTy();
4523 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4524 TargetLowering::ArgListTy Args;
4525 TargetLowering::ArgListEntry Entry;
4526 Entry.Node = Op.getOperand(1);
4527 Entry.Ty = IntPtrTy;
4528 Args.push_back(Entry);
4529 // Extend the unsigned i8 argument to be an int value for the call.
4530 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4531 Entry.Ty = IntPtrTy;
4532 Args.push_back(Entry);
4533 Entry.Node = Op.getOperand(3);
4534 Args.push_back(Entry);
4535 std::pair<SDOperand,SDOperand> CallResult =
4536 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4537 false, DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4538 return CallResult.second;
4543 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4544 unsigned BytesLeft = 0;
4545 bool TwoRepStos = false;
4548 uint64_t Val = ValC->getValue() & 255;
4550 // If the value is a constant, then we can potentially use larger sets.
4551 switch (Align & 3) {
4552 case 2: // WORD aligned
4555 Val = (Val << 8) | Val;
4557 case 0: // DWORD aligned
4560 Val = (Val << 8) | Val;
4561 Val = (Val << 16) | Val;
4562 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4565 Val = (Val << 32) | Val;
4568 default: // Byte aligned
4571 Count = Op.getOperand(3);
4575 if (AVT > MVT::i8) {
4577 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4578 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4579 BytesLeft = I->getValue() % UBytes;
4581 assert(AVT >= MVT::i32 &&
4582 "Do not use rep;stos if not at least DWORD aligned");
4583 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4584 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4589 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4591 InFlag = Chain.getValue(1);
4594 Count = Op.getOperand(3);
4595 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4596 InFlag = Chain.getValue(1);
4599 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4601 InFlag = Chain.getValue(1);
4602 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4603 Op.getOperand(1), InFlag);
4604 InFlag = Chain.getValue(1);
4606 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4607 SmallVector<SDOperand, 8> Ops;
4608 Ops.push_back(Chain);
4609 Ops.push_back(DAG.getValueType(AVT));
4610 Ops.push_back(InFlag);
4611 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4614 InFlag = Chain.getValue(1);
4615 Count = Op.getOperand(3);
4616 MVT::ValueType CVT = Count.getValueType();
4617 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4618 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4619 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4621 InFlag = Chain.getValue(1);
4622 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4624 Ops.push_back(Chain);
4625 Ops.push_back(DAG.getValueType(MVT::i8));
4626 Ops.push_back(InFlag);
4627 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4628 } else if (BytesLeft) {
4629 // Issue stores for the last 1 - 7 bytes.
4631 unsigned Val = ValC->getValue() & 255;
4632 unsigned Offset = I->getValue() - BytesLeft;
4633 SDOperand DstAddr = Op.getOperand(1);
4634 MVT::ValueType AddrVT = DstAddr.getValueType();
4635 if (BytesLeft >= 4) {
4636 Val = (Val << 8) | Val;
4637 Val = (Val << 16) | Val;
4638 Value = DAG.getConstant(Val, MVT::i32);
4639 Chain = DAG.getStore(Chain, Value,
4640 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4641 DAG.getConstant(Offset, AddrVT)),
4646 if (BytesLeft >= 2) {
4647 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4648 Chain = DAG.getStore(Chain, Value,
4649 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4650 DAG.getConstant(Offset, AddrVT)),
4655 if (BytesLeft == 1) {
4656 Value = DAG.getConstant(Val, MVT::i8);
4657 Chain = DAG.getStore(Chain, Value,
4658 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4659 DAG.getConstant(Offset, AddrVT)),
4667 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4672 SelectionDAG &DAG) {
4674 unsigned BytesLeft = 0;
4675 switch (Align & 3) {
4676 case 2: // WORD aligned
4679 case 0: // DWORD aligned
4681 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4684 default: // Byte aligned
4689 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4690 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4691 BytesLeft = Size % UBytes;
4693 SDOperand InFlag(0, 0);
4694 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4696 InFlag = Chain.getValue(1);
4697 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4699 InFlag = Chain.getValue(1);
4700 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4702 InFlag = Chain.getValue(1);
4704 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4705 SmallVector<SDOperand, 8> Ops;
4706 Ops.push_back(Chain);
4707 Ops.push_back(DAG.getValueType(AVT));
4708 Ops.push_back(InFlag);
4709 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4712 // Issue loads and stores for the last 1 - 7 bytes.
4713 unsigned Offset = Size - BytesLeft;
4714 SDOperand DstAddr = Dest;
4715 MVT::ValueType DstVT = DstAddr.getValueType();
4716 SDOperand SrcAddr = Source;
4717 MVT::ValueType SrcVT = SrcAddr.getValueType();
4719 if (BytesLeft >= 4) {
4720 Value = DAG.getLoad(MVT::i32, Chain,
4721 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4722 DAG.getConstant(Offset, SrcVT)),
4724 Chain = Value.getValue(1);
4725 Chain = DAG.getStore(Chain, Value,
4726 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4727 DAG.getConstant(Offset, DstVT)),
4732 if (BytesLeft >= 2) {
4733 Value = DAG.getLoad(MVT::i16, Chain,
4734 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4735 DAG.getConstant(Offset, SrcVT)),
4737 Chain = Value.getValue(1);
4738 Chain = DAG.getStore(Chain, Value,
4739 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4740 DAG.getConstant(Offset, DstVT)),
4746 if (BytesLeft == 1) {
4747 Value = DAG.getLoad(MVT::i8, Chain,
4748 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4749 DAG.getConstant(Offset, SrcVT)),
4751 Chain = Value.getValue(1);
4752 Chain = DAG.getStore(Chain, Value,
4753 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4754 DAG.getConstant(Offset, DstVT)),
4762 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4763 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4764 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4765 SDOperand TheChain = N->getOperand(0);
4766 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4767 if (Subtarget->is64Bit()) {
4768 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4769 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4770 MVT::i64, rax.getValue(2));
4771 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4772 DAG.getConstant(32, MVT::i8));
4774 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4777 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4778 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4781 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4782 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4783 MVT::i32, eax.getValue(2));
4784 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4785 SDOperand Ops[] = { eax, edx };
4786 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4788 // Use a MERGE_VALUES to return the value and chain.
4789 Ops[1] = edx.getValue(1);
4790 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4791 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4794 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4795 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4797 if (!Subtarget->is64Bit()) {
4798 // vastart just stores the address of the VarArgsFrameIndex slot into the
4799 // memory location argument.
4800 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4801 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4805 // gp_offset (0 - 6 * 8)
4806 // fp_offset (48 - 48 + 8 * 16)
4807 // overflow_arg_area (point to parameters coming in memory).
4809 SmallVector<SDOperand, 8> MemOps;
4810 SDOperand FIN = Op.getOperand(1);
4812 SDOperand Store = DAG.getStore(Op.getOperand(0),
4813 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4815 MemOps.push_back(Store);
4818 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4819 Store = DAG.getStore(Op.getOperand(0),
4820 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4822 MemOps.push_back(Store);
4824 // Store ptr to overflow_arg_area
4825 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4826 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4827 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4828 MemOps.push_back(Store);
4830 // Store ptr to reg_save_area.
4831 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4832 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4833 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4834 MemOps.push_back(Store);
4835 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4838 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4839 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4840 SDOperand Chain = Op.getOperand(0);
4841 SDOperand DstPtr = Op.getOperand(1);
4842 SDOperand SrcPtr = Op.getOperand(2);
4843 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4844 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4846 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4847 Chain = SrcPtr.getValue(1);
4848 for (unsigned i = 0; i < 3; ++i) {
4849 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4850 Chain = Val.getValue(1);
4851 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4854 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4855 DAG.getIntPtrConstant(8));
4856 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4857 DAG.getIntPtrConstant(8));
4863 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4864 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4866 default: return SDOperand(); // Don't custom lower most intrinsics.
4867 // Comparison intrinsics.
4868 case Intrinsic::x86_sse_comieq_ss:
4869 case Intrinsic::x86_sse_comilt_ss:
4870 case Intrinsic::x86_sse_comile_ss:
4871 case Intrinsic::x86_sse_comigt_ss:
4872 case Intrinsic::x86_sse_comige_ss:
4873 case Intrinsic::x86_sse_comineq_ss:
4874 case Intrinsic::x86_sse_ucomieq_ss:
4875 case Intrinsic::x86_sse_ucomilt_ss:
4876 case Intrinsic::x86_sse_ucomile_ss:
4877 case Intrinsic::x86_sse_ucomigt_ss:
4878 case Intrinsic::x86_sse_ucomige_ss:
4879 case Intrinsic::x86_sse_ucomineq_ss:
4880 case Intrinsic::x86_sse2_comieq_sd:
4881 case Intrinsic::x86_sse2_comilt_sd:
4882 case Intrinsic::x86_sse2_comile_sd:
4883 case Intrinsic::x86_sse2_comigt_sd:
4884 case Intrinsic::x86_sse2_comige_sd:
4885 case Intrinsic::x86_sse2_comineq_sd:
4886 case Intrinsic::x86_sse2_ucomieq_sd:
4887 case Intrinsic::x86_sse2_ucomilt_sd:
4888 case Intrinsic::x86_sse2_ucomile_sd:
4889 case Intrinsic::x86_sse2_ucomigt_sd:
4890 case Intrinsic::x86_sse2_ucomige_sd:
4891 case Intrinsic::x86_sse2_ucomineq_sd: {
4893 ISD::CondCode CC = ISD::SETCC_INVALID;
4896 case Intrinsic::x86_sse_comieq_ss:
4897 case Intrinsic::x86_sse2_comieq_sd:
4901 case Intrinsic::x86_sse_comilt_ss:
4902 case Intrinsic::x86_sse2_comilt_sd:
4906 case Intrinsic::x86_sse_comile_ss:
4907 case Intrinsic::x86_sse2_comile_sd:
4911 case Intrinsic::x86_sse_comigt_ss:
4912 case Intrinsic::x86_sse2_comigt_sd:
4916 case Intrinsic::x86_sse_comige_ss:
4917 case Intrinsic::x86_sse2_comige_sd:
4921 case Intrinsic::x86_sse_comineq_ss:
4922 case Intrinsic::x86_sse2_comineq_sd:
4926 case Intrinsic::x86_sse_ucomieq_ss:
4927 case Intrinsic::x86_sse2_ucomieq_sd:
4928 Opc = X86ISD::UCOMI;
4931 case Intrinsic::x86_sse_ucomilt_ss:
4932 case Intrinsic::x86_sse2_ucomilt_sd:
4933 Opc = X86ISD::UCOMI;
4936 case Intrinsic::x86_sse_ucomile_ss:
4937 case Intrinsic::x86_sse2_ucomile_sd:
4938 Opc = X86ISD::UCOMI;
4941 case Intrinsic::x86_sse_ucomigt_ss:
4942 case Intrinsic::x86_sse2_ucomigt_sd:
4943 Opc = X86ISD::UCOMI;
4946 case Intrinsic::x86_sse_ucomige_ss:
4947 case Intrinsic::x86_sse2_ucomige_sd:
4948 Opc = X86ISD::UCOMI;
4951 case Intrinsic::x86_sse_ucomineq_ss:
4952 case Intrinsic::x86_sse2_ucomineq_sd:
4953 Opc = X86ISD::UCOMI;
4959 SDOperand LHS = Op.getOperand(1);
4960 SDOperand RHS = Op.getOperand(2);
4961 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4963 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4964 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4965 DAG.getConstant(X86CC, MVT::i8), Cond);
4966 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4971 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4972 // Depths > 0 not supported yet!
4973 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4976 // Just load the return address
4977 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4978 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4981 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4982 // Depths > 0 not supported yet!
4983 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4986 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4987 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4988 DAG.getIntPtrConstant(4));
4991 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4992 SelectionDAG &DAG) {
4993 // Is not yet supported on x86-64
4994 if (Subtarget->is64Bit())
4997 return DAG.getIntPtrConstant(8);
5000 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5002 assert(!Subtarget->is64Bit() &&
5003 "Lowering of eh_return builtin is not supported yet on x86-64");
5005 MachineFunction &MF = DAG.getMachineFunction();
5006 SDOperand Chain = Op.getOperand(0);
5007 SDOperand Offset = Op.getOperand(1);
5008 SDOperand Handler = Op.getOperand(2);
5010 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5013 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5014 DAG.getIntPtrConstant(-4UL));
5015 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5016 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5017 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5018 MF.getRegInfo().addLiveOut(X86::ECX);
5020 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5021 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5024 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5025 SelectionDAG &DAG) {
5026 SDOperand Root = Op.getOperand(0);
5027 SDOperand Trmp = Op.getOperand(1); // trampoline
5028 SDOperand FPtr = Op.getOperand(2); // nested function
5029 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5031 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5033 const X86InstrInfo *TII =
5034 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5036 if (Subtarget->is64Bit()) {
5037 SDOperand OutChains[6];
5039 // Large code-model.
5041 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5042 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5044 const unsigned char N86R10 =
5045 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5046 const unsigned char N86R11 =
5047 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5049 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5051 // Load the pointer to the nested function into R11.
5052 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5053 SDOperand Addr = Trmp;
5054 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5057 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5058 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5060 // Load the 'nest' parameter value into R10.
5061 // R10 is specified in X86CallingConv.td
5062 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5063 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5064 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5067 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5068 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5070 // Jump to the nested function.
5071 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5072 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5073 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5076 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5077 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5078 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5082 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5083 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5085 const Function *Func =
5086 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5087 unsigned CC = Func->getCallingConv();
5092 assert(0 && "Unsupported calling convention");
5093 case CallingConv::C:
5094 case CallingConv::X86_StdCall: {
5095 // Pass 'nest' parameter in ECX.
5096 // Must be kept in sync with X86CallingConv.td
5099 // Check that ECX wasn't needed by an 'inreg' parameter.
5100 const FunctionType *FTy = Func->getFunctionType();
5101 const ParamAttrsList *Attrs = Func->getParamAttrs();
5103 if (Attrs && !Func->isVarArg()) {
5104 unsigned InRegCount = 0;
5107 for (FunctionType::param_iterator I = FTy->param_begin(),
5108 E = FTy->param_end(); I != E; ++I, ++Idx)
5109 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5110 // FIXME: should only count parameters that are lowered to integers.
5111 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5113 if (InRegCount > 2) {
5114 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5120 case CallingConv::X86_FastCall:
5121 // Pass 'nest' parameter in EAX.
5122 // Must be kept in sync with X86CallingConv.td
5127 SDOperand OutChains[4];
5128 SDOperand Addr, Disp;
5130 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5131 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5133 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5134 const unsigned char N86Reg =
5135 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5136 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5139 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5140 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5142 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5143 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5144 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5145 TrmpAddr, 5, false, 1);
5147 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5148 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5151 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5152 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5156 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5158 The rounding mode is in bits 11:10 of FPSR, and has the following
5165 FLT_ROUNDS, on the other hand, expects the following:
5172 To perform the conversion, we do:
5173 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5176 MachineFunction &MF = DAG.getMachineFunction();
5177 const TargetMachine &TM = MF.getTarget();
5178 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5179 unsigned StackAlignment = TFI.getStackAlignment();
5180 MVT::ValueType VT = Op.getValueType();
5182 // Save FP Control Word to stack slot
5183 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5184 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5186 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5187 DAG.getEntryNode(), StackSlot);
5189 // Load FP Control Word from stack slot
5190 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5192 // Transform as necessary
5194 DAG.getNode(ISD::SRL, MVT::i16,
5195 DAG.getNode(ISD::AND, MVT::i16,
5196 CWD, DAG.getConstant(0x800, MVT::i16)),
5197 DAG.getConstant(11, MVT::i8));
5199 DAG.getNode(ISD::SRL, MVT::i16,
5200 DAG.getNode(ISD::AND, MVT::i16,
5201 CWD, DAG.getConstant(0x400, MVT::i16)),
5202 DAG.getConstant(9, MVT::i8));
5205 DAG.getNode(ISD::AND, MVT::i16,
5206 DAG.getNode(ISD::ADD, MVT::i16,
5207 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5208 DAG.getConstant(1, MVT::i16)),
5209 DAG.getConstant(3, MVT::i16));
5212 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5213 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5216 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5217 MVT::ValueType VT = Op.getValueType();
5218 MVT::ValueType OpVT = VT;
5219 unsigned NumBits = MVT::getSizeInBits(VT);
5221 Op = Op.getOperand(0);
5222 if (VT == MVT::i8) {
5223 // Zero extend to i32 since there is not an i8 bsr.
5225 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5228 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5229 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5230 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5232 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5233 SmallVector<SDOperand, 4> Ops;
5235 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5236 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5237 Ops.push_back(Op.getValue(1));
5238 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5240 // Finally xor with NumBits-1.
5241 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5244 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5248 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5249 MVT::ValueType VT = Op.getValueType();
5250 MVT::ValueType OpVT = VT;
5251 unsigned NumBits = MVT::getSizeInBits(VT);
5253 Op = Op.getOperand(0);
5254 if (VT == MVT::i8) {
5256 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5259 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5260 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5261 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5263 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5264 SmallVector<SDOperand, 4> Ops;
5266 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5267 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5268 Ops.push_back(Op.getValue(1));
5269 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5272 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5276 /// LowerOperation - Provide custom lowering hooks for some operations.
5278 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5279 switch (Op.getOpcode()) {
5280 default: assert(0 && "Should not custom lower this!");
5281 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5282 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5283 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5284 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5285 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5286 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5287 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5288 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5289 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5290 case ISD::SHL_PARTS:
5291 case ISD::SRA_PARTS:
5292 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5293 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5294 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5295 case ISD::FABS: return LowerFABS(Op, DAG);
5296 case ISD::FNEG: return LowerFNEG(Op, DAG);
5297 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5298 case ISD::SETCC: return LowerSETCC(Op, DAG);
5299 case ISD::SELECT: return LowerSELECT(Op, DAG);
5300 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5301 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5302 case ISD::CALL: return LowerCALL(Op, DAG);
5303 case ISD::RET: return LowerRET(Op, DAG);
5304 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5305 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5306 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5307 case ISD::VASTART: return LowerVASTART(Op, DAG);
5308 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5309 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5310 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5311 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5312 case ISD::FRAME_TO_ARGS_OFFSET:
5313 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5314 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5315 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5316 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5317 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5318 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5319 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5321 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5322 case ISD::READCYCLECOUNTER:
5323 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5327 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5328 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5329 switch (N->getOpcode()) {
5330 default: assert(0 && "Should not custom lower this!");
5331 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5332 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5336 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5338 default: return NULL;
5339 case X86ISD::BSF: return "X86ISD::BSF";
5340 case X86ISD::BSR: return "X86ISD::BSR";
5341 case X86ISD::SHLD: return "X86ISD::SHLD";
5342 case X86ISD::SHRD: return "X86ISD::SHRD";
5343 case X86ISD::FAND: return "X86ISD::FAND";
5344 case X86ISD::FOR: return "X86ISD::FOR";
5345 case X86ISD::FXOR: return "X86ISD::FXOR";
5346 case X86ISD::FSRL: return "X86ISD::FSRL";
5347 case X86ISD::FILD: return "X86ISD::FILD";
5348 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5349 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5350 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5351 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5352 case X86ISD::FLD: return "X86ISD::FLD";
5353 case X86ISD::FST: return "X86ISD::FST";
5354 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5355 case X86ISD::FP_GET_RESULT2: return "X86ISD::FP_GET_RESULT2";
5356 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5357 case X86ISD::CALL: return "X86ISD::CALL";
5358 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5359 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5360 case X86ISD::CMP: return "X86ISD::CMP";
5361 case X86ISD::COMI: return "X86ISD::COMI";
5362 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5363 case X86ISD::SETCC: return "X86ISD::SETCC";
5364 case X86ISD::CMOV: return "X86ISD::CMOV";
5365 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5366 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5367 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5368 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5369 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5370 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5371 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5372 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5373 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5374 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5375 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5376 case X86ISD::FMAX: return "X86ISD::FMAX";
5377 case X86ISD::FMIN: return "X86ISD::FMIN";
5378 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5379 case X86ISD::FRCP: return "X86ISD::FRCP";
5380 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5381 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5382 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5383 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5384 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5388 // isLegalAddressingMode - Return true if the addressing mode represented
5389 // by AM is legal for this target, for a load/store of the specified type.
5390 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5391 const Type *Ty) const {
5392 // X86 supports extremely general addressing modes.
5394 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5395 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5399 // We can only fold this if we don't need an extra load.
5400 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5403 // X86-64 only supports addr of globals in small code model.
5404 if (Subtarget->is64Bit()) {
5405 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5407 // If lower 4G is not available, then we must use rip-relative addressing.
5408 if (AM.BaseOffs || AM.Scale > 1)
5419 // These scales always work.
5424 // These scales are formed with basereg+scalereg. Only accept if there is
5429 default: // Other stuff never works.
5437 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5438 if (!Ty1->isInteger() || !Ty2->isInteger())
5440 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5441 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5442 if (NumBits1 <= NumBits2)
5444 return Subtarget->is64Bit() || NumBits1 < 64;
5447 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5448 MVT::ValueType VT2) const {
5449 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5451 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5452 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5453 if (NumBits1 <= NumBits2)
5455 return Subtarget->is64Bit() || NumBits1 < 64;
5458 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5459 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5460 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5461 /// are assumed to be legal.
5463 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5464 // Only do shuffles on 128-bit vector types for now.
5465 if (MVT::getSizeInBits(VT) == 64) return false;
5466 return (Mask.Val->getNumOperands() <= 4 ||
5467 isIdentityMask(Mask.Val) ||
5468 isIdentityMask(Mask.Val, true) ||
5469 isSplatMask(Mask.Val) ||
5470 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5471 X86::isUNPCKLMask(Mask.Val) ||
5472 X86::isUNPCKHMask(Mask.Val) ||
5473 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5474 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5477 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5479 SelectionDAG &DAG) const {
5480 unsigned NumElts = BVOps.size();
5481 // Only do shuffles on 128-bit vector types for now.
5482 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5483 if (NumElts == 2) return true;
5485 return (isMOVLMask(&BVOps[0], 4) ||
5486 isCommutedMOVL(&BVOps[0], 4, true) ||
5487 isSHUFPMask(&BVOps[0], 4) ||
5488 isCommutedSHUFP(&BVOps[0], 4));
5493 //===----------------------------------------------------------------------===//
5494 // X86 Scheduler Hooks
5495 //===----------------------------------------------------------------------===//
5498 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5499 MachineBasicBlock *BB) {
5500 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5501 switch (MI->getOpcode()) {
5502 default: assert(false && "Unexpected instr type to insert");
5503 case X86::CMOV_FR32:
5504 case X86::CMOV_FR64:
5505 case X86::CMOV_V4F32:
5506 case X86::CMOV_V2F64:
5507 case X86::CMOV_V2I64: {
5508 // To "insert" a SELECT_CC instruction, we actually have to insert the
5509 // diamond control-flow pattern. The incoming instruction knows the
5510 // destination vreg to set, the condition code register to branch on, the
5511 // true/false values to select between, and a branch opcode to use.
5512 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5513 ilist<MachineBasicBlock>::iterator It = BB;
5519 // cmpTY ccX, r1, r2
5521 // fallthrough --> copy0MBB
5522 MachineBasicBlock *thisMBB = BB;
5523 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5524 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5526 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5527 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5528 MachineFunction *F = BB->getParent();
5529 F->getBasicBlockList().insert(It, copy0MBB);
5530 F->getBasicBlockList().insert(It, sinkMBB);
5531 // Update machine-CFG edges by first adding all successors of the current
5532 // block to the new block which will contain the Phi node for the select.
5533 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5534 e = BB->succ_end(); i != e; ++i)
5535 sinkMBB->addSuccessor(*i);
5536 // Next, remove all successors of the current block, and add the true
5537 // and fallthrough blocks as its successors.
5538 while(!BB->succ_empty())
5539 BB->removeSuccessor(BB->succ_begin());
5540 BB->addSuccessor(copy0MBB);
5541 BB->addSuccessor(sinkMBB);
5544 // %FalseValue = ...
5545 // # fallthrough to sinkMBB
5548 // Update machine-CFG edges
5549 BB->addSuccessor(sinkMBB);
5552 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5555 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5556 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5557 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5559 delete MI; // The pseudo instruction is gone now.
5563 case X86::FP32_TO_INT16_IN_MEM:
5564 case X86::FP32_TO_INT32_IN_MEM:
5565 case X86::FP32_TO_INT64_IN_MEM:
5566 case X86::FP64_TO_INT16_IN_MEM:
5567 case X86::FP64_TO_INT32_IN_MEM:
5568 case X86::FP64_TO_INT64_IN_MEM:
5569 case X86::FP80_TO_INT16_IN_MEM:
5570 case X86::FP80_TO_INT32_IN_MEM:
5571 case X86::FP80_TO_INT64_IN_MEM: {
5572 // Change the floating point control register to use "round towards zero"
5573 // mode when truncating to an integer value.
5574 MachineFunction *F = BB->getParent();
5575 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5576 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5578 // Load the old value of the high byte of the control word...
5580 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5581 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5583 // Set the high part to be round to zero...
5584 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5587 // Reload the modified control word now...
5588 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5590 // Restore the memory image of control word to original value
5591 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5594 // Get the X86 opcode to use.
5596 switch (MI->getOpcode()) {
5597 default: assert(0 && "illegal opcode!");
5598 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5599 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5600 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5601 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5602 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5603 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5604 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5605 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5606 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5610 MachineOperand &Op = MI->getOperand(0);
5611 if (Op.isRegister()) {
5612 AM.BaseType = X86AddressMode::RegBase;
5613 AM.Base.Reg = Op.getReg();
5615 AM.BaseType = X86AddressMode::FrameIndexBase;
5616 AM.Base.FrameIndex = Op.getIndex();
5618 Op = MI->getOperand(1);
5619 if (Op.isImmediate())
5620 AM.Scale = Op.getImm();
5621 Op = MI->getOperand(2);
5622 if (Op.isImmediate())
5623 AM.IndexReg = Op.getImm();
5624 Op = MI->getOperand(3);
5625 if (Op.isGlobalAddress()) {
5626 AM.GV = Op.getGlobal();
5628 AM.Disp = Op.getImm();
5630 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5631 .addReg(MI->getOperand(4).getReg());
5633 // Reload the original control word now.
5634 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5636 delete MI; // The pseudo instruction is gone now.
5642 //===----------------------------------------------------------------------===//
5643 // X86 Optimization Hooks
5644 //===----------------------------------------------------------------------===//
5646 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5650 const SelectionDAG &DAG,
5651 unsigned Depth) const {
5652 unsigned Opc = Op.getOpcode();
5653 assert((Opc >= ISD::BUILTIN_OP_END ||
5654 Opc == ISD::INTRINSIC_WO_CHAIN ||
5655 Opc == ISD::INTRINSIC_W_CHAIN ||
5656 Opc == ISD::INTRINSIC_VOID) &&
5657 "Should use MaskedValueIsZero if you don't know whether Op"
5658 " is a target node!");
5660 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5664 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5665 Mask.getBitWidth() - 1);
5670 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5671 /// element of the result of the vector shuffle.
5672 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5673 MVT::ValueType VT = N->getValueType(0);
5674 SDOperand PermMask = N->getOperand(2);
5675 unsigned NumElems = PermMask.getNumOperands();
5676 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5678 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5680 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5681 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5682 SDOperand Idx = PermMask.getOperand(i);
5683 if (Idx.getOpcode() == ISD::UNDEF)
5684 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5685 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5690 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5691 /// node is a GlobalAddress + an offset.
5692 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5693 unsigned Opc = N->getOpcode();
5694 if (Opc == X86ISD::Wrapper) {
5695 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5696 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5699 } else if (Opc == ISD::ADD) {
5700 SDOperand N1 = N->getOperand(0);
5701 SDOperand N2 = N->getOperand(1);
5702 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5703 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5705 Offset += V->getSignExtended();
5708 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5709 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5711 Offset += V->getSignExtended();
5719 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5721 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5722 MachineFrameInfo *MFI) {
5723 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5726 SDOperand Loc = N->getOperand(1);
5727 SDOperand BaseLoc = Base->getOperand(1);
5728 if (Loc.getOpcode() == ISD::FrameIndex) {
5729 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5731 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5732 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5733 int FS = MFI->getObjectSize(FI);
5734 int BFS = MFI->getObjectSize(BFI);
5735 if (FS != BFS || FS != Size) return false;
5736 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5738 GlobalValue *GV1 = NULL;
5739 GlobalValue *GV2 = NULL;
5740 int64_t Offset1 = 0;
5741 int64_t Offset2 = 0;
5742 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5743 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5744 if (isGA1 && isGA2 && GV1 == GV2)
5745 return Offset1 == (Offset2 + Dist*Size);
5751 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5752 const X86Subtarget *Subtarget) {
5755 if (isGAPlusOffset(Base, GV, Offset))
5756 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5757 // DAG combine handles the stack object case.
5762 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5763 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5764 /// if the load addresses are consecutive, non-overlapping, and in the right
5766 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5767 const X86Subtarget *Subtarget) {
5768 MachineFunction &MF = DAG.getMachineFunction();
5769 MachineFrameInfo *MFI = MF.getFrameInfo();
5770 MVT::ValueType VT = N->getValueType(0);
5771 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5772 SDOperand PermMask = N->getOperand(2);
5773 int NumElems = (int)PermMask.getNumOperands();
5774 SDNode *Base = NULL;
5775 for (int i = 0; i < NumElems; ++i) {
5776 SDOperand Idx = PermMask.getOperand(i);
5777 if (Idx.getOpcode() == ISD::UNDEF) {
5778 if (!Base) return SDOperand();
5781 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5782 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5786 else if (!isConsecutiveLoad(Arg.Val, Base,
5787 i, MVT::getSizeInBits(EVT)/8,MFI))
5792 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5793 LoadSDNode *LD = cast<LoadSDNode>(Base);
5795 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5796 LD->getSrcValueOffset(), LD->isVolatile());
5798 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5799 LD->getSrcValueOffset(), LD->isVolatile(),
5800 LD->getAlignment());
5804 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5805 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5806 const X86Subtarget *Subtarget) {
5807 SDOperand Cond = N->getOperand(0);
5809 // If we have SSE[12] support, try to form min/max nodes.
5810 if (Subtarget->hasSSE2() &&
5811 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5812 if (Cond.getOpcode() == ISD::SETCC) {
5813 // Get the LHS/RHS of the select.
5814 SDOperand LHS = N->getOperand(1);
5815 SDOperand RHS = N->getOperand(2);
5816 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5818 unsigned Opcode = 0;
5819 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5822 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5825 if (!UnsafeFPMath) break;
5827 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5829 Opcode = X86ISD::FMIN;
5832 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5835 if (!UnsafeFPMath) break;
5837 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5839 Opcode = X86ISD::FMAX;
5842 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5845 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5848 if (!UnsafeFPMath) break;
5850 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5852 Opcode = X86ISD::FMIN;
5855 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5858 if (!UnsafeFPMath) break;
5860 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5862 Opcode = X86ISD::FMAX;
5868 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5876 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
5877 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
5878 const X86Subtarget *Subtarget) {
5879 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
5880 // the FP state in cases where an emms may be missing.
5881 // A preferable solution to the general problem is to figure out the right
5882 // places to insert EMMS. This qualifies as a quick hack.
5883 if (MVT::isVector(St->getValue().getValueType()) &&
5884 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
5885 isa<LoadSDNode>(St->getValue()) &&
5886 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
5887 St->getChain().hasOneUse() && !St->isVolatile()) {
5889 int TokenFactorIndex = -1;
5890 SmallVector<SDOperand, 8> Ops;
5891 SDNode* ChainVal = St->getChain().Val;
5892 // Must be a store of a load. We currently handle two cases: the load
5893 // is a direct child, and it's under an intervening TokenFactor. It is
5894 // possible to dig deeper under nested TokenFactors.
5895 if (ChainVal == St->getValue().Val)
5896 Ld = cast<LoadSDNode>(St->getChain());
5897 else if (St->getValue().hasOneUse() &&
5898 ChainVal->getOpcode() == ISD::TokenFactor) {
5899 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
5900 if (ChainVal->getOperand(i).Val == St->getValue().Val) {
5901 if (TokenFactorIndex != -1)
5903 TokenFactorIndex = i;
5904 Ld = cast<LoadSDNode>(St->getValue());
5906 Ops.push_back(ChainVal->getOperand(i));
5910 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
5911 if (Subtarget->is64Bit()) {
5912 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
5913 Ld->getBasePtr(), Ld->getSrcValue(),
5914 Ld->getSrcValueOffset(), Ld->isVolatile(),
5915 Ld->getAlignment());
5916 SDOperand NewChain = NewLd.getValue(1);
5917 if (TokenFactorIndex != -1) {
5918 Ops.push_back(NewLd);
5919 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
5922 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
5923 St->getSrcValue(), St->getSrcValueOffset(),
5924 St->isVolatile(), St->getAlignment());
5927 // Otherwise, lower to two 32-bit copies.
5928 SDOperand LoAddr = Ld->getBasePtr();
5929 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
5930 DAG.getConstant(MVT::i32, 4));
5932 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
5933 Ld->getSrcValue(), Ld->getSrcValueOffset(),
5934 Ld->isVolatile(), Ld->getAlignment());
5935 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
5936 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
5938 MinAlign(Ld->getAlignment(), 4));
5940 SDOperand NewChain = LoLd.getValue(1);
5941 if (TokenFactorIndex != -1) {
5942 Ops.push_back(LoLd);
5943 Ops.push_back(HiLd);
5944 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
5948 LoAddr = St->getBasePtr();
5949 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
5950 DAG.getConstant(MVT::i32, 4));
5952 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
5953 St->getSrcValue(), St->getSrcValueOffset(),
5954 St->isVolatile(), St->getAlignment());
5955 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
5956 St->getSrcValue(), St->getSrcValueOffset()+4,
5958 MinAlign(St->getAlignment(), 4));
5959 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
5965 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
5966 /// X86ISD::FXOR nodes.
5967 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
5968 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
5969 // F[X]OR(0.0, x) -> x
5970 // F[X]OR(x, 0.0) -> x
5971 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5972 if (C->getValueAPF().isPosZero())
5973 return N->getOperand(1);
5974 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5975 if (C->getValueAPF().isPosZero())
5976 return N->getOperand(0);
5980 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
5981 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
5982 // FAND(0.0, x) -> 0.0
5983 // FAND(x, 0.0) -> 0.0
5984 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5985 if (C->getValueAPF().isPosZero())
5986 return N->getOperand(0);
5987 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5988 if (C->getValueAPF().isPosZero())
5989 return N->getOperand(1);
5994 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5995 DAGCombinerInfo &DCI) const {
5996 SelectionDAG &DAG = DCI.DAG;
5997 switch (N->getOpcode()) {
5999 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6000 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6002 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6004 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6005 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6011 //===----------------------------------------------------------------------===//
6012 // X86 Inline Assembly Support
6013 //===----------------------------------------------------------------------===//
6015 /// getConstraintType - Given a constraint letter, return the type of
6016 /// constraint it is for this target.
6017 X86TargetLowering::ConstraintType
6018 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6019 if (Constraint.size() == 1) {
6020 switch (Constraint[0]) {
6029 return C_RegisterClass;
6034 return TargetLowering::getConstraintType(Constraint);
6037 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6038 /// with another that has more specific requirements based on the type of the
6039 /// corresponding operand.
6040 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
6041 std::string& s) const {
6042 if (MVT::isFloatingPoint(ConstraintVT)) {
6043 if (Subtarget->hasSSE2())
6045 else if (Subtarget->hasSSE1())
6050 return TargetLowering::lowerXConstraint(ConstraintVT, s);
6053 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6054 /// vector. If it is invalid, don't add anything to Ops.
6055 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6057 std::vector<SDOperand>&Ops,
6058 SelectionDAG &DAG) {
6059 SDOperand Result(0, 0);
6061 switch (Constraint) {
6064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6065 if (C->getValue() <= 31) {
6066 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6072 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6073 if (C->getValue() <= 255) {
6074 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6080 // Literal immediates are always ok.
6081 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6082 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6086 // If we are in non-pic codegen mode, we allow the address of a global (with
6087 // an optional displacement) to be used with 'i'.
6088 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6091 // Match either (GA) or (GA+C)
6093 Offset = GA->getOffset();
6094 } else if (Op.getOpcode() == ISD::ADD) {
6095 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6096 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6098 Offset = GA->getOffset()+C->getValue();
6100 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6101 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6103 Offset = GA->getOffset()+C->getValue();
6110 // If addressing this global requires a load (e.g. in PIC mode), we can't
6112 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6116 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6122 // Otherwise, not valid for this mode.
6128 Ops.push_back(Result);
6131 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6134 std::vector<unsigned> X86TargetLowering::
6135 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6136 MVT::ValueType VT) const {
6137 if (Constraint.size() == 1) {
6138 // FIXME: not handling fp-stack yet!
6139 switch (Constraint[0]) { // GCC X86 Constraint Letters
6140 default: break; // Unknown constraint letter
6141 case 'A': // EAX/EDX
6142 if (VT == MVT::i32 || VT == MVT::i64)
6143 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6145 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6148 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6149 else if (VT == MVT::i16)
6150 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6151 else if (VT == MVT::i8)
6152 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6153 else if (VT == MVT::i64)
6154 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6159 return std::vector<unsigned>();
6162 std::pair<unsigned, const TargetRegisterClass*>
6163 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6164 MVT::ValueType VT) const {
6165 // First, see if this is a constraint that directly corresponds to an LLVM
6167 if (Constraint.size() == 1) {
6168 // GCC Constraint Letters
6169 switch (Constraint[0]) {
6171 case 'r': // GENERAL_REGS
6172 case 'R': // LEGACY_REGS
6173 case 'l': // INDEX_REGS
6174 if (VT == MVT::i64 && Subtarget->is64Bit())
6175 return std::make_pair(0U, X86::GR64RegisterClass);
6177 return std::make_pair(0U, X86::GR32RegisterClass);
6178 else if (VT == MVT::i16)
6179 return std::make_pair(0U, X86::GR16RegisterClass);
6180 else if (VT == MVT::i8)
6181 return std::make_pair(0U, X86::GR8RegisterClass);
6183 case 'y': // MMX_REGS if MMX allowed.
6184 if (!Subtarget->hasMMX()) break;
6185 return std::make_pair(0U, X86::VR64RegisterClass);
6187 case 'Y': // SSE_REGS if SSE2 allowed
6188 if (!Subtarget->hasSSE2()) break;
6190 case 'x': // SSE_REGS if SSE1 allowed
6191 if (!Subtarget->hasSSE1()) break;
6195 // Scalar SSE types.
6198 return std::make_pair(0U, X86::FR32RegisterClass);
6201 return std::make_pair(0U, X86::FR64RegisterClass);
6209 return std::make_pair(0U, X86::VR128RegisterClass);
6215 // Use the default implementation in TargetLowering to convert the register
6216 // constraint into a member of a register class.
6217 std::pair<unsigned, const TargetRegisterClass*> Res;
6218 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6220 // Not found as a standard register?
6221 if (Res.second == 0) {
6222 // GCC calls "st(0)" just plain "st".
6223 if (StringsEqualNoCase("{st}", Constraint)) {
6224 Res.first = X86::ST0;
6225 Res.second = X86::RFP80RegisterClass;
6231 // Otherwise, check to see if this is a register class of the wrong value
6232 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6233 // turn into {ax},{dx}.
6234 if (Res.second->hasType(VT))
6235 return Res; // Correct type already, nothing to do.
6237 // All of the single-register GCC register classes map their values onto
6238 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6239 // really want an 8-bit or 32-bit register, map to the appropriate register
6240 // class and return the appropriate register.
6241 if (Res.second != X86::GR16RegisterClass)
6244 if (VT == MVT::i8) {
6245 unsigned DestReg = 0;
6246 switch (Res.first) {
6248 case X86::AX: DestReg = X86::AL; break;
6249 case X86::DX: DestReg = X86::DL; break;
6250 case X86::CX: DestReg = X86::CL; break;
6251 case X86::BX: DestReg = X86::BL; break;
6254 Res.first = DestReg;
6255 Res.second = Res.second = X86::GR8RegisterClass;
6257 } else if (VT == MVT::i32) {
6258 unsigned DestReg = 0;
6259 switch (Res.first) {
6261 case X86::AX: DestReg = X86::EAX; break;
6262 case X86::DX: DestReg = X86::EDX; break;
6263 case X86::CX: DestReg = X86::ECX; break;
6264 case X86::BX: DestReg = X86::EBX; break;
6265 case X86::SI: DestReg = X86::ESI; break;
6266 case X86::DI: DestReg = X86::EDI; break;
6267 case X86::BP: DestReg = X86::EBP; break;
6268 case X86::SP: DestReg = X86::ESP; break;
6271 Res.first = DestReg;
6272 Res.second = Res.second = X86::GR32RegisterClass;
6274 } else if (VT == MVT::i64) {
6275 unsigned DestReg = 0;
6276 switch (Res.first) {
6278 case X86::AX: DestReg = X86::RAX; break;
6279 case X86::DX: DestReg = X86::RDX; break;
6280 case X86::CX: DestReg = X86::RCX; break;
6281 case X86::BX: DestReg = X86::RBX; break;
6282 case X86::SI: DestReg = X86::RSI; break;
6283 case X86::DI: DestReg = X86::RDI; break;
6284 case X86::BP: DestReg = X86::RBP; break;
6285 case X86::SP: DestReg = X86::RSP; break;
6288 Res.first = DestReg;
6289 Res.second = Res.second = X86::GR64RegisterClass;