1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
50 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51 : TargetLowering(TM) {
52 Subtarget = &TM.getSubtarget<X86Subtarget>();
53 X86ScalarSSEf64 = Subtarget->hasSSE2();
54 X86ScalarSSEf32 = Subtarget->hasSSE1();
55 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 RegInfo = TM.getRegisterInfo();
62 // Set up the TargetLowering object.
64 // X86 is weird, it always uses i8 for shift amounts and setcc results.
65 setShiftAmountType(MVT::i8);
66 setBooleanContents(ZeroOrOneBooleanContent);
67 setSchedulingPreference(SchedulingForRegPressure);
68 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
69 setStackPointerRegisterToSaveRestore(X86StackPtr);
71 if (Subtarget->isTargetDarwin()) {
72 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(false);
74 setUseUnderscoreLongJmp(false);
75 } else if (Subtarget->isTargetMingw()) {
76 // MS runtime is weird: it exports _setjmp, but longjmp!
77 setUseUnderscoreSetJmp(true);
78 setUseUnderscoreLongJmp(false);
80 setUseUnderscoreSetJmp(true);
81 setUseUnderscoreLongJmp(true);
84 // Set up the register classes.
85 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
86 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
87 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
88 if (Subtarget->is64Bit())
89 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 // We don't accept any truncstore of integer registers.
94 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
97 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
98 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
99 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
101 // SETOEQ and SETUNE require checking two conditions.
102 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
109 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
115 if (Subtarget->is64Bit()) {
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
119 if (X86ScalarSSEf64) {
120 // We have an impenetrably clever algorithm for ui64->double only.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
123 // We have faster algorithm for ui32->single only.
125 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
127 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
130 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
133 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
135 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
136 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
137 // SSE has no i16 to fp conversion, only i32
138 if (X86ScalarSSEf32) {
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
140 // f32 and f64 cases are Legal, f80 case is not
141 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
144 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
147 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
148 // are Legal, f80 is custom lowered.
149 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
150 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
152 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
154 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
155 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
157 if (X86ScalarSSEf32) {
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
159 // f32 and f64 cases are Legal, f80 case is not
160 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
163 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
166 // Handle FP_TO_UINT by promoting the destination to a larger signed
168 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
169 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
172 if (Subtarget->is64Bit()) {
173 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
174 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
176 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
177 // Expand FP_TO_UINT into a select.
178 // FIXME: We would like to use a Custom expander here eventually to do
179 // the optimal thing for SSE vs. the default expansion in the legalizer.
180 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
182 // With SSE3 we can use fisttpll to convert to a signed i64.
183 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
186 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
187 if (!X86ScalarSSEf64) {
188 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
189 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
192 // Scalar integer divide and remainder are lowered to use operations that
193 // produce two results, to match the available instructions. This exposes
194 // the two-result form to trivial CSE, which is able to combine x/y and x%y
195 // into a single instruction.
197 // Scalar integer multiply-high is also lowered to use two-result
198 // operations, to match the available instructions. However, plain multiply
199 // (low) operations are left as Legal, as there are single-result
200 // instructions for this in x86. Using the two-result multiply instructions
201 // when both high and low results are needed must be arranged by dagcombine.
202 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
203 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
204 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
205 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
206 setOperationAction(ISD::SREM , MVT::i8 , Expand);
207 setOperationAction(ISD::UREM , MVT::i8 , Expand);
208 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
209 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
210 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
211 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
212 setOperationAction(ISD::SREM , MVT::i16 , Expand);
213 setOperationAction(ISD::UREM , MVT::i16 , Expand);
214 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
215 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
216 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
217 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
218 setOperationAction(ISD::SREM , MVT::i32 , Expand);
219 setOperationAction(ISD::UREM , MVT::i32 , Expand);
220 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
221 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
222 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
223 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
224 setOperationAction(ISD::SREM , MVT::i64 , Expand);
225 setOperationAction(ISD::UREM , MVT::i64 , Expand);
227 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
228 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
229 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
230 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
231 if (Subtarget->is64Bit())
232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
236 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
237 setOperationAction(ISD::FREM , MVT::f32 , Expand);
238 setOperationAction(ISD::FREM , MVT::f64 , Expand);
239 setOperationAction(ISD::FREM , MVT::f80 , Expand);
240 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
242 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
243 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
244 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
245 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
246 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
247 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
248 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
251 if (Subtarget->is64Bit()) {
252 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
253 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
254 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
257 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
258 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
260 // These should be promoted to a larger select which is supported.
261 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
262 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
263 // X86 wants to expand cmov itself.
264 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
265 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
266 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
267 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
268 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
269 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
270 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
271 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
272 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
273 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
274 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
275 if (Subtarget->is64Bit()) {
276 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
277 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
279 // X86 ret instruction may pop stack.
280 setOperationAction(ISD::RET , MVT::Other, Custom);
281 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
284 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
285 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
286 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
287 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
288 if (Subtarget->is64Bit())
289 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
290 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
291 if (Subtarget->is64Bit()) {
292 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
293 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
294 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
295 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
297 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
298 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
299 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
300 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
301 if (Subtarget->is64Bit()) {
302 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
303 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
304 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
307 if (Subtarget->hasSSE1())
308 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
310 if (!Subtarget->hasSSE2())
311 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
313 // Expand certain atomics
314 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
315 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
316 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
317 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
319 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
321 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
324 if (!Subtarget->is64Bit()) {
325 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
328 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
330 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
331 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
334 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
335 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
336 // FIXME - use subtarget debug flags
337 if (!Subtarget->isTargetDarwin() &&
338 !Subtarget->isTargetELF() &&
339 !Subtarget->isTargetCygMing()) {
340 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
341 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
344 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
345 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
346 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
347 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
348 if (Subtarget->is64Bit()) {
349 setExceptionPointerRegister(X86::RAX);
350 setExceptionSelectorRegister(X86::RDX);
352 setExceptionPointerRegister(X86::EAX);
353 setExceptionSelectorRegister(X86::EDX);
355 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
356 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
358 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
360 setOperationAction(ISD::TRAP, MVT::Other, Legal);
362 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
363 setOperationAction(ISD::VASTART , MVT::Other, Custom);
364 setOperationAction(ISD::VAEND , MVT::Other, Expand);
365 if (Subtarget->is64Bit()) {
366 setOperationAction(ISD::VAARG , MVT::Other, Custom);
367 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
369 setOperationAction(ISD::VAARG , MVT::Other, Expand);
370 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
373 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
374 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
375 if (Subtarget->is64Bit())
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
377 if (Subtarget->isTargetCygMing())
378 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
380 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
382 if (X86ScalarSSEf64) {
383 // f32 and f64 use SSE.
384 // Set up the FP register classes.
385 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
386 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
388 // Use ANDPD to simulate FABS.
389 setOperationAction(ISD::FABS , MVT::f64, Custom);
390 setOperationAction(ISD::FABS , MVT::f32, Custom);
392 // Use XORP to simulate FNEG.
393 setOperationAction(ISD::FNEG , MVT::f64, Custom);
394 setOperationAction(ISD::FNEG , MVT::f32, Custom);
396 // Use ANDPD and ORPD to simulate FCOPYSIGN.
397 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
398 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
400 // We don't support sin/cos/fmod
401 setOperationAction(ISD::FSIN , MVT::f64, Expand);
402 setOperationAction(ISD::FCOS , MVT::f64, Expand);
403 setOperationAction(ISD::FSIN , MVT::f32, Expand);
404 setOperationAction(ISD::FCOS , MVT::f32, Expand);
406 // Expand FP immediates into loads from the stack, except for the special
408 addLegalFPImmediate(APFloat(+0.0)); // xorpd
409 addLegalFPImmediate(APFloat(+0.0f)); // xorps
411 // Floating truncations from f80 and extensions to f80 go through memory.
412 // If optimizing, we lie about this though and handle it in
413 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
415 setConvertAction(MVT::f32, MVT::f80, Expand);
416 setConvertAction(MVT::f64, MVT::f80, Expand);
417 setConvertAction(MVT::f80, MVT::f32, Expand);
418 setConvertAction(MVT::f80, MVT::f64, Expand);
420 } else if (X86ScalarSSEf32) {
421 // Use SSE for f32, x87 for f64.
422 // Set up the FP register classes.
423 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
424 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
426 // Use ANDPS to simulate FABS.
427 setOperationAction(ISD::FABS , MVT::f32, Custom);
429 // Use XORP to simulate FNEG.
430 setOperationAction(ISD::FNEG , MVT::f32, Custom);
432 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
434 // Use ANDPS and ORPS to simulate FCOPYSIGN.
435 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
438 // We don't support sin/cos/fmod
439 setOperationAction(ISD::FSIN , MVT::f32, Expand);
440 setOperationAction(ISD::FCOS , MVT::f32, Expand);
442 // Special cases we handle for FP constants.
443 addLegalFPImmediate(APFloat(+0.0f)); // xorps
444 addLegalFPImmediate(APFloat(+0.0)); // FLD0
445 addLegalFPImmediate(APFloat(+1.0)); // FLD1
446 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
447 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
449 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
450 // this though and handle it in InstructionSelectPreprocess so that
451 // dagcombine2 can hack on these.
453 setConvertAction(MVT::f32, MVT::f64, Expand);
454 setConvertAction(MVT::f32, MVT::f80, Expand);
455 setConvertAction(MVT::f80, MVT::f32, Expand);
456 setConvertAction(MVT::f64, MVT::f32, Expand);
457 // And x87->x87 truncations also.
458 setConvertAction(MVT::f80, MVT::f64, Expand);
462 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
463 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
466 // f32 and f64 in x87.
467 // Set up the FP register classes.
468 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
469 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
471 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
472 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
473 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
474 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
476 // Floating truncations go through memory. If optimizing, we lie about
477 // this though and handle it in InstructionSelectPreprocess so that
478 // dagcombine2 can hack on these.
480 setConvertAction(MVT::f80, MVT::f32, Expand);
481 setConvertAction(MVT::f64, MVT::f32, Expand);
482 setConvertAction(MVT::f80, MVT::f64, Expand);
486 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
487 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
489 addLegalFPImmediate(APFloat(+0.0)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
493 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
494 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
495 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
496 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
499 // Long double always uses X87.
500 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
501 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
502 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
505 APFloat TmpFlt(+0.0);
506 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
508 addLegalFPImmediate(TmpFlt); // FLD0
510 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
511 APFloat TmpFlt2(+1.0);
512 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
514 addLegalFPImmediate(TmpFlt2); // FLD1
515 TmpFlt2.changeSign();
516 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
520 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
521 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
524 // Always use a library call for pow.
525 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
526 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
527 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
529 setOperationAction(ISD::FLOG, MVT::f80, Expand);
530 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
531 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
532 setOperationAction(ISD::FEXP, MVT::f80, Expand);
533 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
535 // First set operation action for all vector types to either promote
536 // (for widening) or expand (for scalarization). Then we will selectively
537 // turn on ones that can be effectively codegen'd.
538 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
539 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
540 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
555 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
585 if (!DisableMMX && Subtarget->hasMMX()) {
586 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
587 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
588 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
589 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
590 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
592 // FIXME: add MMX packed arithmetics
594 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
595 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
596 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
597 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
599 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
600 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
601 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
602 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
604 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
605 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
607 setOperationAction(ISD::AND, MVT::v8i8, Promote);
608 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
609 setOperationAction(ISD::AND, MVT::v4i16, Promote);
610 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
611 setOperationAction(ISD::AND, MVT::v2i32, Promote);
612 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
613 setOperationAction(ISD::AND, MVT::v1i64, Legal);
615 setOperationAction(ISD::OR, MVT::v8i8, Promote);
616 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
617 setOperationAction(ISD::OR, MVT::v4i16, Promote);
618 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
619 setOperationAction(ISD::OR, MVT::v2i32, Promote);
620 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
621 setOperationAction(ISD::OR, MVT::v1i64, Legal);
623 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
624 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
625 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
626 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
627 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
628 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
629 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
631 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
632 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
633 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
634 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
635 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
636 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
637 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
638 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
639 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
641 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
642 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
643 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
644 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
645 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
647 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
649 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
652 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
653 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
654 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
655 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
659 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
660 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
661 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
662 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
663 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
664 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
667 if (Subtarget->hasSSE1()) {
668 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
670 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
671 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
672 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
673 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
674 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
675 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
676 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
677 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
679 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
680 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
684 if (Subtarget->hasSSE2()) {
685 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
686 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
687 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
688 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
689 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
691 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
692 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
693 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
694 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
695 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
696 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
697 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
698 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
699 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
700 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
701 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
702 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
703 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
704 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
705 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
706 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
708 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
709 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
710 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
711 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
713 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
714 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
715 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
716 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
717 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
719 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
720 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
721 MVT VT = (MVT::SimpleValueType)i;
722 // Do not attempt to custom lower non-power-of-2 vectors
723 if (!isPowerOf2_32(VT.getVectorNumElements()))
725 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
726 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
729 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
730 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
731 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
732 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
733 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
734 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
735 if (Subtarget->is64Bit()) {
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
740 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
741 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
742 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
743 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
744 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
745 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
746 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
747 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
748 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
749 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
750 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
751 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
754 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
756 // Custom lower v2i64 and v2f64 selects.
757 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
758 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
759 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
760 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
764 if (Subtarget->hasSSE41()) {
765 // FIXME: Do we need to handle scalar-to-vector here?
766 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
768 // i8 and i16 vectors are custom , because the source register and source
769 // source memory operand types are not the same width. f32 vectors are
770 // custom since the immediate controlling the insert encodes additional
772 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
774 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
775 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
778 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
779 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
782 if (Subtarget->is64Bit()) {
783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
784 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
788 if (Subtarget->hasSSE42()) {
789 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
792 // We want to custom lower some of our intrinsics.
793 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
795 // Add/Sub/Mul with overflow operations are custom lowered.
796 setOperationAction(ISD::SADDO, MVT::i32, Custom);
797 setOperationAction(ISD::SADDO, MVT::i64, Custom);
798 setOperationAction(ISD::UADDO, MVT::i32, Custom);
799 setOperationAction(ISD::UADDO, MVT::i64, Custom);
800 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
801 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
802 setOperationAction(ISD::USUBO, MVT::i32, Custom);
803 setOperationAction(ISD::USUBO, MVT::i64, Custom);
804 setOperationAction(ISD::SMULO, MVT::i32, Custom);
805 setOperationAction(ISD::SMULO, MVT::i64, Custom);
806 setOperationAction(ISD::UMULO, MVT::i32, Custom);
807 setOperationAction(ISD::UMULO, MVT::i64, Custom);
809 // We have target-specific dag combine patterns for the following nodes:
810 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
811 setTargetDAGCombine(ISD::BUILD_VECTOR);
812 setTargetDAGCombine(ISD::SELECT);
813 setTargetDAGCombine(ISD::STORE);
815 computeRegisterProperties();
817 // FIXME: These should be based on subtarget info. Plus, the values should
818 // be smaller when we are in optimizing for size mode.
819 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
820 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
821 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
822 allowUnalignedMemoryAccesses = true; // x86 supports it!
823 setPrefLoopAlignment(16);
827 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
832 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
833 /// the desired ByVal argument alignment.
834 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
837 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
838 if (VTy->getBitWidth() == 128)
840 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
841 unsigned EltAlign = 0;
842 getMaxByValAlign(ATy->getElementType(), EltAlign);
843 if (EltAlign > MaxAlign)
845 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
846 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
847 unsigned EltAlign = 0;
848 getMaxByValAlign(STy->getElementType(i), EltAlign);
849 if (EltAlign > MaxAlign)
858 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
859 /// function arguments in the caller parameter area. For X86, aggregates
860 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
861 /// are at 4-byte boundaries.
862 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
863 if (Subtarget->is64Bit()) {
864 // Max of 8 and alignment of type.
865 unsigned TyAlign = TD->getABITypeAlignment(Ty);
872 if (Subtarget->hasSSE1())
873 getMaxByValAlign(Ty, Align);
877 /// getOptimalMemOpType - Returns the target specific optimal type for load
878 /// and store operations as a result of memset, memcpy, and memmove
879 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
882 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
883 bool isSrcConst, bool isSrcStr) const {
884 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
885 // linux. This is because the stack realignment code can't handle certain
886 // cases like PR2962. This should be removed when PR2962 is fixed.
887 if (Subtarget->getStackAlignment() >= 16) {
888 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
890 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
893 if (Subtarget->is64Bit() && Size >= 8)
899 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
901 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
902 SelectionDAG &DAG) const {
903 if (usesGlobalOffsetTable())
904 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
905 if (!Subtarget->isPICStyleRIPRel())
906 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
910 //===----------------------------------------------------------------------===//
911 // Return Value Calling Convention Implementation
912 //===----------------------------------------------------------------------===//
914 #include "X86GenCallingConv.inc"
916 /// LowerRET - Lower an ISD::RET node.
917 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
918 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
920 SmallVector<CCValAssign, 16> RVLocs;
921 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
922 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
923 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
924 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
926 // If this is the first return lowered for this function, add the regs to the
927 // liveout set for the function.
928 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
929 for (unsigned i = 0; i != RVLocs.size(); ++i)
930 if (RVLocs[i].isRegLoc())
931 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
933 SDValue Chain = Op.getOperand(0);
935 // Handle tail call return.
936 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
937 if (Chain.getOpcode() == X86ISD::TAILCALL) {
938 SDValue TailCall = Chain;
939 SDValue TargetAddress = TailCall.getOperand(1);
940 SDValue StackAdjustment = TailCall.getOperand(2);
941 assert(((TargetAddress.getOpcode() == ISD::Register &&
942 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
943 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
944 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
945 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
946 "Expecting an global address, external symbol, or register");
947 assert(StackAdjustment.getOpcode() == ISD::Constant &&
948 "Expecting a const value");
950 SmallVector<SDValue,8> Operands;
951 Operands.push_back(Chain.getOperand(0));
952 Operands.push_back(TargetAddress);
953 Operands.push_back(StackAdjustment);
954 // Copy registers used by the call. Last operand is a flag so it is not
956 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
957 Operands.push_back(Chain.getOperand(i));
959 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
966 SmallVector<SDValue, 6> RetOps;
967 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
968 // Operand #1 = Bytes To Pop
969 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
971 // Copy the result values into the output registers.
972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
973 CCValAssign &VA = RVLocs[i];
974 assert(VA.isRegLoc() && "Can only return in registers!");
975 SDValue ValToCopy = Op.getOperand(i*2+1);
977 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
978 // the RET instruction and handled by the FP Stackifier.
979 if (RVLocs[i].getLocReg() == X86::ST0 ||
980 RVLocs[i].getLocReg() == X86::ST1) {
981 // If this is a copy from an xmm register to ST(0), use an FPExtend to
982 // change the value to the FP stack register class.
983 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
984 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
985 RetOps.push_back(ValToCopy);
986 // Don't emit a copytoreg.
990 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
991 Flag = Chain.getValue(1);
994 // The x86-64 ABI for returning structs by value requires that we copy
995 // the sret argument into %rax for the return. We saved the argument into
996 // a virtual register in the entry block, so now we copy the value out
998 if (Subtarget->is64Bit() &&
999 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1000 MachineFunction &MF = DAG.getMachineFunction();
1001 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1002 unsigned Reg = FuncInfo->getSRetReturnReg();
1004 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1005 FuncInfo->setSRetReturnReg(Reg);
1007 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
1009 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
1010 Flag = Chain.getValue(1);
1013 RetOps[0] = Chain; // Update chain.
1015 // Add the flag if we have it.
1017 RetOps.push_back(Flag);
1019 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
1023 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1024 /// appropriate copies out of appropriate physical registers. This assumes that
1025 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1026 /// being lowered. The returns a SDNode with the same number of values as the
1028 SDNode *X86TargetLowering::
1029 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1030 unsigned CallingConv, SelectionDAG &DAG) {
1032 // Assign locations to each value returned by this call.
1033 SmallVector<CCValAssign, 16> RVLocs;
1034 bool isVarArg = TheCall->isVarArg();
1035 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1036 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1038 SmallVector<SDValue, 8> ResultVals;
1040 // Copy all of the result registers out of their specified physreg.
1041 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1042 MVT CopyVT = RVLocs[i].getValVT();
1044 // If this is a call to a function that returns an fp value on the floating
1045 // point stack, but where we prefer to use the value in xmm registers, copy
1046 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1047 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1048 RVLocs[i].getLocReg() == X86::ST1) &&
1049 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1053 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1054 CopyVT, InFlag).getValue(1);
1055 SDValue Val = Chain.getValue(0);
1056 InFlag = Chain.getValue(2);
1058 if (CopyVT != RVLocs[i].getValVT()) {
1059 // Round the F80 the right size, which also moves to the appropriate xmm
1061 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1062 // This truncation won't change the value.
1063 DAG.getIntPtrConstant(1));
1066 ResultVals.push_back(Val);
1069 // Merge everything together with a MERGE_VALUES node.
1070 ResultVals.push_back(Chain);
1071 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(), &ResultVals[0],
1072 ResultVals.size()).getNode();
1076 //===----------------------------------------------------------------------===//
1077 // C & StdCall & Fast Calling Convention implementation
1078 //===----------------------------------------------------------------------===//
1079 // StdCall calling convention seems to be standard for many Windows' API
1080 // routines and around. It differs from C calling convention just a little:
1081 // callee should clean up the stack, not caller. Symbols should be also
1082 // decorated in some fancy way :) It doesn't support any vector arguments.
1083 // For info on fast calling convention see Fast Calling Convention (tail call)
1084 // implementation LowerX86_32FastCCCallTo.
1086 /// AddLiveIn - This helper function adds the specified physical register to the
1087 /// MachineFunction as a live in value. It also creates a corresponding virtual
1088 /// register for it.
1089 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1090 const TargetRegisterClass *RC) {
1091 assert(RC->contains(PReg) && "Not the correct regclass!");
1092 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1093 MF.getRegInfo().addLiveIn(PReg, VReg);
1097 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1099 static bool CallIsStructReturn(CallSDNode *TheCall) {
1100 unsigned NumOps = TheCall->getNumArgs();
1104 return TheCall->getArgFlags(0).isSRet();
1107 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1108 /// return semantics.
1109 static bool ArgsAreStructReturn(SDValue Op) {
1110 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1114 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1117 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1118 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1120 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1124 switch (CallingConv) {
1127 case CallingConv::X86_StdCall:
1128 return !Subtarget->is64Bit();
1129 case CallingConv::X86_FastCall:
1130 return !Subtarget->is64Bit();
1131 case CallingConv::Fast:
1132 return PerformTailCallOpt;
1136 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1137 /// given CallingConvention value.
1138 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1139 if (Subtarget->is64Bit()) {
1140 if (Subtarget->isTargetWin64())
1141 return CC_X86_Win64_C;
1142 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1143 return CC_X86_64_TailCall;
1148 if (CC == CallingConv::X86_FastCall)
1149 return CC_X86_32_FastCall;
1150 else if (CC == CallingConv::Fast)
1151 return CC_X86_32_FastCC;
1156 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1157 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1159 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1160 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1161 if (CC == CallingConv::X86_FastCall)
1163 else if (CC == CallingConv::X86_StdCall)
1169 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1170 /// in a register before calling.
1171 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1172 return !IsTailCall && !Is64Bit &&
1173 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1174 Subtarget->isPICStyleGOT();
1177 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1178 /// address to be loaded in a register.
1180 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1181 return !Is64Bit && IsTailCall &&
1182 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1183 Subtarget->isPICStyleGOT();
1186 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1187 /// by "Src" to address "Dst" with size and alignment information specified by
1188 /// the specific parameter attribute. The copy will be passed as a byval
1189 /// function parameter.
1191 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1192 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1193 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1194 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1195 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1198 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1199 const CCValAssign &VA,
1200 MachineFrameInfo *MFI,
1202 SDValue Root, unsigned i) {
1203 // Create the nodes corresponding to a load from this parameter slot.
1204 ISD::ArgFlagsTy Flags =
1205 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1206 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1207 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1209 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1210 // changed with more analysis.
1211 // In case of tail call optimization mark all arguments mutable. Since they
1212 // could be overwritten by lowering of arguments in case of a tail call.
1213 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1214 VA.getLocMemOffset(), isImmutable);
1215 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1216 if (Flags.isByVal())
1218 return DAG.getLoad(VA.getValVT(), Root, FIN,
1219 PseudoSourceValue::getFixedStack(FI), 0);
1223 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1224 MachineFunction &MF = DAG.getMachineFunction();
1225 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1227 const Function* Fn = MF.getFunction();
1228 if (Fn->hasExternalLinkage() &&
1229 Subtarget->isTargetCygMing() &&
1230 Fn->getName() == "main")
1231 FuncInfo->setForceFramePointer(true);
1233 // Decorate the function name.
1234 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1236 MachineFrameInfo *MFI = MF.getFrameInfo();
1237 SDValue Root = Op.getOperand(0);
1238 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1239 unsigned CC = MF.getFunction()->getCallingConv();
1240 bool Is64Bit = Subtarget->is64Bit();
1241 bool IsWin64 = Subtarget->isTargetWin64();
1243 assert(!(isVarArg && CC == CallingConv::Fast) &&
1244 "Var args not supported with calling convention fastcc");
1246 // Assign locations to all of the incoming arguments.
1247 SmallVector<CCValAssign, 16> ArgLocs;
1248 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1249 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1251 SmallVector<SDValue, 8> ArgValues;
1252 unsigned LastVal = ~0U;
1253 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1254 CCValAssign &VA = ArgLocs[i];
1255 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1257 assert(VA.getValNo() != LastVal &&
1258 "Don't support value assigned to multiple locs yet");
1259 LastVal = VA.getValNo();
1261 if (VA.isRegLoc()) {
1262 MVT RegVT = VA.getLocVT();
1263 TargetRegisterClass *RC = NULL;
1264 if (RegVT == MVT::i32)
1265 RC = X86::GR32RegisterClass;
1266 else if (Is64Bit && RegVT == MVT::i64)
1267 RC = X86::GR64RegisterClass;
1268 else if (RegVT == MVT::f32)
1269 RC = X86::FR32RegisterClass;
1270 else if (RegVT == MVT::f64)
1271 RC = X86::FR64RegisterClass;
1272 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1273 RC = X86::VR128RegisterClass;
1274 else if (RegVT.isVector()) {
1275 assert(RegVT.getSizeInBits() == 64);
1277 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1279 // Darwin calling convention passes MMX values in either GPRs or
1280 // XMMs in x86-64. Other targets pass them in memory.
1281 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1282 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1285 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1290 assert(0 && "Unknown argument type!");
1293 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1294 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1296 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1297 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1299 if (VA.getLocInfo() == CCValAssign::SExt)
1300 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1301 DAG.getValueType(VA.getValVT()));
1302 else if (VA.getLocInfo() == CCValAssign::ZExt)
1303 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1304 DAG.getValueType(VA.getValVT()));
1306 if (VA.getLocInfo() != CCValAssign::Full)
1307 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1309 // Handle MMX values passed in GPRs.
1310 if (Is64Bit && RegVT != VA.getLocVT()) {
1311 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1312 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1313 else if (RC == X86::VR128RegisterClass) {
1314 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1315 DAG.getConstant(0, MVT::i64));
1316 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1320 ArgValues.push_back(ArgValue);
1322 assert(VA.isMemLoc());
1323 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1327 // The x86-64 ABI for returning structs by value requires that we copy
1328 // the sret argument into %rax for the return. Save the argument into
1329 // a virtual register so that we can access it from the return points.
1330 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1331 MachineFunction &MF = DAG.getMachineFunction();
1332 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1333 unsigned Reg = FuncInfo->getSRetReturnReg();
1335 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1336 FuncInfo->setSRetReturnReg(Reg);
1338 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1339 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1342 unsigned StackSize = CCInfo.getNextStackOffset();
1343 // align stack specially for tail calls
1344 if (PerformTailCallOpt && CC == CallingConv::Fast)
1345 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1347 // If the function takes variable number of arguments, make a frame index for
1348 // the start of the first vararg value... for expansion of llvm.va_start.
1350 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1351 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1354 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1356 // FIXME: We should really autogenerate these arrays
1357 static const unsigned GPR64ArgRegsWin64[] = {
1358 X86::RCX, X86::RDX, X86::R8, X86::R9
1360 static const unsigned XMMArgRegsWin64[] = {
1361 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1363 static const unsigned GPR64ArgRegs64Bit[] = {
1364 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1366 static const unsigned XMMArgRegs64Bit[] = {
1367 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1368 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1370 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1373 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1374 GPR64ArgRegs = GPR64ArgRegsWin64;
1375 XMMArgRegs = XMMArgRegsWin64;
1377 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1378 GPR64ArgRegs = GPR64ArgRegs64Bit;
1379 XMMArgRegs = XMMArgRegs64Bit;
1381 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1383 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1386 // For X86-64, if there are vararg parameters that are passed via
1387 // registers, then we must store them to their spots on the stack so they
1388 // may be loaded by deferencing the result of va_next.
1389 VarArgsGPOffset = NumIntRegs * 8;
1390 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1391 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1392 TotalNumXMMRegs * 16, 16);
1394 // Store the integer parameter registers.
1395 SmallVector<SDValue, 8> MemOps;
1396 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1397 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1398 DAG.getIntPtrConstant(VarArgsGPOffset));
1399 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1400 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1401 X86::GR64RegisterClass);
1402 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1404 DAG.getStore(Val.getValue(1), Val, FIN,
1405 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1406 MemOps.push_back(Store);
1407 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1408 DAG.getIntPtrConstant(8));
1411 // Now store the XMM (fp + vector) parameter registers.
1412 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1413 DAG.getIntPtrConstant(VarArgsFPOffset));
1414 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1415 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1416 X86::VR128RegisterClass);
1417 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1419 DAG.getStore(Val.getValue(1), Val, FIN,
1420 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1421 MemOps.push_back(Store);
1422 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1423 DAG.getIntPtrConstant(16));
1425 if (!MemOps.empty())
1426 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1427 &MemOps[0], MemOps.size());
1431 ArgValues.push_back(Root);
1433 // Some CCs need callee pop.
1434 if (IsCalleePop(isVarArg, CC)) {
1435 BytesToPopOnReturn = StackSize; // Callee pops everything.
1436 BytesCallerReserves = 0;
1438 BytesToPopOnReturn = 0; // Callee pops nothing.
1439 // If this is an sret function, the return should pop the hidden pointer.
1440 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1441 BytesToPopOnReturn = 4;
1442 BytesCallerReserves = StackSize;
1446 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1447 if (CC == CallingConv::X86_FastCall)
1448 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1451 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1453 // Return the new list of results.
1454 return DAG.getNode(ISD::MERGE_VALUES, Op.getNode()->getVTList(),
1455 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1459 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1460 const SDValue &StackPtr,
1461 const CCValAssign &VA,
1463 SDValue Arg, ISD::ArgFlagsTy Flags) {
1464 unsigned LocMemOffset = VA.getLocMemOffset();
1465 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1466 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1467 if (Flags.isByVal()) {
1468 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1470 return DAG.getStore(Chain, Arg, PtrOff,
1471 PseudoSourceValue::getStack(), LocMemOffset);
1474 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1475 /// optimization is performed and it is required.
1477 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1478 SDValue &OutRetAddr,
1483 if (!IsTailCall || FPDiff==0) return Chain;
1485 // Adjust the Return address stack slot.
1486 MVT VT = getPointerTy();
1487 OutRetAddr = getReturnAddressFrameIndex(DAG);
1489 // Load the "old" Return address.
1490 OutRetAddr = DAG.getLoad(VT, Chain, OutRetAddr, NULL, 0);
1491 return SDValue(OutRetAddr.getNode(), 1);
1494 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1495 /// optimization is performed and it is required (FPDiff!=0).
1497 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1498 SDValue Chain, SDValue RetAddrFrIdx,
1499 bool Is64Bit, int FPDiff) {
1500 // Store the return address to the appropriate stack slot.
1501 if (!FPDiff) return Chain;
1502 // Calculate the new stack slot for the return address.
1503 int SlotSize = Is64Bit ? 8 : 4;
1504 int NewReturnAddrFI =
1505 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1506 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1507 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1508 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1509 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1513 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1514 MachineFunction &MF = DAG.getMachineFunction();
1515 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1516 SDValue Chain = TheCall->getChain();
1517 unsigned CC = TheCall->getCallingConv();
1518 bool isVarArg = TheCall->isVarArg();
1519 bool IsTailCall = TheCall->isTailCall() &&
1520 CC == CallingConv::Fast && PerformTailCallOpt;
1521 SDValue Callee = TheCall->getCallee();
1522 bool Is64Bit = Subtarget->is64Bit();
1523 bool IsStructRet = CallIsStructReturn(TheCall);
1525 assert(!(isVarArg && CC == CallingConv::Fast) &&
1526 "Var args not supported with calling convention fastcc");
1528 // Analyze operands of the call, assigning locations to each operand.
1529 SmallVector<CCValAssign, 16> ArgLocs;
1530 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1531 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1533 // Get a count of how many bytes are to be pushed on the stack.
1534 unsigned NumBytes = CCInfo.getNextStackOffset();
1535 if (PerformTailCallOpt && CC == CallingConv::Fast)
1536 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1540 // Lower arguments at fp - stackoffset + fpdiff.
1541 unsigned NumBytesCallerPushed =
1542 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1543 FPDiff = NumBytesCallerPushed - NumBytes;
1545 // Set the delta of movement of the returnaddr stackslot.
1546 // But only set if delta is greater than previous delta.
1547 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1548 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1551 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1553 SDValue RetAddrFrIdx;
1554 // Load return adress for tail calls.
1555 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1558 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1559 SmallVector<SDValue, 8> MemOpChains;
1562 // Walk the register/memloc assignments, inserting copies/loads. In the case
1563 // of tail call optimization arguments are handle later.
1564 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1565 CCValAssign &VA = ArgLocs[i];
1566 SDValue Arg = TheCall->getArg(i);
1567 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1568 bool isByVal = Flags.isByVal();
1570 // Promote the value if needed.
1571 switch (VA.getLocInfo()) {
1572 default: assert(0 && "Unknown loc info!");
1573 case CCValAssign::Full: break;
1574 case CCValAssign::SExt:
1575 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1577 case CCValAssign::ZExt:
1578 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1580 case CCValAssign::AExt:
1581 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1585 if (VA.isRegLoc()) {
1587 MVT RegVT = VA.getLocVT();
1588 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1589 switch (VA.getLocReg()) {
1592 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1594 // Special case: passing MMX values in GPR registers.
1595 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1598 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1599 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1600 // Special case: passing MMX values in XMM registers.
1601 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1602 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1603 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1604 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1605 getMOVLMask(2, DAG));
1610 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1612 if (!IsTailCall || (IsTailCall && isByVal)) {
1613 assert(VA.isMemLoc());
1614 if (StackPtr.getNode() == 0)
1615 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1617 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1618 Chain, Arg, Flags));
1623 if (!MemOpChains.empty())
1624 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1625 &MemOpChains[0], MemOpChains.size());
1627 // Build a sequence of copy-to-reg nodes chained together with token chain
1628 // and flag operands which copy the outgoing args into registers.
1630 // Tail call byval lowering might overwrite argument registers so in case of
1631 // tail call optimization the copies to registers are lowered later.
1633 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1634 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1636 InFlag = Chain.getValue(1);
1639 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1641 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1642 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1643 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1645 InFlag = Chain.getValue(1);
1647 // If we are tail calling and generating PIC/GOT style code load the address
1648 // of the callee into ecx. The value in ecx is used as target of the tail
1649 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1650 // calls on PIC/GOT architectures. Normally we would just put the address of
1651 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1652 // restored (since ebx is callee saved) before jumping to the target@PLT.
1653 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1654 // Note: The actual moving to ecx is done further down.
1655 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1656 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1657 !G->getGlobal()->hasProtectedVisibility())
1658 Callee = LowerGlobalAddress(Callee, DAG);
1659 else if (isa<ExternalSymbolSDNode>(Callee))
1660 Callee = LowerExternalSymbol(Callee,DAG);
1663 if (Is64Bit && isVarArg) {
1664 // From AMD64 ABI document:
1665 // For calls that may call functions that use varargs or stdargs
1666 // (prototype-less calls or calls to functions containing ellipsis (...) in
1667 // the declaration) %al is used as hidden argument to specify the number
1668 // of SSE registers used. The contents of %al do not need to match exactly
1669 // the number of registers, but must be an ubound on the number of SSE
1670 // registers used and is in the range 0 - 8 inclusive.
1672 // FIXME: Verify this on Win64
1673 // Count the number of XMM registers allocated.
1674 static const unsigned XMMArgRegs[] = {
1675 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1676 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1678 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1680 Chain = DAG.getCopyToReg(Chain, X86::AL,
1681 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1682 InFlag = Chain.getValue(1);
1686 // For tail calls lower the arguments to the 'real' stack slot.
1688 SmallVector<SDValue, 8> MemOpChains2;
1691 // Do not flag preceeding copytoreg stuff together with the following stuff.
1693 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1694 CCValAssign &VA = ArgLocs[i];
1695 if (!VA.isRegLoc()) {
1696 assert(VA.isMemLoc());
1697 SDValue Arg = TheCall->getArg(i);
1698 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1699 // Create frame index.
1700 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1701 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1702 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1703 FIN = DAG.getFrameIndex(FI, getPointerTy());
1705 if (Flags.isByVal()) {
1706 // Copy relative to framepointer.
1707 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1708 if (StackPtr.getNode() == 0)
1709 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1710 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1712 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1715 // Store relative to framepointer.
1716 MemOpChains2.push_back(
1717 DAG.getStore(Chain, Arg, FIN,
1718 PseudoSourceValue::getFixedStack(FI), 0));
1723 if (!MemOpChains2.empty())
1724 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1725 &MemOpChains2[0], MemOpChains2.size());
1727 // Copy arguments to their registers.
1728 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1729 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1731 InFlag = Chain.getValue(1);
1735 // Store the return address to the appropriate stack slot.
1736 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1740 // If the callee is a GlobalAddress node (quite common, every direct call is)
1741 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1742 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1743 // We should use extra load for direct calls to dllimported functions in
1745 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1746 getTargetMachine(), true))
1747 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1749 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1750 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1751 } else if (IsTailCall) {
1752 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1754 Chain = DAG.getCopyToReg(Chain,
1755 DAG.getRegister(Opc, getPointerTy()),
1757 Callee = DAG.getRegister(Opc, getPointerTy());
1758 // Add register as live out.
1759 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1762 // Returns a chain & a flag for retval copy to use.
1763 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1764 SmallVector<SDValue, 8> Ops;
1767 Ops.push_back(Chain);
1768 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1769 Ops.push_back(DAG.getIntPtrConstant(0, true));
1770 if (InFlag.getNode())
1771 Ops.push_back(InFlag);
1772 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1773 InFlag = Chain.getValue(1);
1775 // Returns a chain & a flag for retval copy to use.
1776 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1780 Ops.push_back(Chain);
1781 Ops.push_back(Callee);
1784 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1786 // Add argument registers to the end of the list so that they are known live
1788 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1789 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1790 RegsToPass[i].second.getValueType()));
1792 // Add an implicit use GOT pointer in EBX.
1793 if (!IsTailCall && !Is64Bit &&
1794 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1795 Subtarget->isPICStyleGOT())
1796 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1798 // Add an implicit use of AL for x86 vararg functions.
1799 if (Is64Bit && isVarArg)
1800 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1802 if (InFlag.getNode())
1803 Ops.push_back(InFlag);
1806 assert(InFlag.getNode() &&
1807 "Flag must be set. Depend on flag being set in LowerRET");
1808 Chain = DAG.getNode(X86ISD::TAILCALL,
1809 TheCall->getVTList(), &Ops[0], Ops.size());
1811 return SDValue(Chain.getNode(), Op.getResNo());
1814 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1815 InFlag = Chain.getValue(1);
1817 // Create the CALLSEQ_END node.
1818 unsigned NumBytesForCalleeToPush;
1819 if (IsCalleePop(isVarArg, CC))
1820 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1821 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1822 // If this is is a call to a struct-return function, the callee
1823 // pops the hidden struct pointer, so we have to push it back.
1824 // This is common for Darwin/X86, Linux & Mingw32 targets.
1825 NumBytesForCalleeToPush = 4;
1827 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1829 // Returns a flag for retval copy to use.
1830 Chain = DAG.getCALLSEQ_END(Chain,
1831 DAG.getIntPtrConstant(NumBytes, true),
1832 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1835 InFlag = Chain.getValue(1);
1837 // Handle result values, copying them out of physregs into vregs that we
1839 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1844 //===----------------------------------------------------------------------===//
1845 // Fast Calling Convention (tail call) implementation
1846 //===----------------------------------------------------------------------===//
1848 // Like std call, callee cleans arguments, convention except that ECX is
1849 // reserved for storing the tail called function address. Only 2 registers are
1850 // free for argument passing (inreg). Tail call optimization is performed
1852 // * tailcallopt is enabled
1853 // * caller/callee are fastcc
1854 // On X86_64 architecture with GOT-style position independent code only local
1855 // (within module) calls are supported at the moment.
1856 // To keep the stack aligned according to platform abi the function
1857 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1858 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1859 // If a tail called function callee has more arguments than the caller the
1860 // caller needs to make sure that there is room to move the RETADDR to. This is
1861 // achieved by reserving an area the size of the argument delta right after the
1862 // original REtADDR, but before the saved framepointer or the spilled registers
1863 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1875 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1876 /// for a 16 byte align requirement.
1877 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1878 SelectionDAG& DAG) {
1879 MachineFunction &MF = DAG.getMachineFunction();
1880 const TargetMachine &TM = MF.getTarget();
1881 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1882 unsigned StackAlignment = TFI.getStackAlignment();
1883 uint64_t AlignMask = StackAlignment - 1;
1884 int64_t Offset = StackSize;
1885 uint64_t SlotSize = TD->getPointerSize();
1886 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1887 // Number smaller than 12 so just add the difference.
1888 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1890 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1891 Offset = ((~AlignMask) & Offset) + StackAlignment +
1892 (StackAlignment-SlotSize);
1897 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1898 /// following the call is a return. A function is eligible if caller/callee
1899 /// calling conventions match, currently only fastcc supports tail calls, and
1900 /// the function CALL is immediatly followed by a RET.
1901 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1903 SelectionDAG& DAG) const {
1904 if (!PerformTailCallOpt)
1907 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1908 MachineFunction &MF = DAG.getMachineFunction();
1909 unsigned CallerCC = MF.getFunction()->getCallingConv();
1910 unsigned CalleeCC= TheCall->getCallingConv();
1911 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1912 SDValue Callee = TheCall->getCallee();
1913 // On x86/32Bit PIC/GOT tail calls are supported.
1914 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1915 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1918 // Can only do local tail calls (in same module, hidden or protected) on
1919 // x86_64 PIC/GOT at the moment.
1920 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1921 return G->getGlobal()->hasHiddenVisibility()
1922 || G->getGlobal()->hasProtectedVisibility();
1930 X86TargetLowering::createFastISel(MachineFunction &mf,
1931 MachineModuleInfo *mmo,
1933 DenseMap<const Value *, unsigned> &vm,
1934 DenseMap<const BasicBlock *,
1935 MachineBasicBlock *> &bm,
1936 DenseMap<const AllocaInst *, int> &am
1938 , SmallSet<Instruction*, 8> &cil
1941 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1949 //===----------------------------------------------------------------------===//
1950 // Other Lowering Hooks
1951 //===----------------------------------------------------------------------===//
1954 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1955 MachineFunction &MF = DAG.getMachineFunction();
1956 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1957 int ReturnAddrIndex = FuncInfo->getRAIndex();
1959 if (ReturnAddrIndex == 0) {
1960 // Set up a frame object for the return address.
1961 uint64_t SlotSize = TD->getPointerSize();
1962 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1963 FuncInfo->setRAIndex(ReturnAddrIndex);
1966 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1970 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1971 /// specific condition code, returning the condition code and the LHS/RHS of the
1972 /// comparison to make.
1973 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1974 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
1976 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1977 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1978 // X > -1 -> X == 0, jump !sign.
1979 RHS = DAG.getConstant(0, RHS.getValueType());
1980 return X86::COND_NS;
1981 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1982 // X < 0 -> X == 0, jump on sign.
1984 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1986 RHS = DAG.getConstant(0, RHS.getValueType());
1987 return X86::COND_LE;
1991 switch (SetCCOpcode) {
1992 default: assert(0 && "Invalid integer condition!");
1993 case ISD::SETEQ: return X86::COND_E;
1994 case ISD::SETGT: return X86::COND_G;
1995 case ISD::SETGE: return X86::COND_GE;
1996 case ISD::SETLT: return X86::COND_L;
1997 case ISD::SETLE: return X86::COND_LE;
1998 case ISD::SETNE: return X86::COND_NE;
1999 case ISD::SETULT: return X86::COND_B;
2000 case ISD::SETUGT: return X86::COND_A;
2001 case ISD::SETULE: return X86::COND_BE;
2002 case ISD::SETUGE: return X86::COND_AE;
2006 // First determine if it is required or is profitable to flip the operands.
2008 // If LHS is a foldable load, but RHS is not, flip the condition.
2009 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2010 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2011 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2012 std::swap(LHS, RHS);
2015 switch (SetCCOpcode) {
2021 std::swap(LHS, RHS);
2025 // On a floating point condition, the flags are set as follows:
2027 // 0 | 0 | 0 | X > Y
2028 // 0 | 0 | 1 | X < Y
2029 // 1 | 0 | 0 | X == Y
2030 // 1 | 1 | 1 | unordered
2031 switch (SetCCOpcode) {
2032 default: assert(0 && "Condcode should be pre-legalized away");
2034 case ISD::SETEQ: return X86::COND_E;
2035 case ISD::SETOLT: // flipped
2037 case ISD::SETGT: return X86::COND_A;
2038 case ISD::SETOLE: // flipped
2040 case ISD::SETGE: return X86::COND_AE;
2041 case ISD::SETUGT: // flipped
2043 case ISD::SETLT: return X86::COND_B;
2044 case ISD::SETUGE: // flipped
2046 case ISD::SETLE: return X86::COND_BE;
2048 case ISD::SETNE: return X86::COND_NE;
2049 case ISD::SETUO: return X86::COND_P;
2050 case ISD::SETO: return X86::COND_NP;
2054 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2055 /// code. Current x86 isa includes the following FP cmov instructions:
2056 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2057 static bool hasFPCMov(unsigned X86CC) {
2073 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2074 /// true if Op is undef or if its value falls within the specified range (L, H].
2075 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2076 if (Op.getOpcode() == ISD::UNDEF)
2079 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2080 return (Val >= Low && Val < Hi);
2083 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2084 /// true if Op is undef or if its value equal to the specified value.
2085 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2086 if (Op.getOpcode() == ISD::UNDEF)
2088 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2091 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2092 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2093 bool X86::isPSHUFDMask(SDNode *N) {
2094 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2096 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2099 // Check if the value doesn't reference the second vector.
2100 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2101 SDValue Arg = N->getOperand(i);
2102 if (Arg.getOpcode() == ISD::UNDEF) continue;
2103 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2104 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2111 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2112 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2113 bool X86::isPSHUFHWMask(SDNode *N) {
2114 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2116 if (N->getNumOperands() != 8)
2119 // Lower quadword copied in order.
2120 for (unsigned i = 0; i != 4; ++i) {
2121 SDValue Arg = N->getOperand(i);
2122 if (Arg.getOpcode() == ISD::UNDEF) continue;
2123 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2124 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2128 // Upper quadword shuffled.
2129 for (unsigned i = 4; i != 8; ++i) {
2130 SDValue Arg = N->getOperand(i);
2131 if (Arg.getOpcode() == ISD::UNDEF) continue;
2132 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2133 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2134 if (Val < 4 || Val > 7)
2141 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2142 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2143 bool X86::isPSHUFLWMask(SDNode *N) {
2144 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2146 if (N->getNumOperands() != 8)
2149 // Upper quadword copied in order.
2150 for (unsigned i = 4; i != 8; ++i)
2151 if (!isUndefOrEqual(N->getOperand(i), i))
2154 // Lower quadword shuffled.
2155 for (unsigned i = 0; i != 4; ++i)
2156 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2162 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2163 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2164 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2165 if (NumElems != 2 && NumElems != 4) return false;
2167 unsigned Half = NumElems / 2;
2168 for (unsigned i = 0; i < Half; ++i)
2169 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2171 for (unsigned i = Half; i < NumElems; ++i)
2172 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2178 bool X86::isSHUFPMask(SDNode *N) {
2179 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2180 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2183 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2184 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2185 /// half elements to come from vector 1 (which would equal the dest.) and
2186 /// the upper half to come from vector 2.
2187 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2188 if (NumOps != 2 && NumOps != 4) return false;
2190 unsigned Half = NumOps / 2;
2191 for (unsigned i = 0; i < Half; ++i)
2192 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2194 for (unsigned i = Half; i < NumOps; ++i)
2195 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2200 static bool isCommutedSHUFP(SDNode *N) {
2201 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2202 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2205 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2206 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2207 bool X86::isMOVHLPSMask(SDNode *N) {
2208 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2210 if (N->getNumOperands() != 4)
2213 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2214 return isUndefOrEqual(N->getOperand(0), 6) &&
2215 isUndefOrEqual(N->getOperand(1), 7) &&
2216 isUndefOrEqual(N->getOperand(2), 2) &&
2217 isUndefOrEqual(N->getOperand(3), 3);
2220 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2221 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2223 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2224 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2226 if (N->getNumOperands() != 4)
2229 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2230 return isUndefOrEqual(N->getOperand(0), 2) &&
2231 isUndefOrEqual(N->getOperand(1), 3) &&
2232 isUndefOrEqual(N->getOperand(2), 2) &&
2233 isUndefOrEqual(N->getOperand(3), 3);
2236 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2237 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2238 bool X86::isMOVLPMask(SDNode *N) {
2239 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2241 unsigned NumElems = N->getNumOperands();
2242 if (NumElems != 2 && NumElems != 4)
2245 for (unsigned i = 0; i < NumElems/2; ++i)
2246 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2249 for (unsigned i = NumElems/2; i < NumElems; ++i)
2250 if (!isUndefOrEqual(N->getOperand(i), i))
2256 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2257 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2259 bool X86::isMOVHPMask(SDNode *N) {
2260 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2262 unsigned NumElems = N->getNumOperands();
2263 if (NumElems != 2 && NumElems != 4)
2266 for (unsigned i = 0; i < NumElems/2; ++i)
2267 if (!isUndefOrEqual(N->getOperand(i), i))
2270 for (unsigned i = 0; i < NumElems/2; ++i) {
2271 SDValue Arg = N->getOperand(i + NumElems/2);
2272 if (!isUndefOrEqual(Arg, i + NumElems))
2279 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2280 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2281 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2282 bool V2IsSplat = false) {
2283 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2286 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2287 SDValue BitI = Elts[i];
2288 SDValue BitI1 = Elts[i+1];
2289 if (!isUndefOrEqual(BitI, j))
2292 if (isUndefOrEqual(BitI1, NumElts))
2295 if (!isUndefOrEqual(BitI1, j + NumElts))
2303 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2304 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2305 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2308 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2309 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2310 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2311 bool V2IsSplat = false) {
2312 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2315 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2316 SDValue BitI = Elts[i];
2317 SDValue BitI1 = Elts[i+1];
2318 if (!isUndefOrEqual(BitI, j + NumElts/2))
2321 if (isUndefOrEqual(BitI1, NumElts))
2324 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2332 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2333 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2334 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2337 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2338 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2340 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2341 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2343 unsigned NumElems = N->getNumOperands();
2344 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2347 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2348 SDValue BitI = N->getOperand(i);
2349 SDValue BitI1 = N->getOperand(i+1);
2351 if (!isUndefOrEqual(BitI, j))
2353 if (!isUndefOrEqual(BitI1, j))
2360 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2361 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2363 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2364 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2366 unsigned NumElems = N->getNumOperands();
2367 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2370 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2371 SDValue BitI = N->getOperand(i);
2372 SDValue BitI1 = N->getOperand(i + 1);
2374 if (!isUndefOrEqual(BitI, j))
2376 if (!isUndefOrEqual(BitI1, j))
2383 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2384 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2385 /// MOVSD, and MOVD, i.e. setting the lowest element.
2386 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2387 if (NumElts != 2 && NumElts != 4)
2390 if (!isUndefOrEqual(Elts[0], NumElts))
2393 for (unsigned i = 1; i < NumElts; ++i) {
2394 if (!isUndefOrEqual(Elts[i], i))
2401 bool X86::isMOVLMask(SDNode *N) {
2402 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2403 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2406 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2407 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2408 /// element of vector 2 and the other elements to come from vector 1 in order.
2409 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2410 bool V2IsSplat = false,
2411 bool V2IsUndef = false) {
2412 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2415 if (!isUndefOrEqual(Ops[0], 0))
2418 for (unsigned i = 1; i < NumOps; ++i) {
2419 SDValue Arg = Ops[i];
2420 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2421 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2422 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2429 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2430 bool V2IsUndef = false) {
2431 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2432 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2433 V2IsSplat, V2IsUndef);
2436 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2437 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2438 bool X86::isMOVSHDUPMask(SDNode *N) {
2439 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2441 if (N->getNumOperands() != 4)
2444 // Expect 1, 1, 3, 3
2445 for (unsigned i = 0; i < 2; ++i) {
2446 SDValue Arg = N->getOperand(i);
2447 if (Arg.getOpcode() == ISD::UNDEF) continue;
2448 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2449 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2450 if (Val != 1) return false;
2454 for (unsigned i = 2; i < 4; ++i) {
2455 SDValue Arg = N->getOperand(i);
2456 if (Arg.getOpcode() == ISD::UNDEF) continue;
2457 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2458 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2459 if (Val != 3) return false;
2463 // Don't use movshdup if it can be done with a shufps.
2467 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2468 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2469 bool X86::isMOVSLDUPMask(SDNode *N) {
2470 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2472 if (N->getNumOperands() != 4)
2475 // Expect 0, 0, 2, 2
2476 for (unsigned i = 0; i < 2; ++i) {
2477 SDValue Arg = N->getOperand(i);
2478 if (Arg.getOpcode() == ISD::UNDEF) continue;
2479 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2480 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2481 if (Val != 0) return false;
2485 for (unsigned i = 2; i < 4; ++i) {
2486 SDValue Arg = N->getOperand(i);
2487 if (Arg.getOpcode() == ISD::UNDEF) continue;
2488 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2489 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2490 if (Val != 2) return false;
2494 // Don't use movshdup if it can be done with a shufps.
2498 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2499 /// specifies a identity operation on the LHS or RHS.
2500 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2501 unsigned NumElems = N->getNumOperands();
2502 for (unsigned i = 0; i < NumElems; ++i)
2503 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2508 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2509 /// a splat of a single element.
2510 static bool isSplatMask(SDNode *N) {
2511 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2513 // This is a splat operation if each element of the permute is the same, and
2514 // if the value doesn't reference the second vector.
2515 unsigned NumElems = N->getNumOperands();
2516 SDValue ElementBase;
2518 for (; i != NumElems; ++i) {
2519 SDValue Elt = N->getOperand(i);
2520 if (isa<ConstantSDNode>(Elt)) {
2526 if (!ElementBase.getNode())
2529 for (; i != NumElems; ++i) {
2530 SDValue Arg = N->getOperand(i);
2531 if (Arg.getOpcode() == ISD::UNDEF) continue;
2532 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2533 if (Arg != ElementBase) return false;
2536 // Make sure it is a splat of the first vector operand.
2537 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2540 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2541 /// we want to splat.
2542 static SDValue getSplatMaskEltNo(SDNode *N) {
2543 assert(isSplatMask(N) && "Not a splat mask");
2544 unsigned NumElems = N->getNumOperands();
2545 SDValue ElementBase;
2547 for (; i != NumElems; ++i) {
2548 SDValue Elt = N->getOperand(i);
2549 if (isa<ConstantSDNode>(Elt))
2552 assert(0 && " No splat value found!");
2557 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2558 /// a splat of a single element and it's a 2 or 4 element mask.
2559 bool X86::isSplatMask(SDNode *N) {
2560 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2562 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2563 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2565 return ::isSplatMask(N);
2568 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2569 /// specifies a splat of zero element.
2570 bool X86::isSplatLoMask(SDNode *N) {
2571 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2573 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2574 if (!isUndefOrEqual(N->getOperand(i), 0))
2579 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2580 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2581 bool X86::isMOVDDUPMask(SDNode *N) {
2582 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2584 unsigned e = N->getNumOperands() / 2;
2585 for (unsigned i = 0; i < e; ++i)
2586 if (!isUndefOrEqual(N->getOperand(i), i))
2588 for (unsigned i = 0; i < e; ++i)
2589 if (!isUndefOrEqual(N->getOperand(e+i), i))
2594 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2595 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2597 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2598 unsigned NumOperands = N->getNumOperands();
2599 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2601 for (unsigned i = 0; i < NumOperands; ++i) {
2603 SDValue Arg = N->getOperand(NumOperands-i-1);
2604 if (Arg.getOpcode() != ISD::UNDEF)
2605 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2606 if (Val >= NumOperands) Val -= NumOperands;
2608 if (i != NumOperands - 1)
2615 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2616 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2618 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2620 // 8 nodes, but we only care about the last 4.
2621 for (unsigned i = 7; i >= 4; --i) {
2623 SDValue Arg = N->getOperand(i);
2624 if (Arg.getOpcode() != ISD::UNDEF)
2625 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2634 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2635 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2637 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2639 // 8 nodes, but we only care about the first 4.
2640 for (int i = 3; i >= 0; --i) {
2642 SDValue Arg = N->getOperand(i);
2643 if (Arg.getOpcode() != ISD::UNDEF)
2644 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2653 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2654 /// specifies a 8 element shuffle that can be broken into a pair of
2655 /// PSHUFHW and PSHUFLW.
2656 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2657 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2659 if (N->getNumOperands() != 8)
2662 // Lower quadword shuffled.
2663 for (unsigned i = 0; i != 4; ++i) {
2664 SDValue Arg = N->getOperand(i);
2665 if (Arg.getOpcode() == ISD::UNDEF) continue;
2666 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2667 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2672 // Upper quadword shuffled.
2673 for (unsigned i = 4; i != 8; ++i) {
2674 SDValue Arg = N->getOperand(i);
2675 if (Arg.getOpcode() == ISD::UNDEF) continue;
2676 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2677 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2678 if (Val < 4 || Val > 7)
2685 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2686 /// values in ther permute mask.
2687 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2688 SDValue &V2, SDValue &Mask,
2689 SelectionDAG &DAG) {
2690 MVT VT = Op.getValueType();
2691 MVT MaskVT = Mask.getValueType();
2692 MVT EltVT = MaskVT.getVectorElementType();
2693 unsigned NumElems = Mask.getNumOperands();
2694 SmallVector<SDValue, 8> MaskVec;
2696 for (unsigned i = 0; i != NumElems; ++i) {
2697 SDValue Arg = Mask.getOperand(i);
2698 if (Arg.getOpcode() == ISD::UNDEF) {
2699 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2702 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2703 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2705 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2707 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2711 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2712 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2715 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2716 /// the two vector operands have swapped position.
2718 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2719 MVT MaskVT = Mask.getValueType();
2720 MVT EltVT = MaskVT.getVectorElementType();
2721 unsigned NumElems = Mask.getNumOperands();
2722 SmallVector<SDValue, 8> MaskVec;
2723 for (unsigned i = 0; i != NumElems; ++i) {
2724 SDValue Arg = Mask.getOperand(i);
2725 if (Arg.getOpcode() == ISD::UNDEF) {
2726 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2729 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2730 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2732 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2734 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2736 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2740 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2741 /// match movhlps. The lower half elements should come from upper half of
2742 /// V1 (and in order), and the upper half elements should come from the upper
2743 /// half of V2 (and in order).
2744 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2745 unsigned NumElems = Mask->getNumOperands();
2748 for (unsigned i = 0, e = 2; i != e; ++i)
2749 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2751 for (unsigned i = 2; i != 4; ++i)
2752 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2757 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2758 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2760 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2761 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2763 N = N->getOperand(0).getNode();
2764 if (!ISD::isNON_EXTLoad(N))
2767 *LD = cast<LoadSDNode>(N);
2771 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2772 /// match movlp{s|d}. The lower half elements should come from lower half of
2773 /// V1 (and in order), and the upper half elements should come from the upper
2774 /// half of V2 (and in order). And since V1 will become the source of the
2775 /// MOVLP, it must be either a vector load or a scalar load to vector.
2776 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2777 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2779 // Is V2 is a vector load, don't do this transformation. We will try to use
2780 // load folding shufps op.
2781 if (ISD::isNON_EXTLoad(V2))
2784 unsigned NumElems = Mask->getNumOperands();
2785 if (NumElems != 2 && NumElems != 4)
2787 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2788 if (!isUndefOrEqual(Mask->getOperand(i), i))
2790 for (unsigned i = NumElems/2; i != NumElems; ++i)
2791 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2796 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2798 static bool isSplatVector(SDNode *N) {
2799 if (N->getOpcode() != ISD::BUILD_VECTOR)
2802 SDValue SplatValue = N->getOperand(0);
2803 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2804 if (N->getOperand(i) != SplatValue)
2809 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2811 static bool isUndefShuffle(SDNode *N) {
2812 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2815 SDValue V1 = N->getOperand(0);
2816 SDValue V2 = N->getOperand(1);
2817 SDValue Mask = N->getOperand(2);
2818 unsigned NumElems = Mask.getNumOperands();
2819 for (unsigned i = 0; i != NumElems; ++i) {
2820 SDValue Arg = Mask.getOperand(i);
2821 if (Arg.getOpcode() != ISD::UNDEF) {
2822 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2823 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2825 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2832 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2834 static inline bool isZeroNode(SDValue Elt) {
2835 return ((isa<ConstantSDNode>(Elt) &&
2836 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2837 (isa<ConstantFPSDNode>(Elt) &&
2838 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2841 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2842 /// to an zero vector.
2843 static bool isZeroShuffle(SDNode *N) {
2844 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2847 SDValue V1 = N->getOperand(0);
2848 SDValue V2 = N->getOperand(1);
2849 SDValue Mask = N->getOperand(2);
2850 unsigned NumElems = Mask.getNumOperands();
2851 for (unsigned i = 0; i != NumElems; ++i) {
2852 SDValue Arg = Mask.getOperand(i);
2853 if (Arg.getOpcode() == ISD::UNDEF)
2856 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2857 if (Idx < NumElems) {
2858 unsigned Opc = V1.getNode()->getOpcode();
2859 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2861 if (Opc != ISD::BUILD_VECTOR ||
2862 !isZeroNode(V1.getNode()->getOperand(Idx)))
2864 } else if (Idx >= NumElems) {
2865 unsigned Opc = V2.getNode()->getOpcode();
2866 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2868 if (Opc != ISD::BUILD_VECTOR ||
2869 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2876 /// getZeroVector - Returns a vector of specified type with all zero elements.
2878 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2879 assert(VT.isVector() && "Expected a vector type");
2881 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2882 // type. This ensures they get CSE'd.
2884 if (VT.getSizeInBits() == 64) { // MMX
2885 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2886 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2887 } else if (HasSSE2) { // SSE2
2888 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2889 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2891 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2892 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2894 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2897 /// getOnesVector - Returns a vector of specified type with all bits set.
2899 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2900 assert(VT.isVector() && "Expected a vector type");
2902 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2903 // type. This ensures they get CSE'd.
2904 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2906 if (VT.getSizeInBits() == 64) // MMX
2907 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2909 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2910 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2914 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2915 /// that point to V2 points to its first element.
2916 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2917 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2919 bool Changed = false;
2920 SmallVector<SDValue, 8> MaskVec;
2921 unsigned NumElems = Mask.getNumOperands();
2922 for (unsigned i = 0; i != NumElems; ++i) {
2923 SDValue Arg = Mask.getOperand(i);
2924 if (Arg.getOpcode() != ISD::UNDEF) {
2925 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2926 if (Val > NumElems) {
2927 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2931 MaskVec.push_back(Arg);
2935 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2936 &MaskVec[0], MaskVec.size());
2940 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2941 /// operation of specified width.
2942 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2943 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2944 MVT BaseVT = MaskVT.getVectorElementType();
2946 SmallVector<SDValue, 8> MaskVec;
2947 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2948 for (unsigned i = 1; i != NumElems; ++i)
2949 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2950 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2953 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2954 /// of specified width.
2955 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2956 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2957 MVT BaseVT = MaskVT.getVectorElementType();
2958 SmallVector<SDValue, 8> MaskVec;
2959 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2960 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2961 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2963 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2966 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2967 /// of specified width.
2968 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2969 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2970 MVT BaseVT = MaskVT.getVectorElementType();
2971 unsigned Half = NumElems/2;
2972 SmallVector<SDValue, 8> MaskVec;
2973 for (unsigned i = 0; i != Half; ++i) {
2974 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2975 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2977 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2980 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2981 /// element #0 of a vector with the specified index, leaving the rest of the
2982 /// elements in place.
2983 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2984 SelectionDAG &DAG) {
2985 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2986 MVT BaseVT = MaskVT.getVectorElementType();
2987 SmallVector<SDValue, 8> MaskVec;
2988 // Element #0 of the result gets the elt we are replacing.
2989 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2990 for (unsigned i = 1; i != NumElems; ++i)
2991 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2992 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2995 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2996 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2997 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2998 MVT VT = Op.getValueType();
3001 SDValue V1 = Op.getOperand(0);
3002 SDValue Mask = Op.getOperand(2);
3003 unsigned MaskNumElems = Mask.getNumOperands();
3004 unsigned NumElems = MaskNumElems;
3005 // Special handling of v4f32 -> v4i32.
3006 if (VT != MVT::v4f32) {
3007 // Find which element we want to splat.
3008 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3009 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3010 // unpack elements to the correct location
3011 while (NumElems > 4) {
3012 if (EltNo < NumElems/2) {
3013 Mask = getUnpacklMask(MaskNumElems, DAG);
3015 Mask = getUnpackhMask(MaskNumElems, DAG);
3016 EltNo -= NumElems/2;
3018 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3021 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3022 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
3025 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3026 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3027 DAG.getNode(ISD::UNDEF, PVT), Mask);
3028 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3031 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3032 /// load that's promoted to vector, or a load bitcasted.
3033 static bool isVectorLoad(SDValue Op) {
3034 assert(Op.getValueType().isVector() && "Expected a vector type");
3035 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3036 Op.getOpcode() == ISD::BIT_CONVERT) {
3037 return isa<LoadSDNode>(Op.getOperand(0));
3039 return isa<LoadSDNode>(Op);
3043 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3045 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3046 SelectionDAG &DAG, bool HasSSE3) {
3047 // If we have sse3 and shuffle has more than one use or input is a load, then
3048 // use movddup. Otherwise, use movlhps.
3049 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3050 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3051 MVT VT = Op.getValueType();
3054 unsigned NumElems = PVT.getVectorNumElements();
3055 if (NumElems == 2) {
3056 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3057 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3059 assert(NumElems == 4);
3060 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3061 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3062 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
3065 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3066 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3067 DAG.getNode(ISD::UNDEF, PVT), Mask);
3068 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3071 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3072 /// vector of zero or undef vector. This produces a shuffle where the low
3073 /// element of V2 is swizzled into the zero/undef vector, landing at element
3074 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3075 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3076 bool isZero, bool HasSSE2,
3077 SelectionDAG &DAG) {
3078 MVT VT = V2.getValueType();
3080 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
3081 unsigned NumElems = V2.getValueType().getVectorNumElements();
3082 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3083 MVT EVT = MaskVT.getVectorElementType();
3084 SmallVector<SDValue, 16> MaskVec;
3085 for (unsigned i = 0; i != NumElems; ++i)
3086 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3087 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3089 MaskVec.push_back(DAG.getConstant(i, EVT));
3090 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3091 &MaskVec[0], MaskVec.size());
3092 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3095 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3096 /// a shuffle that is zero.
3098 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3099 unsigned NumElems, bool Low,
3100 SelectionDAG &DAG) {
3101 unsigned NumZeros = 0;
3102 for (unsigned i = 0; i < NumElems; ++i) {
3103 unsigned Index = Low ? i : NumElems-i-1;
3104 SDValue Idx = Mask.getOperand(Index);
3105 if (Idx.getOpcode() == ISD::UNDEF) {
3109 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3110 if (Elt.getNode() && isZeroNode(Elt))
3118 /// isVectorShift - Returns true if the shuffle can be implemented as a
3119 /// logical left or right shift of a vector.
3120 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3121 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3122 unsigned NumElems = Mask.getNumOperands();
3125 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3128 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3133 bool SeenV1 = false;
3134 bool SeenV2 = false;
3135 for (unsigned i = NumZeros; i < NumElems; ++i) {
3136 unsigned Val = isLeft ? (i - NumZeros) : i;
3137 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3138 if (Idx.getOpcode() == ISD::UNDEF)
3140 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3141 if (Index < NumElems)
3150 if (SeenV1 && SeenV2)
3153 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3159 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3161 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3162 unsigned NumNonZero, unsigned NumZero,
3163 SelectionDAG &DAG, TargetLowering &TLI) {
3169 for (unsigned i = 0; i < 16; ++i) {
3170 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3171 if (ThisIsNonZero && First) {
3173 V = getZeroVector(MVT::v8i16, true, DAG);
3175 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3180 SDValue ThisElt(0, 0), LastElt(0, 0);
3181 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3182 if (LastIsNonZero) {
3183 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3185 if (ThisIsNonZero) {
3186 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3187 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3188 ThisElt, DAG.getConstant(8, MVT::i8));
3190 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3194 if (ThisElt.getNode())
3195 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3196 DAG.getIntPtrConstant(i/2));
3200 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3203 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3205 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3206 unsigned NumNonZero, unsigned NumZero,
3207 SelectionDAG &DAG, TargetLowering &TLI) {
3213 for (unsigned i = 0; i < 8; ++i) {
3214 bool isNonZero = (NonZeros & (1 << i)) != 0;
3218 V = getZeroVector(MVT::v8i16, true, DAG);
3220 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3223 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3224 DAG.getIntPtrConstant(i));
3231 /// getVShift - Return a vector logical shift node.
3233 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3234 unsigned NumBits, SelectionDAG &DAG,
3235 const TargetLowering &TLI) {
3236 bool isMMX = VT.getSizeInBits() == 64;
3237 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3238 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3239 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3240 return DAG.getNode(ISD::BIT_CONVERT, VT,
3241 DAG.getNode(Opc, ShVT, SrcOp,
3242 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3246 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3247 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3248 if (ISD::isBuildVectorAllZeros(Op.getNode())
3249 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3250 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3251 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3252 // eliminated on x86-32 hosts.
3253 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3256 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3257 return getOnesVector(Op.getValueType(), DAG);
3258 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3261 MVT VT = Op.getValueType();
3262 MVT EVT = VT.getVectorElementType();
3263 unsigned EVTBits = EVT.getSizeInBits();
3265 unsigned NumElems = Op.getNumOperands();
3266 unsigned NumZero = 0;
3267 unsigned NumNonZero = 0;
3268 unsigned NonZeros = 0;
3269 bool IsAllConstants = true;
3270 SmallSet<SDValue, 8> Values;
3271 for (unsigned i = 0; i < NumElems; ++i) {
3272 SDValue Elt = Op.getOperand(i);
3273 if (Elt.getOpcode() == ISD::UNDEF)
3276 if (Elt.getOpcode() != ISD::Constant &&
3277 Elt.getOpcode() != ISD::ConstantFP)
3278 IsAllConstants = false;
3279 if (isZeroNode(Elt))
3282 NonZeros |= (1 << i);
3287 if (NumNonZero == 0) {
3288 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3289 return DAG.getNode(ISD::UNDEF, VT);
3292 // Special case for single non-zero, non-undef, element.
3293 if (NumNonZero == 1 && NumElems <= 4) {
3294 unsigned Idx = CountTrailingZeros_32(NonZeros);
3295 SDValue Item = Op.getOperand(Idx);
3297 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3298 // the value are obviously zero, truncate the value to i32 and do the
3299 // insertion that way. Only do this if the value is non-constant or if the
3300 // value is a constant being inserted into element 0. It is cheaper to do
3301 // a constant pool load than it is to do a movd + shuffle.
3302 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3303 (!IsAllConstants || Idx == 0)) {
3304 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3305 // Handle MMX and SSE both.
3306 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3307 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3309 // Truncate the value (which may itself be a constant) to i32, and
3310 // convert it to a vector with movd (S2V+shuffle to zero extend).
3311 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3312 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3313 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3314 Subtarget->hasSSE2(), DAG);
3316 // Now we have our 32-bit value zero extended in the low element of
3317 // a vector. If Idx != 0, swizzle it into place.
3320 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3321 getSwapEltZeroMask(VecElts, Idx, DAG)
3323 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3325 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3329 // If we have a constant or non-constant insertion into the low element of
3330 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3331 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3332 // depending on what the source datatype is. Because we can only get here
3333 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3335 // Don't do this for i64 values on x86-32.
3336 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3337 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3338 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3339 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3340 Subtarget->hasSSE2(), DAG);
3343 // Is it a vector logical left shift?
3344 if (NumElems == 2 && Idx == 1 &&
3345 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3346 unsigned NumBits = VT.getSizeInBits();
3347 return getVShift(true, VT,
3348 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3349 NumBits/2, DAG, *this);
3352 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3355 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3356 // is a non-constant being inserted into an element other than the low one,
3357 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3358 // movd/movss) to move this into the low element, then shuffle it into
3360 if (EVTBits == 32) {
3361 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3363 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3364 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3365 Subtarget->hasSSE2(), DAG);
3366 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3367 MVT MaskEVT = MaskVT.getVectorElementType();
3368 SmallVector<SDValue, 8> MaskVec;
3369 for (unsigned i = 0; i < NumElems; i++)
3370 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3371 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3372 &MaskVec[0], MaskVec.size());
3373 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3374 DAG.getNode(ISD::UNDEF, VT), Mask);
3378 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3379 if (Values.size() == 1)
3382 // A vector full of immediates; various special cases are already
3383 // handled, so this is best done with a single constant-pool load.
3387 // Let legalizer expand 2-wide build_vectors.
3388 if (EVTBits == 64) {
3389 if (NumNonZero == 1) {
3390 // One half is zero or undef.
3391 unsigned Idx = CountTrailingZeros_32(NonZeros);
3392 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3393 Op.getOperand(Idx));
3394 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3395 Subtarget->hasSSE2(), DAG);
3400 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3401 if (EVTBits == 8 && NumElems == 16) {
3402 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3404 if (V.getNode()) return V;
3407 if (EVTBits == 16 && NumElems == 8) {
3408 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3410 if (V.getNode()) return V;
3413 // If element VT is == 32 bits, turn it into a number of shuffles.
3414 SmallVector<SDValue, 8> V;
3416 if (NumElems == 4 && NumZero > 0) {
3417 for (unsigned i = 0; i < 4; ++i) {
3418 bool isZero = !(NonZeros & (1 << i));
3420 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3422 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3425 for (unsigned i = 0; i < 2; ++i) {
3426 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3429 V[i] = V[i*2]; // Must be a zero vector.
3432 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3433 getMOVLMask(NumElems, DAG));
3436 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3437 getMOVLMask(NumElems, DAG));
3440 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3441 getUnpacklMask(NumElems, DAG));
3446 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3447 MVT EVT = MaskVT.getVectorElementType();
3448 SmallVector<SDValue, 8> MaskVec;
3449 bool Reverse = (NonZeros & 0x3) == 2;
3450 for (unsigned i = 0; i < 2; ++i)
3452 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3454 MaskVec.push_back(DAG.getConstant(i, EVT));
3455 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3456 for (unsigned i = 0; i < 2; ++i)
3458 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3460 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3461 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3462 &MaskVec[0], MaskVec.size());
3463 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3466 if (Values.size() > 2) {
3467 // Expand into a number of unpckl*.
3469 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3470 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3471 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3472 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3473 for (unsigned i = 0; i < NumElems; ++i)
3474 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3476 while (NumElems != 0) {
3477 for (unsigned i = 0; i < NumElems; ++i)
3478 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3489 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3490 SDValue PermMask, SelectionDAG &DAG,
3491 TargetLowering &TLI) {
3493 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3494 MVT MaskEVT = MaskVT.getVectorElementType();
3495 MVT PtrVT = TLI.getPointerTy();
3496 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3497 PermMask.getNode()->op_end());
3499 // First record which half of which vector the low elements come from.
3500 SmallVector<unsigned, 4> LowQuad(4);
3501 for (unsigned i = 0; i < 4; ++i) {
3502 SDValue Elt = MaskElts[i];
3503 if (Elt.getOpcode() == ISD::UNDEF)
3505 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3506 int QuadIdx = EltIdx / 4;
3510 int BestLowQuad = -1;
3511 unsigned MaxQuad = 1;
3512 for (unsigned i = 0; i < 4; ++i) {
3513 if (LowQuad[i] > MaxQuad) {
3515 MaxQuad = LowQuad[i];
3519 // Record which half of which vector the high elements come from.
3520 SmallVector<unsigned, 4> HighQuad(4);
3521 for (unsigned i = 4; i < 8; ++i) {
3522 SDValue Elt = MaskElts[i];
3523 if (Elt.getOpcode() == ISD::UNDEF)
3525 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3526 int QuadIdx = EltIdx / 4;
3527 ++HighQuad[QuadIdx];
3530 int BestHighQuad = -1;
3532 for (unsigned i = 0; i < 4; ++i) {
3533 if (HighQuad[i] > MaxQuad) {
3535 MaxQuad = HighQuad[i];
3539 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3540 if (BestLowQuad != -1 || BestHighQuad != -1) {
3541 // First sort the 4 chunks in order using shufpd.
3542 SmallVector<SDValue, 8> MaskVec;
3544 if (BestLowQuad != -1)
3545 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3547 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3549 if (BestHighQuad != -1)
3550 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3552 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3554 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3555 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3556 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3557 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3558 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3560 // Now sort high and low parts separately.
3561 BitVector InOrder(8);
3562 if (BestLowQuad != -1) {
3563 // Sort lower half in order using PSHUFLW.
3565 bool AnyOutOrder = false;
3567 for (unsigned i = 0; i != 4; ++i) {
3568 SDValue Elt = MaskElts[i];
3569 if (Elt.getOpcode() == ISD::UNDEF) {
3570 MaskVec.push_back(Elt);
3573 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3577 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3579 // If this element is in the right place after this shuffle, then
3581 if ((int)(EltIdx / 4) == BestLowQuad)
3586 for (unsigned i = 4; i != 8; ++i)
3587 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3588 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3589 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3593 if (BestHighQuad != -1) {
3594 // Sort high half in order using PSHUFHW if possible.
3597 for (unsigned i = 0; i != 4; ++i)
3598 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3600 bool AnyOutOrder = false;
3601 for (unsigned i = 4; i != 8; ++i) {
3602 SDValue Elt = MaskElts[i];
3603 if (Elt.getOpcode() == ISD::UNDEF) {
3604 MaskVec.push_back(Elt);
3607 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3611 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3613 // If this element is in the right place after this shuffle, then
3615 if ((int)(EltIdx / 4) == BestHighQuad)
3621 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3622 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3626 // The other elements are put in the right place using pextrw and pinsrw.
3627 for (unsigned i = 0; i != 8; ++i) {
3630 SDValue Elt = MaskElts[i];
3631 if (Elt.getOpcode() == ISD::UNDEF)
3633 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3634 SDValue ExtOp = (EltIdx < 8)
3635 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3636 DAG.getConstant(EltIdx, PtrVT))
3637 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3638 DAG.getConstant(EltIdx - 8, PtrVT));
3639 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3640 DAG.getConstant(i, PtrVT));
3646 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3647 // few as possible. First, let's find out how many elements are already in the
3649 unsigned V1InOrder = 0;
3650 unsigned V1FromV1 = 0;
3651 unsigned V2InOrder = 0;
3652 unsigned V2FromV2 = 0;
3653 SmallVector<SDValue, 8> V1Elts;
3654 SmallVector<SDValue, 8> V2Elts;
3655 for (unsigned i = 0; i < 8; ++i) {
3656 SDValue Elt = MaskElts[i];
3657 if (Elt.getOpcode() == ISD::UNDEF) {
3658 V1Elts.push_back(Elt);
3659 V2Elts.push_back(Elt);
3664 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3666 V1Elts.push_back(Elt);
3667 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3669 } else if (EltIdx == i+8) {
3670 V1Elts.push_back(Elt);
3671 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3673 } else if (EltIdx < 8) {
3674 V1Elts.push_back(Elt);
3675 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3678 V1Elts.push_back(Elt);
3679 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3684 if (V2InOrder > V1InOrder) {
3685 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3687 std::swap(V1Elts, V2Elts);
3688 std::swap(V1FromV1, V2FromV2);
3691 if ((V1FromV1 + V1InOrder) != 8) {
3692 // Some elements are from V2.
3694 // If there are elements that are from V1 but out of place,
3695 // then first sort them in place
3696 SmallVector<SDValue, 8> MaskVec;
3697 for (unsigned i = 0; i < 8; ++i) {
3698 SDValue Elt = V1Elts[i];
3699 if (Elt.getOpcode() == ISD::UNDEF) {
3700 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3703 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3705 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3707 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3709 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3710 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3714 for (unsigned i = 0; i < 8; ++i) {
3715 SDValue Elt = V1Elts[i];
3716 if (Elt.getOpcode() == ISD::UNDEF)
3718 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3721 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3722 DAG.getConstant(EltIdx - 8, PtrVT));
3723 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3724 DAG.getConstant(i, PtrVT));
3728 // All elements are from V1.
3730 for (unsigned i = 0; i < 8; ++i) {
3731 SDValue Elt = V1Elts[i];
3732 if (Elt.getOpcode() == ISD::UNDEF)
3734 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3735 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3736 DAG.getConstant(EltIdx, PtrVT));
3737 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3738 DAG.getConstant(i, PtrVT));
3744 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3745 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3746 /// done when every pair / quad of shuffle mask elements point to elements in
3747 /// the right sequence. e.g.
3748 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3750 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3752 SDValue PermMask, SelectionDAG &DAG,
3753 TargetLowering &TLI) {
3754 unsigned NumElems = PermMask.getNumOperands();
3755 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3756 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3757 MVT MaskEltVT = MaskVT.getVectorElementType();
3759 switch (VT.getSimpleVT()) {
3760 default: assert(false && "Unexpected!");
3761 case MVT::v4f32: NewVT = MVT::v2f64; break;
3762 case MVT::v4i32: NewVT = MVT::v2i64; break;
3763 case MVT::v8i16: NewVT = MVT::v4i32; break;
3764 case MVT::v16i8: NewVT = MVT::v4i32; break;
3767 if (NewWidth == 2) {
3773 unsigned Scale = NumElems / NewWidth;
3774 SmallVector<SDValue, 8> MaskVec;
3775 for (unsigned i = 0; i < NumElems; i += Scale) {
3776 unsigned StartIdx = ~0U;
3777 for (unsigned j = 0; j < Scale; ++j) {
3778 SDValue Elt = PermMask.getOperand(i+j);
3779 if (Elt.getOpcode() == ISD::UNDEF)
3781 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3782 if (StartIdx == ~0U)
3783 StartIdx = EltIdx - (EltIdx % Scale);
3784 if (EltIdx != StartIdx + j)
3787 if (StartIdx == ~0U)
3788 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3790 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3793 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3794 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3795 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3796 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3797 &MaskVec[0], MaskVec.size()));
3800 /// getVZextMovL - Return a zero-extending vector move low node.
3802 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3803 SDValue SrcOp, SelectionDAG &DAG,
3804 const X86Subtarget *Subtarget) {
3805 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3806 LoadSDNode *LD = NULL;
3807 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3808 LD = dyn_cast<LoadSDNode>(SrcOp);
3810 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3812 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3813 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3814 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3815 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3816 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3818 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3819 return DAG.getNode(ISD::BIT_CONVERT, VT,
3820 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3821 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3828 return DAG.getNode(ISD::BIT_CONVERT, VT,
3829 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3830 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3833 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3836 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3837 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3838 MVT MaskVT = PermMask.getValueType();
3839 MVT MaskEVT = MaskVT.getVectorElementType();
3840 SmallVector<std::pair<int, int>, 8> Locs;
3842 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3845 for (unsigned i = 0; i != 4; ++i) {
3846 SDValue Elt = PermMask.getOperand(i);
3847 if (Elt.getOpcode() == ISD::UNDEF) {
3848 Locs[i] = std::make_pair(-1, -1);
3850 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3851 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3853 Locs[i] = std::make_pair(0, NumLo);
3857 Locs[i] = std::make_pair(1, NumHi);
3859 Mask1[2+NumHi] = Elt;
3865 if (NumLo <= 2 && NumHi <= 2) {
3866 // If no more than two elements come from either vector. This can be
3867 // implemented with two shuffles. First shuffle gather the elements.
3868 // The second shuffle, which takes the first shuffle as both of its
3869 // vector operands, put the elements into the right order.
3870 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3871 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3872 &Mask1[0], Mask1.size()));
3874 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3875 for (unsigned i = 0; i != 4; ++i) {
3876 if (Locs[i].first == -1)
3879 unsigned Idx = (i < 2) ? 0 : 4;
3880 Idx += Locs[i].first * 2 + Locs[i].second;
3881 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3885 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3886 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3887 &Mask2[0], Mask2.size()));
3888 } else if (NumLo == 3 || NumHi == 3) {
3889 // Otherwise, we must have three elements from one vector, call it X, and
3890 // one element from the other, call it Y. First, use a shufps to build an
3891 // intermediate vector with the one element from Y and the element from X
3892 // that will be in the same half in the final destination (the indexes don't
3893 // matter). Then, use a shufps to build the final vector, taking the half
3894 // containing the element from Y from the intermediate, and the other half
3897 // Normalize it so the 3 elements come from V1.
3898 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3902 // Find the element from V2.
3904 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3905 SDValue Elt = PermMask.getOperand(HiIndex);
3906 if (Elt.getOpcode() == ISD::UNDEF)
3908 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3913 Mask1[0] = PermMask.getOperand(HiIndex);
3914 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3915 Mask1[2] = PermMask.getOperand(HiIndex^1);
3916 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3917 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3918 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3921 Mask1[0] = PermMask.getOperand(0);
3922 Mask1[1] = PermMask.getOperand(1);
3923 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3924 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3925 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3926 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3928 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3929 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3930 Mask1[2] = PermMask.getOperand(2);
3931 Mask1[3] = PermMask.getOperand(3);
3932 if (Mask1[2].getOpcode() != ISD::UNDEF)
3934 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3936 if (Mask1[3].getOpcode() != ISD::UNDEF)
3938 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3940 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3941 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3945 // Break it into (shuffle shuffle_hi, shuffle_lo).
3947 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3948 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3949 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3950 unsigned MaskIdx = 0;
3953 for (unsigned i = 0; i != 4; ++i) {
3960 SDValue Elt = PermMask.getOperand(i);
3961 if (Elt.getOpcode() == ISD::UNDEF) {
3962 Locs[i] = std::make_pair(-1, -1);
3963 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3964 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3965 (*MaskPtr)[LoIdx] = Elt;
3968 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3969 (*MaskPtr)[HiIdx] = Elt;
3974 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3975 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3976 &LoMask[0], LoMask.size()));
3977 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3978 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3979 &HiMask[0], HiMask.size()));
3980 SmallVector<SDValue, 8> MaskOps;
3981 for (unsigned i = 0; i != 4; ++i) {
3982 if (Locs[i].first == -1) {
3983 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3985 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3986 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3989 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3990 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3991 &MaskOps[0], MaskOps.size()));
3995 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3996 SDValue V1 = Op.getOperand(0);
3997 SDValue V2 = Op.getOperand(1);
3998 SDValue PermMask = Op.getOperand(2);
3999 MVT VT = Op.getValueType();
4000 unsigned NumElems = PermMask.getNumOperands();
4001 bool isMMX = VT.getSizeInBits() == 64;
4002 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4003 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4004 bool V1IsSplat = false;
4005 bool V2IsSplat = false;
4007 if (isUndefShuffle(Op.getNode()))
4008 return DAG.getNode(ISD::UNDEF, VT);
4010 if (isZeroShuffle(Op.getNode()))
4011 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
4013 if (isIdentityMask(PermMask.getNode()))
4015 else if (isIdentityMask(PermMask.getNode(), true))
4018 // Canonicalize movddup shuffles.
4019 if (V2IsUndef && Subtarget->hasSSE2() &&
4020 VT.getSizeInBits() == 128 &&
4021 X86::isMOVDDUPMask(PermMask.getNode()))
4022 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4024 if (isSplatMask(PermMask.getNode())) {
4025 if (isMMX || NumElems < 4) return Op;
4026 // Promote it to a v4{if}32 splat.
4027 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4030 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4032 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4033 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
4034 if (NewOp.getNode())
4035 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
4036 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4037 // FIXME: Figure out a cleaner way to do this.
4038 // Try to make use of movq to zero out the top part.
4039 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4040 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4042 if (NewOp.getNode()) {
4043 SDValue NewV1 = NewOp.getOperand(0);
4044 SDValue NewV2 = NewOp.getOperand(1);
4045 SDValue NewMask = NewOp.getOperand(2);
4046 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4047 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4048 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
4051 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4052 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4054 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4055 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4060 // Check if this can be converted into a logical shift.
4061 bool isLeft = false;
4064 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4065 if (isShift && ShVal.hasOneUse()) {
4066 // If the shifted value has multiple uses, it may be cheaper to use
4067 // v_set0 + movlhps or movhlps, etc.
4068 MVT EVT = VT.getVectorElementType();
4069 ShAmt *= EVT.getSizeInBits();
4070 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4073 if (X86::isMOVLMask(PermMask.getNode())) {
4076 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4077 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
4082 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4083 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4084 X86::isMOVHLPSMask(PermMask.getNode()) ||
4085 X86::isMOVHPMask(PermMask.getNode()) ||
4086 X86::isMOVLPMask(PermMask.getNode())))
4089 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4090 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4091 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4094 // No better options. Use a vshl / vsrl.
4095 MVT EVT = VT.getVectorElementType();
4096 ShAmt *= EVT.getSizeInBits();
4097 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4100 bool Commuted = false;
4101 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4102 // 1,1,1,1 -> v8i16 though.
4103 V1IsSplat = isSplatVector(V1.getNode());
4104 V2IsSplat = isSplatVector(V2.getNode());
4106 // Canonicalize the splat or undef, if present, to be on the RHS.
4107 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4108 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4109 std::swap(V1IsSplat, V2IsSplat);
4110 std::swap(V1IsUndef, V2IsUndef);
4114 // FIXME: Figure out a cleaner way to do this.
4115 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4116 if (V2IsUndef) return V1;
4117 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4119 // V2 is a splat, so the mask may be malformed. That is, it may point
4120 // to any V2 element. The instruction selectior won't like this. Get
4121 // a corrected mask and commute to form a proper MOVS{S|D}.
4122 SDValue NewMask = getMOVLMask(NumElems, DAG);
4123 if (NewMask.getNode() != PermMask.getNode())
4124 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4129 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4130 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4131 X86::isUNPCKLMask(PermMask.getNode()) ||
4132 X86::isUNPCKHMask(PermMask.getNode()))
4136 // Normalize mask so all entries that point to V2 points to its first
4137 // element then try to match unpck{h|l} again. If match, return a
4138 // new vector_shuffle with the corrected mask.
4139 SDValue NewMask = NormalizeMask(PermMask, DAG);
4140 if (NewMask.getNode() != PermMask.getNode()) {
4141 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4142 SDValue NewMask = getUnpacklMask(NumElems, DAG);
4143 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4144 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4145 SDValue NewMask = getUnpackhMask(NumElems, DAG);
4146 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4151 // Normalize the node to match x86 shuffle ops if needed
4152 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4153 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4156 // Commute is back and try unpck* again.
4157 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4158 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4159 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4160 X86::isUNPCKLMask(PermMask.getNode()) ||
4161 X86::isUNPCKHMask(PermMask.getNode()))
4165 // Try PSHUF* first, then SHUFP*.
4166 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4167 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4168 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4169 if (V2.getOpcode() != ISD::UNDEF)
4170 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4171 DAG.getNode(ISD::UNDEF, VT), PermMask);
4176 if (Subtarget->hasSSE2() &&
4177 (X86::isPSHUFDMask(PermMask.getNode()) ||
4178 X86::isPSHUFHWMask(PermMask.getNode()) ||
4179 X86::isPSHUFLWMask(PermMask.getNode()))) {
4181 if (VT == MVT::v4f32) {
4183 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4184 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4185 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4186 } else if (V2.getOpcode() != ISD::UNDEF)
4187 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4188 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4190 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4194 // Binary or unary shufps.
4195 if (X86::isSHUFPMask(PermMask.getNode()) ||
4196 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4200 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4201 if (VT == MVT::v8i16) {
4202 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4203 if (NewOp.getNode())
4207 // Handle all 4 wide cases with a number of shuffles except for MMX.
4208 if (NumElems == 4 && !isMMX)
4209 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4215 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4216 SelectionDAG &DAG) {
4217 MVT VT = Op.getValueType();
4218 if (VT.getSizeInBits() == 8) {
4219 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4220 Op.getOperand(0), Op.getOperand(1));
4221 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4222 DAG.getValueType(VT));
4223 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4224 } else if (VT.getSizeInBits() == 16) {
4225 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4226 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4228 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4229 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4230 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32,
4233 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4234 Op.getOperand(0), Op.getOperand(1));
4235 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4236 DAG.getValueType(VT));
4237 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4238 } else if (VT == MVT::f32) {
4239 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4240 // the result back to FR32 register. It's only worth matching if the
4241 // result has a single use which is a store or a bitcast to i32. And in
4242 // the case of a store, it's not worth it if the index is a constant 0,
4243 // because a MOVSSmr can be used instead, which is smaller and faster.
4244 if (!Op.hasOneUse())
4246 SDNode *User = *Op.getNode()->use_begin();
4247 if ((User->getOpcode() != ISD::STORE ||
4248 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4249 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4250 (User->getOpcode() != ISD::BIT_CONVERT ||
4251 User->getValueType(0) != MVT::i32))
4253 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4254 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4256 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4257 } else if (VT == MVT::i32) {
4258 // ExtractPS works with constant index.
4259 if (isa<ConstantSDNode>(Op.getOperand(1)))
4267 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4268 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4271 if (Subtarget->hasSSE41()) {
4272 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4277 MVT VT = Op.getValueType();
4278 // TODO: handle v16i8.
4279 if (VT.getSizeInBits() == 16) {
4280 SDValue Vec = Op.getOperand(0);
4281 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4283 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4284 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4285 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4287 // Transform it so it match pextrw which produces a 32-bit result.
4288 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4289 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4290 Op.getOperand(0), Op.getOperand(1));
4291 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4292 DAG.getValueType(VT));
4293 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4294 } else if (VT.getSizeInBits() == 32) {
4295 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4298 // SHUFPS the element to the lowest double word, then movss.
4299 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4300 SmallVector<SDValue, 8> IdxVec;
4302 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4304 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4306 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4308 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4309 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4310 &IdxVec[0], IdxVec.size());
4311 SDValue Vec = Op.getOperand(0);
4312 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4313 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4314 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4315 DAG.getIntPtrConstant(0));
4316 } else if (VT.getSizeInBits() == 64) {
4317 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4318 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4319 // to match extract_elt for f64.
4320 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4324 // UNPCKHPD the element to the lowest double word, then movsd.
4325 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4326 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4327 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4328 SmallVector<SDValue, 8> IdxVec;
4329 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4331 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4332 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4333 &IdxVec[0], IdxVec.size());
4334 SDValue Vec = Op.getOperand(0);
4335 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4336 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4337 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4338 DAG.getIntPtrConstant(0));
4345 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4346 MVT VT = Op.getValueType();
4347 MVT EVT = VT.getVectorElementType();
4349 SDValue N0 = Op.getOperand(0);
4350 SDValue N1 = Op.getOperand(1);
4351 SDValue N2 = Op.getOperand(2);
4353 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4354 isa<ConstantSDNode>(N2)) {
4355 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4357 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4359 if (N1.getValueType() != MVT::i32)
4360 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4361 if (N2.getValueType() != MVT::i32)
4362 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4363 return DAG.getNode(Opc, VT, N0, N1, N2);
4364 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4365 // Bits [7:6] of the constant are the source select. This will always be
4366 // zero here. The DAG Combiner may combine an extract_elt index into these
4367 // bits. For example (insert (extract, 3), 2) could be matched by putting
4368 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4369 // Bits [5:4] of the constant are the destination select. This is the
4370 // value of the incoming immediate.
4371 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4372 // combine either bitwise AND or insert of float 0.0 to set these bits.
4373 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4374 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4375 } else if (EVT == MVT::i32) {
4376 // InsertPS works with constant index.
4377 if (isa<ConstantSDNode>(N2))
4384 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4385 MVT VT = Op.getValueType();
4386 MVT EVT = VT.getVectorElementType();
4388 if (Subtarget->hasSSE41())
4389 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4394 SDValue N0 = Op.getOperand(0);
4395 SDValue N1 = Op.getOperand(1);
4396 SDValue N2 = Op.getOperand(2);
4398 if (EVT.getSizeInBits() == 16) {
4399 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4400 // as its second argument.
4401 if (N1.getValueType() != MVT::i32)
4402 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4403 if (N2.getValueType() != MVT::i32)
4404 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4405 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4411 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4412 if (Op.getValueType() == MVT::v2f32)
4413 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4414 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4415 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4416 Op.getOperand(0))));
4418 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4419 MVT VT = MVT::v2i32;
4420 switch (Op.getValueType().getSimpleVT()) {
4427 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4428 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4431 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4432 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4433 // one of the above mentioned nodes. It has to be wrapped because otherwise
4434 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4435 // be used to form addressing mode. These wrapped nodes will be selected
4438 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4439 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4440 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4442 CP->getAlignment());
4443 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4444 // With PIC, the address is actually $g + Offset.
4445 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4446 !Subtarget->isPICStyleRIPRel()) {
4447 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4448 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4456 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4458 SelectionDAG &DAG) const {
4459 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4460 bool ExtraLoadRequired =
4461 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4463 // Create the TargetGlobalAddress node, folding in the constant
4464 // offset if it is legal.
4466 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4467 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4470 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4471 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4473 // With PIC, the address is actually $g + Offset.
4474 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4475 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4476 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4480 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4481 // load the value at address GV, not the value of GV itself. This means that
4482 // the GlobalAddress must be in the base or index register of the address, not
4483 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4484 // The same applies for external symbols during PIC codegen
4485 if (ExtraLoadRequired)
4486 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4487 PseudoSourceValue::getGOT(), 0);
4489 // If there was a non-zero offset that we didn't fold, create an explicit
4492 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4493 DAG.getConstant(Offset, getPointerTy()));
4499 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4500 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4501 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4502 return LowerGlobalAddress(GV, Offset, DAG);
4505 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4507 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4510 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4511 DAG.getNode(X86ISD::GlobalBaseReg,
4513 InFlag = Chain.getValue(1);
4515 // emit leal symbol@TLSGD(,%ebx,1), %eax
4516 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4517 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4518 GA->getValueType(0),
4520 SDValue Ops[] = { Chain, TGA, InFlag };
4521 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4522 InFlag = Result.getValue(2);
4523 Chain = Result.getValue(1);
4525 // call ___tls_get_addr. This function receives its argument in
4526 // the register EAX.
4527 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4528 InFlag = Chain.getValue(1);
4530 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4531 SDValue Ops1[] = { Chain,
4532 DAG.getTargetExternalSymbol("___tls_get_addr",
4534 DAG.getRegister(X86::EAX, PtrVT),
4535 DAG.getRegister(X86::EBX, PtrVT),
4537 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4538 InFlag = Chain.getValue(1);
4540 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4543 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4545 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4547 SDValue InFlag, Chain;
4549 // emit leaq symbol@TLSGD(%rip), %rdi
4550 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4551 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4552 GA->getValueType(0),
4554 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4555 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4556 Chain = Result.getValue(1);
4557 InFlag = Result.getValue(2);
4559 // call __tls_get_addr. This function receives its argument in
4560 // the register RDI.
4561 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4562 InFlag = Chain.getValue(1);
4564 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4565 SDValue Ops1[] = { Chain,
4566 DAG.getTargetExternalSymbol("__tls_get_addr",
4568 DAG.getRegister(X86::RDI, PtrVT),
4570 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4571 InFlag = Chain.getValue(1);
4573 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4576 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4577 // "local exec" model.
4578 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4580 // Get the Thread Pointer
4581 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4582 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4584 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4585 GA->getValueType(0),
4587 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4589 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4590 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4591 PseudoSourceValue::getGOT(), 0);
4593 // The address of the thread local variable is the add of the thread
4594 // pointer with the offset of the variable.
4595 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4599 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4600 // TODO: implement the "local dynamic" model
4601 // TODO: implement the "initial exec"model for pic executables
4602 assert(Subtarget->isTargetELF() &&
4603 "TLS not implemented for non-ELF targets");
4604 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4605 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4606 // otherwise use the "Local Exec"TLS Model
4607 if (Subtarget->is64Bit()) {
4608 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4610 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4611 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4613 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4618 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4619 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4620 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4621 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4622 // With PIC, the address is actually $g + Offset.
4623 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4624 !Subtarget->isPICStyleRIPRel()) {
4625 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4626 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4633 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4634 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4635 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4636 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4637 // With PIC, the address is actually $g + Offset.
4638 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4639 !Subtarget->isPICStyleRIPRel()) {
4640 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4641 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4648 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4649 /// take a 2 x i32 value to shift plus a shift amount.
4650 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4651 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4652 MVT VT = Op.getValueType();
4653 unsigned VTBits = VT.getSizeInBits();
4654 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4655 SDValue ShOpLo = Op.getOperand(0);
4656 SDValue ShOpHi = Op.getOperand(1);
4657 SDValue ShAmt = Op.getOperand(2);
4658 SDValue Tmp1 = isSRA ?
4659 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4660 DAG.getConstant(0, VT);
4663 if (Op.getOpcode() == ISD::SHL_PARTS) {
4664 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4665 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4667 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4668 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4671 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4672 DAG.getConstant(VTBits, MVT::i8));
4673 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4674 AndNode, DAG.getConstant(0, MVT::i8));
4677 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4678 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4679 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4681 if (Op.getOpcode() == ISD::SHL_PARTS) {
4682 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4683 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4685 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4686 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4689 SDValue Ops[2] = { Lo, Hi };
4690 return DAG.getMergeValues(Ops, 2);
4693 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4694 MVT SrcVT = Op.getOperand(0).getValueType();
4695 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4696 "Unknown SINT_TO_FP to lower!");
4698 // These are really Legal; caller falls through into that case.
4699 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4701 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4702 Subtarget->is64Bit())
4705 unsigned Size = SrcVT.getSizeInBits()/8;
4706 MachineFunction &MF = DAG.getMachineFunction();
4707 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4708 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4709 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4711 PseudoSourceValue::getFixedStack(SSFI), 0);
4715 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4717 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4719 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4720 SmallVector<SDValue, 8> Ops;
4721 Ops.push_back(Chain);
4722 Ops.push_back(StackSlot);
4723 Ops.push_back(DAG.getValueType(SrcVT));
4724 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4725 Tys, &Ops[0], Ops.size());
4728 Chain = Result.getValue(1);
4729 SDValue InFlag = Result.getValue(2);
4731 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4732 // shouldn't be necessary except that RFP cannot be live across
4733 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4734 MachineFunction &MF = DAG.getMachineFunction();
4735 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4736 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4737 Tys = DAG.getVTList(MVT::Other);
4738 SmallVector<SDValue, 8> Ops;
4739 Ops.push_back(Chain);
4740 Ops.push_back(Result);
4741 Ops.push_back(StackSlot);
4742 Ops.push_back(DAG.getValueType(Op.getValueType()));
4743 Ops.push_back(InFlag);
4744 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4745 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4746 PseudoSourceValue::getFixedStack(SSFI), 0);
4752 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4753 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4754 // This algorithm is not obvious. Here it is in C code, more or less:
4756 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4757 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4758 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4760 // Copy ints to xmm registers.
4761 __m128i xh = _mm_cvtsi32_si128( hi );
4762 __m128i xl = _mm_cvtsi32_si128( lo );
4764 // Combine into low half of a single xmm register.
4765 __m128i x = _mm_unpacklo_epi32( xh, xl );
4769 // Merge in appropriate exponents to give the integer bits the right
4771 x = _mm_unpacklo_epi32( x, exp );
4773 // Subtract away the biases to deal with the IEEE-754 double precision
4775 d = _mm_sub_pd( (__m128d) x, bias );
4777 // All conversions up to here are exact. The correctly rounded result is
4778 // calculated using the current rounding mode using the following
4780 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4781 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4782 // store doesn't really need to be here (except
4783 // maybe to zero the other double)
4788 // Build some magic constants.
4789 std::vector<Constant*> CV0;
4790 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4791 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4792 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4793 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4794 Constant *C0 = ConstantVector::get(CV0);
4795 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4797 std::vector<Constant*> CV1;
4798 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4799 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4800 Constant *C1 = ConstantVector::get(CV1);
4801 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4803 SmallVector<SDValue, 4> MaskVec;
4804 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4805 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4806 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4807 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4808 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],
4810 SmallVector<SDValue, 4> MaskVec2;
4811 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4812 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4813 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec2[0],
4816 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4817 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4819 DAG.getIntPtrConstant(1)));
4820 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4821 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4823 DAG.getIntPtrConstant(0)));
4824 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4825 XR1, XR2, UnpcklMask);
4826 SDValue CLod0 = DAG.getLoad(MVT::v4i32, DAG.getEntryNode(), CPIdx0,
4827 PseudoSourceValue::getConstantPool(), 0,
4829 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4830 Unpck1, CLod0, UnpcklMask);
4831 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Unpck2);
4832 SDValue CLod1 = DAG.getLoad(MVT::v2f64, CLod0.getValue(1), CPIdx1,
4833 PseudoSourceValue::getConstantPool(), 0,
4835 SDValue Sub = DAG.getNode(ISD::FSUB, MVT::v2f64, XR2F, CLod1);
4837 // Add the halves; easiest way is to swap them into another reg first.
4838 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2f64,
4839 Sub, Sub, ShufMask);
4840 SDValue Add = DAG.getNode(ISD::FADD, MVT::v2f64, Shuf, Sub);
4841 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64, Add,
4842 DAG.getIntPtrConstant(0));
4845 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4846 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4847 // FP constant to bias correct the final result.
4848 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4851 // Load the 32-bit value into an XMM register.
4852 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4853 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4855 DAG.getIntPtrConstant(0)));
4857 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64,
4858 DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Load),
4859 DAG.getIntPtrConstant(0));
4861 // Or the load with the bias.
4862 SDValue Or = DAG.getNode(ISD::OR, MVT::v2i64,
4863 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64,
4864 DAG.getNode(ISD::SCALAR_TO_VECTOR,
4866 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64,
4867 DAG.getNode(ISD::SCALAR_TO_VECTOR,
4868 MVT::v2f64, Load)));
4869 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64,
4870 DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Or),
4871 DAG.getIntPtrConstant(0));
4873 // Subtract the bias.
4874 SDValue Sub = DAG.getNode(ISD::FSUB, MVT::f64, Or, Bias);
4876 // Handle final rounding.
4877 return DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub,
4878 DAG.getIntPtrConstant(0));
4881 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4882 MVT SrcVT = Op.getOperand(0).getValueType();
4884 if (SrcVT == MVT::i64) {
4885 // We only handle SSE2 f64 target here; caller can handle the rest.
4886 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4889 return LowerUINT_TO_FP_i64(Op, DAG);
4890 } else if (SrcVT == MVT::i32) {
4891 // We only handle SSE2 f32 target here; caller can handle the rest.
4892 if (Op.getValueType() != MVT::f32 || !X86ScalarSSEf32)
4895 return LowerUINT_TO_FP_i32(Op, DAG);
4898 assert(0 && "Unknown UINT_TO_FP to lower!");
4902 std::pair<SDValue,SDValue> X86TargetLowering::
4903 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4904 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4905 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4906 "Unknown FP_TO_SINT to lower!");
4908 // These are really Legal.
4909 if (Op.getValueType() == MVT::i32 &&
4910 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4911 return std::make_pair(SDValue(), SDValue());
4912 if (Subtarget->is64Bit() &&
4913 Op.getValueType() == MVT::i64 &&
4914 Op.getOperand(0).getValueType() != MVT::f80)
4915 return std::make_pair(SDValue(), SDValue());
4917 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4919 MachineFunction &MF = DAG.getMachineFunction();
4920 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4921 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4922 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4924 switch (Op.getValueType().getSimpleVT()) {
4925 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4926 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4927 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4928 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4931 SDValue Chain = DAG.getEntryNode();
4932 SDValue Value = Op.getOperand(0);
4933 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4934 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4935 Chain = DAG.getStore(Chain, Value, StackSlot,
4936 PseudoSourceValue::getFixedStack(SSFI), 0);
4937 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4939 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4941 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4942 Chain = Value.getValue(1);
4943 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4944 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4947 // Build the FP_TO_INT*_IN_MEM
4948 SDValue Ops[] = { Chain, Value, StackSlot };
4949 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4951 return std::make_pair(FIST, StackSlot);
4954 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4955 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4956 SDValue FIST = Vals.first, StackSlot = Vals.second;
4957 if (FIST.getNode() == 0) return SDValue();
4960 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4963 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4964 MVT VT = Op.getValueType();
4967 EltVT = VT.getVectorElementType();
4968 std::vector<Constant*> CV;
4969 if (EltVT == MVT::f64) {
4970 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4974 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4980 Constant *C = ConstantVector::get(CV);
4981 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4982 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4983 PseudoSourceValue::getConstantPool(), 0,
4985 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4988 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4989 MVT VT = Op.getValueType();
4991 unsigned EltNum = 1;
4992 if (VT.isVector()) {
4993 EltVT = VT.getVectorElementType();
4994 EltNum = VT.getVectorNumElements();
4996 std::vector<Constant*> CV;
4997 if (EltVT == MVT::f64) {
4998 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5002 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5008 Constant *C = ConstantVector::get(CV);
5009 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5010 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5011 PseudoSourceValue::getConstantPool(), 0,
5013 if (VT.isVector()) {
5014 return DAG.getNode(ISD::BIT_CONVERT, VT,
5015 DAG.getNode(ISD::XOR, MVT::v2i64,
5016 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
5017 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
5019 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
5023 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5024 SDValue Op0 = Op.getOperand(0);
5025 SDValue Op1 = Op.getOperand(1);
5026 MVT VT = Op.getValueType();
5027 MVT SrcVT = Op1.getValueType();
5029 // If second operand is smaller, extend it first.
5030 if (SrcVT.bitsLT(VT)) {
5031 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
5034 // And if it is bigger, shrink it first.
5035 if (SrcVT.bitsGT(VT)) {
5036 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
5040 // At this point the operands and the result should have the same
5041 // type, and that won't be f80 since that is not custom lowered.
5043 // First get the sign bit of second operand.
5044 std::vector<Constant*> CV;
5045 if (SrcVT == MVT::f64) {
5046 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5047 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5049 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5050 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5051 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5052 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5054 Constant *C = ConstantVector::get(CV);
5055 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5056 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
5057 PseudoSourceValue::getConstantPool(), 0,
5059 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
5061 // Shift sign bit right or left if the two operands have different types.
5062 if (SrcVT.bitsGT(VT)) {
5063 // Op0 is MVT::f32, Op1 is MVT::f64.
5064 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
5065 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
5066 DAG.getConstant(32, MVT::i32));
5067 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
5068 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
5069 DAG.getIntPtrConstant(0));
5072 // Clear first operand sign bit.
5074 if (VT == MVT::f64) {
5075 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5076 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5078 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5079 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5080 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5081 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5083 C = ConstantVector::get(CV);
5084 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5085 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5086 PseudoSourceValue::getConstantPool(), 0,
5088 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
5090 // Or the value with the sign bit.
5091 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
5094 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5095 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5096 SDValue Op0 = Op.getOperand(0);
5097 SDValue Op1 = Op.getOperand(1);
5098 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5100 // Lower (X & (1 << N)) == 0 to BT.
5101 // Lower ((X >>u N) & 1) != 0 to BT.
5102 // Lower ((X >>s N) & 1) != 0 to BT.
5103 if (Op0.getOpcode() == ISD::AND &&
5105 Op1.getOpcode() == ISD::Constant &&
5106 Op0.getOperand(1).getOpcode() == ISD::Constant &&
5107 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5108 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5109 ConstantSDNode *CmpRHS = cast<ConstantSDNode>(Op1);
5110 SDValue AndLHS = Op0.getOperand(0);
5111 if (CmpRHS->getZExtValue() == 0 && AndRHS->getZExtValue() == 1 &&
5112 AndLHS.getOpcode() == ISD::SRL) {
5113 SDValue LHS = AndLHS.getOperand(0);
5114 SDValue RHS = AndLHS.getOperand(1);
5116 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5117 // instruction. Since the shift amount is in-range-or-undefined, we know
5118 // that doing a bittest on the i16 value is ok. We extend to i32 because
5119 // the encoding for the i16 version is larger than the i32 version.
5120 if (LHS.getValueType() == MVT::i8)
5121 LHS = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, LHS);
5123 // If the operand types disagree, extend the shift amount to match. Since
5124 // BT ignores high bits (like shifts) we can use anyextend.
5125 if (LHS.getValueType() != RHS.getValueType())
5126 RHS = DAG.getNode(ISD::ANY_EXTEND, LHS.getValueType(), RHS);
5128 SDValue BT = DAG.getNode(X86ISD::BT, MVT::i32, LHS, RHS);
5129 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5130 return DAG.getNode(X86ISD::SETCC, MVT::i8,
5131 DAG.getConstant(Cond, MVT::i8), BT);
5135 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5136 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5138 SDValue Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
5139 return DAG.getNode(X86ISD::SETCC, MVT::i8,
5140 DAG.getConstant(X86CC, MVT::i8), Cond);
5143 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5145 SDValue Op0 = Op.getOperand(0);
5146 SDValue Op1 = Op.getOperand(1);
5147 SDValue CC = Op.getOperand(2);
5148 MVT VT = Op.getValueType();
5149 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5150 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5154 MVT VT0 = Op0.getValueType();
5155 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5156 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5159 switch (SetCCOpcode) {
5162 case ISD::SETEQ: SSECC = 0; break;
5164 case ISD::SETGT: Swap = true; // Fallthrough
5166 case ISD::SETOLT: SSECC = 1; break;
5168 case ISD::SETGE: Swap = true; // Fallthrough
5170 case ISD::SETOLE: SSECC = 2; break;
5171 case ISD::SETUO: SSECC = 3; break;
5173 case ISD::SETNE: SSECC = 4; break;
5174 case ISD::SETULE: Swap = true;
5175 case ISD::SETUGE: SSECC = 5; break;
5176 case ISD::SETULT: Swap = true;
5177 case ISD::SETUGT: SSECC = 6; break;
5178 case ISD::SETO: SSECC = 7; break;
5181 std::swap(Op0, Op1);
5183 // In the two special cases we can't handle, emit two comparisons.
5185 if (SetCCOpcode == ISD::SETUEQ) {
5187 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5188 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5189 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
5191 else if (SetCCOpcode == ISD::SETONE) {
5193 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5194 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5195 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
5197 assert(0 && "Illegal FP comparison");
5199 // Handle all other FP comparisons here.
5200 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5203 // We are handling one of the integer comparisons here. Since SSE only has
5204 // GT and EQ comparisons for integer, swapping operands and multiple
5205 // operations may be required for some comparisons.
5206 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5207 bool Swap = false, Invert = false, FlipSigns = false;
5209 switch (VT.getSimpleVT()) {
5211 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5212 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5213 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5214 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5217 switch (SetCCOpcode) {
5219 case ISD::SETNE: Invert = true;
5220 case ISD::SETEQ: Opc = EQOpc; break;
5221 case ISD::SETLT: Swap = true;
5222 case ISD::SETGT: Opc = GTOpc; break;
5223 case ISD::SETGE: Swap = true;
5224 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5225 case ISD::SETULT: Swap = true;
5226 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5227 case ISD::SETUGE: Swap = true;
5228 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5231 std::swap(Op0, Op1);
5233 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5234 // bits of the inputs before performing those operations.
5236 MVT EltVT = VT.getVectorElementType();
5237 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
5238 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5239 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
5241 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
5242 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
5245 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
5247 // If the logical-not of the result is required, perform that now.
5249 MVT EltVT = VT.getVectorElementType();
5250 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
5251 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
5252 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
5254 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
5259 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5260 static bool isX86LogicalCmp(unsigned Opc) {
5261 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5264 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5265 bool addTest = true;
5266 SDValue Cond = Op.getOperand(0);
5269 if (Cond.getOpcode() == ISD::SETCC)
5270 Cond = LowerSETCC(Cond, DAG);
5272 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5273 // setting operand in place of the X86ISD::SETCC.
5274 if (Cond.getOpcode() == X86ISD::SETCC) {
5275 CC = Cond.getOperand(0);
5277 SDValue Cmp = Cond.getOperand(1);
5278 unsigned Opc = Cmp.getOpcode();
5279 MVT VT = Op.getValueType();
5281 bool IllegalFPCMov = false;
5282 if (VT.isFloatingPoint() && !VT.isVector() &&
5283 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5284 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5286 if (isX86LogicalCmp(Opc) && !IllegalFPCMov) {
5293 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5294 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5297 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5299 SmallVector<SDValue, 4> Ops;
5300 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5301 // condition is true.
5302 Ops.push_back(Op.getOperand(2));
5303 Ops.push_back(Op.getOperand(1));
5305 Ops.push_back(Cond);
5306 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5309 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5310 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5311 // from the AND / OR.
5312 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5313 Opc = Op.getOpcode();
5314 if (Opc != ISD::OR && Opc != ISD::AND)
5316 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5317 Op.getOperand(0).hasOneUse() &&
5318 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5319 Op.getOperand(1).hasOneUse());
5322 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5323 bool addTest = true;
5324 SDValue Chain = Op.getOperand(0);
5325 SDValue Cond = Op.getOperand(1);
5326 SDValue Dest = Op.getOperand(2);
5329 if (Cond.getOpcode() == ISD::SETCC)
5330 Cond = LowerSETCC(Cond, DAG);
5332 // FIXME: LowerXALUO doesn't handle these!!
5333 else if (Cond.getOpcode() == X86ISD::ADD ||
5334 Cond.getOpcode() == X86ISD::SUB ||
5335 Cond.getOpcode() == X86ISD::SMUL ||
5336 Cond.getOpcode() == X86ISD::UMUL)
5337 Cond = LowerXALUO(Cond, DAG);
5340 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5341 // setting operand in place of the X86ISD::SETCC.
5342 if (Cond.getOpcode() == X86ISD::SETCC) {
5343 CC = Cond.getOperand(0);
5345 SDValue Cmp = Cond.getOperand(1);
5346 unsigned Opc = Cmp.getOpcode();
5347 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5348 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5352 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5356 // These can only come from an arithmetic instruction with overflow,
5357 // e.g. SADDO, UADDO.
5358 Cond = Cond.getNode()->getOperand(1);
5365 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5366 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5367 unsigned Opc = Cmp.getOpcode();
5368 if (CondOpc == ISD::OR) {
5369 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5370 // two branches instead of an explicit OR instruction with a
5372 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5373 isX86LogicalCmp(Opc)) {
5374 CC = Cond.getOperand(0).getOperand(0);
5375 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5376 Chain, Dest, CC, Cmp);
5377 CC = Cond.getOperand(1).getOperand(0);
5381 } else { // ISD::AND
5382 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5383 // two branches instead of an explicit AND instruction with a
5384 // separate test. However, we only do this if this block doesn't
5385 // have a fall-through edge, because this requires an explicit
5386 // jmp when the condition is false.
5387 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5388 isX86LogicalCmp(Opc) &&
5389 Op.getNode()->hasOneUse()) {
5390 X86::CondCode CCode =
5391 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5392 CCode = X86::GetOppositeBranchCondition(CCode);
5393 CC = DAG.getConstant(CCode, MVT::i8);
5394 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5395 // Look for an unconditional branch following this conditional branch.
5396 // We need this because we need to reverse the successors in order
5397 // to implement FCMP_OEQ.
5398 if (User.getOpcode() == ISD::BR) {
5399 SDValue FalseBB = User.getOperand(1);
5401 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5402 assert(NewBR == User);
5405 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5406 Chain, Dest, CC, Cmp);
5407 X86::CondCode CCode =
5408 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5409 CCode = X86::GetOppositeBranchCondition(CCode);
5410 CC = DAG.getConstant(CCode, MVT::i8);
5420 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5421 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5423 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5424 Chain, Dest, CC, Cond);
5428 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5429 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5430 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5431 // that the guard pages used by the OS virtual memory manager are allocated in
5432 // correct sequence.
5434 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5435 SelectionDAG &DAG) {
5436 assert(Subtarget->isTargetCygMing() &&
5437 "This should be used only on Cygwin/Mingw targets");
5440 SDValue Chain = Op.getOperand(0);
5441 SDValue Size = Op.getOperand(1);
5442 // FIXME: Ensure alignment here
5446 MVT IntPtr = getPointerTy();
5447 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5449 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5451 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5452 Flag = Chain.getValue(1);
5454 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5455 SDValue Ops[] = { Chain,
5456 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5457 DAG.getRegister(X86::EAX, IntPtr),
5458 DAG.getRegister(X86StackPtr, SPTy),
5460 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5461 Flag = Chain.getValue(1);
5463 Chain = DAG.getCALLSEQ_END(Chain,
5464 DAG.getIntPtrConstant(0, true),
5465 DAG.getIntPtrConstant(0, true),
5468 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5470 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5471 return DAG.getMergeValues(Ops1, 2);
5475 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5477 SDValue Dst, SDValue Src,
5478 SDValue Size, unsigned Align,
5480 uint64_t DstSVOff) {
5481 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5483 // If not DWORD aligned or size is more than the threshold, call the library.
5484 // The libc version is likely to be faster for these cases. It can use the
5485 // address value and run time information about the CPU.
5486 if ((Align & 3) != 0 ||
5488 ConstantSize->getZExtValue() >
5489 getSubtarget()->getMaxInlineSizeThreshold()) {
5490 SDValue InFlag(0, 0);
5492 // Check to see if there is a specialized entry-point for memory zeroing.
5493 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5495 if (const char *bzeroEntry = V &&
5496 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5497 MVT IntPtr = getPointerTy();
5498 const Type *IntPtrTy = TD->getIntPtrType();
5499 TargetLowering::ArgListTy Args;
5500 TargetLowering::ArgListEntry Entry;
5502 Entry.Ty = IntPtrTy;
5503 Args.push_back(Entry);
5505 Args.push_back(Entry);
5506 std::pair<SDValue,SDValue> CallResult =
5507 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5508 CallingConv::C, false,
5509 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG);
5510 return CallResult.second;
5513 // Otherwise have the target-independent code call memset.
5517 uint64_t SizeVal = ConstantSize->getZExtValue();
5518 SDValue InFlag(0, 0);
5521 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5522 unsigned BytesLeft = 0;
5523 bool TwoRepStos = false;
5526 uint64_t Val = ValC->getZExtValue() & 255;
5528 // If the value is a constant, then we can potentially use larger sets.
5529 switch (Align & 3) {
5530 case 2: // WORD aligned
5533 Val = (Val << 8) | Val;
5535 case 0: // DWORD aligned
5538 Val = (Val << 8) | Val;
5539 Val = (Val << 16) | Val;
5540 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5543 Val = (Val << 32) | Val;
5546 default: // Byte aligned
5549 Count = DAG.getIntPtrConstant(SizeVal);
5553 if (AVT.bitsGT(MVT::i8)) {
5554 unsigned UBytes = AVT.getSizeInBits() / 8;
5555 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5556 BytesLeft = SizeVal % UBytes;
5559 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5561 InFlag = Chain.getValue(1);
5564 Count = DAG.getIntPtrConstant(SizeVal);
5565 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5566 InFlag = Chain.getValue(1);
5569 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5571 InFlag = Chain.getValue(1);
5572 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5574 InFlag = Chain.getValue(1);
5576 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5577 SmallVector<SDValue, 8> Ops;
5578 Ops.push_back(Chain);
5579 Ops.push_back(DAG.getValueType(AVT));
5580 Ops.push_back(InFlag);
5581 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5584 InFlag = Chain.getValue(1);
5586 MVT CVT = Count.getValueType();
5587 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5588 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5589 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5591 InFlag = Chain.getValue(1);
5592 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5594 Ops.push_back(Chain);
5595 Ops.push_back(DAG.getValueType(MVT::i8));
5596 Ops.push_back(InFlag);
5597 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5598 } else if (BytesLeft) {
5599 // Handle the last 1 - 7 bytes.
5600 unsigned Offset = SizeVal - BytesLeft;
5601 MVT AddrVT = Dst.getValueType();
5602 MVT SizeVT = Size.getValueType();
5604 Chain = DAG.getMemset(Chain,
5605 DAG.getNode(ISD::ADD, AddrVT, Dst,
5606 DAG.getConstant(Offset, AddrVT)),
5608 DAG.getConstant(BytesLeft, SizeVT),
5609 Align, DstSV, DstSVOff + Offset);
5612 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5617 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5618 SDValue Chain, SDValue Dst, SDValue Src,
5619 SDValue Size, unsigned Align,
5621 const Value *DstSV, uint64_t DstSVOff,
5622 const Value *SrcSV, uint64_t SrcSVOff) {
5623 // This requires the copy size to be a constant, preferrably
5624 // within a subtarget-specific limit.
5625 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5628 uint64_t SizeVal = ConstantSize->getZExtValue();
5629 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5632 /// If not DWORD aligned, call the library.
5633 if ((Align & 3) != 0)
5638 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5641 unsigned UBytes = AVT.getSizeInBits() / 8;
5642 unsigned CountVal = SizeVal / UBytes;
5643 SDValue Count = DAG.getIntPtrConstant(CountVal);
5644 unsigned BytesLeft = SizeVal % UBytes;
5646 SDValue InFlag(0, 0);
5647 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5649 InFlag = Chain.getValue(1);
5650 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5652 InFlag = Chain.getValue(1);
5653 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5655 InFlag = Chain.getValue(1);
5657 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5658 SmallVector<SDValue, 8> Ops;
5659 Ops.push_back(Chain);
5660 Ops.push_back(DAG.getValueType(AVT));
5661 Ops.push_back(InFlag);
5662 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5664 SmallVector<SDValue, 4> Results;
5665 Results.push_back(RepMovs);
5667 // Handle the last 1 - 7 bytes.
5668 unsigned Offset = SizeVal - BytesLeft;
5669 MVT DstVT = Dst.getValueType();
5670 MVT SrcVT = Src.getValueType();
5671 MVT SizeVT = Size.getValueType();
5672 Results.push_back(DAG.getMemcpy(Chain,
5673 DAG.getNode(ISD::ADD, DstVT, Dst,
5674 DAG.getConstant(Offset, DstVT)),
5675 DAG.getNode(ISD::ADD, SrcVT, Src,
5676 DAG.getConstant(Offset, SrcVT)),
5677 DAG.getConstant(BytesLeft, SizeVT),
5678 Align, AlwaysInline,
5679 DstSV, DstSVOff + Offset,
5680 SrcSV, SrcSVOff + Offset));
5683 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5686 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5687 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5689 if (!Subtarget->is64Bit()) {
5690 // vastart just stores the address of the VarArgsFrameIndex slot into the
5691 // memory location argument.
5692 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5693 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5697 // gp_offset (0 - 6 * 8)
5698 // fp_offset (48 - 48 + 8 * 16)
5699 // overflow_arg_area (point to parameters coming in memory).
5701 SmallVector<SDValue, 8> MemOps;
5702 SDValue FIN = Op.getOperand(1);
5704 SDValue Store = DAG.getStore(Op.getOperand(0),
5705 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5707 MemOps.push_back(Store);
5710 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5711 Store = DAG.getStore(Op.getOperand(0),
5712 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5714 MemOps.push_back(Store);
5716 // Store ptr to overflow_arg_area
5717 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5718 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5719 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5720 MemOps.push_back(Store);
5722 // Store ptr to reg_save_area.
5723 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5724 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5725 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5726 MemOps.push_back(Store);
5727 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5730 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5731 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5732 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5733 SDValue Chain = Op.getOperand(0);
5734 SDValue SrcPtr = Op.getOperand(1);
5735 SDValue SrcSV = Op.getOperand(2);
5737 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5742 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5743 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5744 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5745 SDValue Chain = Op.getOperand(0);
5746 SDValue DstPtr = Op.getOperand(1);
5747 SDValue SrcPtr = Op.getOperand(2);
5748 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5749 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5751 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5752 DAG.getIntPtrConstant(24), 8, false,
5753 DstSV, 0, SrcSV, 0);
5757 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5758 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5760 default: return SDValue(); // Don't custom lower most intrinsics.
5761 // Comparison intrinsics.
5762 case Intrinsic::x86_sse_comieq_ss:
5763 case Intrinsic::x86_sse_comilt_ss:
5764 case Intrinsic::x86_sse_comile_ss:
5765 case Intrinsic::x86_sse_comigt_ss:
5766 case Intrinsic::x86_sse_comige_ss:
5767 case Intrinsic::x86_sse_comineq_ss:
5768 case Intrinsic::x86_sse_ucomieq_ss:
5769 case Intrinsic::x86_sse_ucomilt_ss:
5770 case Intrinsic::x86_sse_ucomile_ss:
5771 case Intrinsic::x86_sse_ucomigt_ss:
5772 case Intrinsic::x86_sse_ucomige_ss:
5773 case Intrinsic::x86_sse_ucomineq_ss:
5774 case Intrinsic::x86_sse2_comieq_sd:
5775 case Intrinsic::x86_sse2_comilt_sd:
5776 case Intrinsic::x86_sse2_comile_sd:
5777 case Intrinsic::x86_sse2_comigt_sd:
5778 case Intrinsic::x86_sse2_comige_sd:
5779 case Intrinsic::x86_sse2_comineq_sd:
5780 case Intrinsic::x86_sse2_ucomieq_sd:
5781 case Intrinsic::x86_sse2_ucomilt_sd:
5782 case Intrinsic::x86_sse2_ucomile_sd:
5783 case Intrinsic::x86_sse2_ucomigt_sd:
5784 case Intrinsic::x86_sse2_ucomige_sd:
5785 case Intrinsic::x86_sse2_ucomineq_sd: {
5787 ISD::CondCode CC = ISD::SETCC_INVALID;
5790 case Intrinsic::x86_sse_comieq_ss:
5791 case Intrinsic::x86_sse2_comieq_sd:
5795 case Intrinsic::x86_sse_comilt_ss:
5796 case Intrinsic::x86_sse2_comilt_sd:
5800 case Intrinsic::x86_sse_comile_ss:
5801 case Intrinsic::x86_sse2_comile_sd:
5805 case Intrinsic::x86_sse_comigt_ss:
5806 case Intrinsic::x86_sse2_comigt_sd:
5810 case Intrinsic::x86_sse_comige_ss:
5811 case Intrinsic::x86_sse2_comige_sd:
5815 case Intrinsic::x86_sse_comineq_ss:
5816 case Intrinsic::x86_sse2_comineq_sd:
5820 case Intrinsic::x86_sse_ucomieq_ss:
5821 case Intrinsic::x86_sse2_ucomieq_sd:
5822 Opc = X86ISD::UCOMI;
5825 case Intrinsic::x86_sse_ucomilt_ss:
5826 case Intrinsic::x86_sse2_ucomilt_sd:
5827 Opc = X86ISD::UCOMI;
5830 case Intrinsic::x86_sse_ucomile_ss:
5831 case Intrinsic::x86_sse2_ucomile_sd:
5832 Opc = X86ISD::UCOMI;
5835 case Intrinsic::x86_sse_ucomigt_ss:
5836 case Intrinsic::x86_sse2_ucomigt_sd:
5837 Opc = X86ISD::UCOMI;
5840 case Intrinsic::x86_sse_ucomige_ss:
5841 case Intrinsic::x86_sse2_ucomige_sd:
5842 Opc = X86ISD::UCOMI;
5845 case Intrinsic::x86_sse_ucomineq_ss:
5846 case Intrinsic::x86_sse2_ucomineq_sd:
5847 Opc = X86ISD::UCOMI;
5852 SDValue LHS = Op.getOperand(1);
5853 SDValue RHS = Op.getOperand(2);
5854 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5855 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5856 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5857 DAG.getConstant(X86CC, MVT::i8), Cond);
5858 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5861 // Fix vector shift instructions where the last operand is a non-immediate
5863 case Intrinsic::x86_sse2_pslli_w:
5864 case Intrinsic::x86_sse2_pslli_d:
5865 case Intrinsic::x86_sse2_pslli_q:
5866 case Intrinsic::x86_sse2_psrli_w:
5867 case Intrinsic::x86_sse2_psrli_d:
5868 case Intrinsic::x86_sse2_psrli_q:
5869 case Intrinsic::x86_sse2_psrai_w:
5870 case Intrinsic::x86_sse2_psrai_d:
5871 case Intrinsic::x86_mmx_pslli_w:
5872 case Intrinsic::x86_mmx_pslli_d:
5873 case Intrinsic::x86_mmx_pslli_q:
5874 case Intrinsic::x86_mmx_psrli_w:
5875 case Intrinsic::x86_mmx_psrli_d:
5876 case Intrinsic::x86_mmx_psrli_q:
5877 case Intrinsic::x86_mmx_psrai_w:
5878 case Intrinsic::x86_mmx_psrai_d: {
5879 SDValue ShAmt = Op.getOperand(2);
5880 if (isa<ConstantSDNode>(ShAmt))
5883 unsigned NewIntNo = 0;
5884 MVT ShAmtVT = MVT::v4i32;
5886 case Intrinsic::x86_sse2_pslli_w:
5887 NewIntNo = Intrinsic::x86_sse2_psll_w;
5889 case Intrinsic::x86_sse2_pslli_d:
5890 NewIntNo = Intrinsic::x86_sse2_psll_d;
5892 case Intrinsic::x86_sse2_pslli_q:
5893 NewIntNo = Intrinsic::x86_sse2_psll_q;
5895 case Intrinsic::x86_sse2_psrli_w:
5896 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5898 case Intrinsic::x86_sse2_psrli_d:
5899 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5901 case Intrinsic::x86_sse2_psrli_q:
5902 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5904 case Intrinsic::x86_sse2_psrai_w:
5905 NewIntNo = Intrinsic::x86_sse2_psra_w;
5907 case Intrinsic::x86_sse2_psrai_d:
5908 NewIntNo = Intrinsic::x86_sse2_psra_d;
5911 ShAmtVT = MVT::v2i32;
5913 case Intrinsic::x86_mmx_pslli_w:
5914 NewIntNo = Intrinsic::x86_mmx_psll_w;
5916 case Intrinsic::x86_mmx_pslli_d:
5917 NewIntNo = Intrinsic::x86_mmx_psll_d;
5919 case Intrinsic::x86_mmx_pslli_q:
5920 NewIntNo = Intrinsic::x86_mmx_psll_q;
5922 case Intrinsic::x86_mmx_psrli_w:
5923 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5925 case Intrinsic::x86_mmx_psrli_d:
5926 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5928 case Intrinsic::x86_mmx_psrli_q:
5929 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5931 case Intrinsic::x86_mmx_psrai_w:
5932 NewIntNo = Intrinsic::x86_mmx_psra_w;
5934 case Intrinsic::x86_mmx_psrai_d:
5935 NewIntNo = Intrinsic::x86_mmx_psra_d;
5937 default: abort(); // Can't reach here.
5942 MVT VT = Op.getValueType();
5943 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5944 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5945 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5946 DAG.getConstant(NewIntNo, MVT::i32),
5947 Op.getOperand(1), ShAmt);
5952 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5953 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5956 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5958 DAG.getConstant(TD->getPointerSize(),
5959 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
5960 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(),
5961 DAG.getNode(ISD::ADD, getPointerTy(), FrameAddr, Offset),
5965 // Just load the return address.
5966 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5967 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5970 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5971 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5972 MFI->setFrameAddressIsTaken(true);
5973 MVT VT = Op.getValueType();
5974 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5975 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
5976 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
5978 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
5982 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5983 SelectionDAG &DAG) {
5984 return DAG.getIntPtrConstant(2*TD->getPointerSize());
5987 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5989 MachineFunction &MF = DAG.getMachineFunction();
5990 SDValue Chain = Op.getOperand(0);
5991 SDValue Offset = Op.getOperand(1);
5992 SDValue Handler = Op.getOperand(2);
5994 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5996 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5998 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5999 DAG.getIntPtrConstant(-TD->getPointerSize()));
6000 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
6001 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
6002 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
6003 MF.getRegInfo().addLiveOut(StoreAddrReg);
6005 return DAG.getNode(X86ISD::EH_RETURN,
6007 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6010 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6011 SelectionDAG &DAG) {
6012 SDValue Root = Op.getOperand(0);
6013 SDValue Trmp = Op.getOperand(1); // trampoline
6014 SDValue FPtr = Op.getOperand(2); // nested function
6015 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6017 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6019 const X86InstrInfo *TII =
6020 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6022 if (Subtarget->is64Bit()) {
6023 SDValue OutChains[6];
6025 // Large code-model.
6027 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6028 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6030 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6031 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6033 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6035 // Load the pointer to the nested function into R11.
6036 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6037 SDValue Addr = Trmp;
6038 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6041 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
6042 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
6044 // Load the 'nest' parameter value into R10.
6045 // R10 is specified in X86CallingConv.td
6046 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6047 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
6048 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6051 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
6052 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
6054 // Jump to the nested function.
6055 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6056 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
6057 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6060 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6061 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
6062 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
6066 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
6067 return DAG.getMergeValues(Ops, 2);
6069 const Function *Func =
6070 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6071 unsigned CC = Func->getCallingConv();
6076 assert(0 && "Unsupported calling convention");
6077 case CallingConv::C:
6078 case CallingConv::X86_StdCall: {
6079 // Pass 'nest' parameter in ECX.
6080 // Must be kept in sync with X86CallingConv.td
6083 // Check that ECX wasn't needed by an 'inreg' parameter.
6084 const FunctionType *FTy = Func->getFunctionType();
6085 const AttrListPtr &Attrs = Func->getAttributes();
6087 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6088 unsigned InRegCount = 0;
6091 for (FunctionType::param_iterator I = FTy->param_begin(),
6092 E = FTy->param_end(); I != E; ++I, ++Idx)
6093 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6094 // FIXME: should only count parameters that are lowered to integers.
6095 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6097 if (InRegCount > 2) {
6098 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6104 case CallingConv::X86_FastCall:
6105 case CallingConv::Fast:
6106 // Pass 'nest' parameter in EAX.
6107 // Must be kept in sync with X86CallingConv.td
6112 SDValue OutChains[4];
6115 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
6116 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
6118 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6119 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6120 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6123 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
6124 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
6126 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6127 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
6128 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
6129 TrmpAddr, 5, false, 1);
6131 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
6132 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
6135 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
6136 return DAG.getMergeValues(Ops, 2);
6140 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6142 The rounding mode is in bits 11:10 of FPSR, and has the following
6149 FLT_ROUNDS, on the other hand, expects the following:
6156 To perform the conversion, we do:
6157 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6160 MachineFunction &MF = DAG.getMachineFunction();
6161 const TargetMachine &TM = MF.getTarget();
6162 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6163 unsigned StackAlignment = TFI.getStackAlignment();
6164 MVT VT = Op.getValueType();
6166 // Save FP Control Word to stack slot
6167 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6168 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6170 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
6171 DAG.getEntryNode(), StackSlot);
6173 // Load FP Control Word from stack slot
6174 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
6176 // Transform as necessary
6178 DAG.getNode(ISD::SRL, MVT::i16,
6179 DAG.getNode(ISD::AND, MVT::i16,
6180 CWD, DAG.getConstant(0x800, MVT::i16)),
6181 DAG.getConstant(11, MVT::i8));
6183 DAG.getNode(ISD::SRL, MVT::i16,
6184 DAG.getNode(ISD::AND, MVT::i16,
6185 CWD, DAG.getConstant(0x400, MVT::i16)),
6186 DAG.getConstant(9, MVT::i8));
6189 DAG.getNode(ISD::AND, MVT::i16,
6190 DAG.getNode(ISD::ADD, MVT::i16,
6191 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
6192 DAG.getConstant(1, MVT::i16)),
6193 DAG.getConstant(3, MVT::i16));
6196 return DAG.getNode((VT.getSizeInBits() < 16 ?
6197 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6200 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6201 MVT VT = Op.getValueType();
6203 unsigned NumBits = VT.getSizeInBits();
6205 Op = Op.getOperand(0);
6206 if (VT == MVT::i8) {
6207 // Zero extend to i32 since there is not an i8 bsr.
6209 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6212 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6213 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6214 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
6216 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6217 SmallVector<SDValue, 4> Ops;
6219 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6220 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6221 Ops.push_back(Op.getValue(1));
6222 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6224 // Finally xor with NumBits-1.
6225 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6228 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6232 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6233 MVT VT = Op.getValueType();
6235 unsigned NumBits = VT.getSizeInBits();
6237 Op = Op.getOperand(0);
6238 if (VT == MVT::i8) {
6240 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6243 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6244 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6245 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
6247 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6248 SmallVector<SDValue, 4> Ops;
6250 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6251 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6252 Ops.push_back(Op.getValue(1));
6253 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6256 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6260 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6261 MVT VT = Op.getValueType();
6262 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6264 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6265 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6266 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6267 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6268 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6270 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6271 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6272 // return AloBlo + AloBhi + AhiBlo;
6274 SDValue A = Op.getOperand(0);
6275 SDValue B = Op.getOperand(1);
6277 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6278 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6279 A, DAG.getConstant(32, MVT::i32));
6280 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6281 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6282 B, DAG.getConstant(32, MVT::i32));
6283 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6284 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6286 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6287 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6289 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6290 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6292 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6293 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6294 AloBhi, DAG.getConstant(32, MVT::i32));
6295 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6296 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6297 AhiBlo, DAG.getConstant(32, MVT::i32));
6298 SDValue Res = DAG.getNode(ISD::ADD, VT, AloBlo, AloBhi);
6299 Res = DAG.getNode(ISD::ADD, VT, Res, AhiBlo);
6304 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6305 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6306 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6307 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6308 // has only one use.
6309 SDNode *N = Op.getNode();
6310 SDValue LHS = N->getOperand(0);
6311 SDValue RHS = N->getOperand(1);
6312 unsigned BaseOp = 0;
6315 switch (Op.getOpcode()) {
6316 default: assert(0 && "Unknown ovf instruction!");
6318 BaseOp = X86ISD::ADD;
6322 BaseOp = X86ISD::ADD;
6326 BaseOp = X86ISD::SUB;
6330 BaseOp = X86ISD::SUB;
6334 BaseOp = X86ISD::SMUL;
6338 BaseOp = X86ISD::UMUL;
6343 // Also sets EFLAGS.
6344 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6345 SDValue Sum = DAG.getNode(BaseOp, VTs, LHS, RHS);
6348 DAG.getNode(X86ISD::SETCC, N->getValueType(1),
6349 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6351 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6355 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6356 MVT T = Op.getValueType();
6359 switch(T.getSimpleVT()) {
6361 assert(false && "Invalid value type!");
6362 case MVT::i8: Reg = X86::AL; size = 1; break;
6363 case MVT::i16: Reg = X86::AX; size = 2; break;
6364 case MVT::i32: Reg = X86::EAX; size = 4; break;
6366 assert(Subtarget->is64Bit() && "Node not type legal!");
6367 Reg = X86::RAX; size = 8;
6370 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6371 Op.getOperand(2), SDValue());
6372 SDValue Ops[] = { cpIn.getValue(0),
6375 DAG.getTargetConstant(size, MVT::i8),
6377 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6378 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
6380 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6384 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6385 SelectionDAG &DAG) {
6386 assert(Subtarget->is64Bit() && "Result not type legalized?");
6387 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6388 SDValue TheChain = Op.getOperand(0);
6389 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6390 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
6391 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX, MVT::i64,
6393 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
6394 DAG.getConstant(32, MVT::i8));
6396 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp),
6399 return DAG.getMergeValues(Ops, 2);
6402 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6403 SDNode *Node = Op.getNode();
6404 MVT T = Node->getValueType(0);
6405 SDValue negOp = DAG.getNode(ISD::SUB, T,
6406 DAG.getConstant(0, T), Node->getOperand(2));
6407 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD,
6408 cast<AtomicSDNode>(Node)->getMemoryVT(),
6409 Node->getOperand(0),
6410 Node->getOperand(1), negOp,
6411 cast<AtomicSDNode>(Node)->getSrcValue(),
6412 cast<AtomicSDNode>(Node)->getAlignment());
6415 /// LowerOperation - Provide custom lowering hooks for some operations.
6417 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6418 switch (Op.getOpcode()) {
6419 default: assert(0 && "Should not custom lower this!");
6420 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6421 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6422 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6423 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6424 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6425 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6426 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6427 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6428 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6429 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6430 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6431 case ISD::SHL_PARTS:
6432 case ISD::SRA_PARTS:
6433 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6434 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6435 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6436 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6437 case ISD::FABS: return LowerFABS(Op, DAG);
6438 case ISD::FNEG: return LowerFNEG(Op, DAG);
6439 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6440 case ISD::SETCC: return LowerSETCC(Op, DAG);
6441 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6442 case ISD::SELECT: return LowerSELECT(Op, DAG);
6443 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6444 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6445 case ISD::CALL: return LowerCALL(Op, DAG);
6446 case ISD::RET: return LowerRET(Op, DAG);
6447 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6448 case ISD::VASTART: return LowerVASTART(Op, DAG);
6449 case ISD::VAARG: return LowerVAARG(Op, DAG);
6450 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6451 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6452 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6453 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6454 case ISD::FRAME_TO_ARGS_OFFSET:
6455 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6456 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6457 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6458 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6459 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6460 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6461 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6462 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6468 case ISD::UMULO: return LowerXALUO(Op, DAG);
6469 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6473 void X86TargetLowering::
6474 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6475 SelectionDAG &DAG, unsigned NewOp) {
6476 MVT T = Node->getValueType(0);
6477 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6479 SDValue Chain = Node->getOperand(0);
6480 SDValue In1 = Node->getOperand(1);
6481 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6482 Node->getOperand(2), DAG.getIntPtrConstant(0));
6483 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6484 Node->getOperand(2), DAG.getIntPtrConstant(1));
6485 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6486 // have a MemOperand. Pass the info through as a normal operand.
6487 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6488 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6489 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6490 SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6491 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6492 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6493 Results.push_back(Result.getValue(2));
6496 /// ReplaceNodeResults - Replace a node with an illegal result type
6497 /// with a new node built out of custom code.
6498 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6499 SmallVectorImpl<SDValue>&Results,
6500 SelectionDAG &DAG) {
6501 switch (N->getOpcode()) {
6503 assert(false && "Do not know how to custom type legalize this operation!");
6505 case ISD::FP_TO_SINT: {
6506 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6507 SDValue FIST = Vals.first, StackSlot = Vals.second;
6508 if (FIST.getNode() != 0) {
6509 MVT VT = N->getValueType(0);
6510 // Return a load from the stack slot.
6511 Results.push_back(DAG.getLoad(VT, FIST, StackSlot, NULL, 0));
6515 case ISD::READCYCLECOUNTER: {
6516 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6517 SDValue TheChain = N->getOperand(0);
6518 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6519 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
6520 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX, MVT::i32,
6522 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6523 SDValue Ops[] = { eax, edx };
6524 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2));
6525 Results.push_back(edx.getValue(1));
6528 case ISD::ATOMIC_CMP_SWAP: {
6529 MVT T = N->getValueType(0);
6530 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6531 SDValue cpInL, cpInH;
6532 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6533 DAG.getConstant(0, MVT::i32));
6534 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6535 DAG.getConstant(1, MVT::i32));
6536 cpInL = DAG.getCopyToReg(N->getOperand(0), X86::EAX, cpInL, SDValue());
6537 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX, cpInH,
6539 SDValue swapInL, swapInH;
6540 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6541 DAG.getConstant(0, MVT::i32));
6542 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6543 DAG.getConstant(1, MVT::i32));
6544 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX, swapInL,
6546 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX, swapInH,
6547 swapInL.getValue(1));
6548 SDValue Ops[] = { swapInH.getValue(0),
6550 swapInH.getValue(1) };
6551 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6552 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6553 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6554 Result.getValue(1));
6555 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6556 cpOutL.getValue(2));
6557 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6558 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6559 Results.push_back(cpOutH.getValue(1));
6562 case ISD::ATOMIC_LOAD_ADD:
6563 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6565 case ISD::ATOMIC_LOAD_AND:
6566 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6568 case ISD::ATOMIC_LOAD_NAND:
6569 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6571 case ISD::ATOMIC_LOAD_OR:
6572 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6574 case ISD::ATOMIC_LOAD_SUB:
6575 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6577 case ISD::ATOMIC_LOAD_XOR:
6578 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6580 case ISD::ATOMIC_SWAP:
6581 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6586 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6588 default: return NULL;
6589 case X86ISD::BSF: return "X86ISD::BSF";
6590 case X86ISD::BSR: return "X86ISD::BSR";
6591 case X86ISD::SHLD: return "X86ISD::SHLD";
6592 case X86ISD::SHRD: return "X86ISD::SHRD";
6593 case X86ISD::FAND: return "X86ISD::FAND";
6594 case X86ISD::FOR: return "X86ISD::FOR";
6595 case X86ISD::FXOR: return "X86ISD::FXOR";
6596 case X86ISD::FSRL: return "X86ISD::FSRL";
6597 case X86ISD::FILD: return "X86ISD::FILD";
6598 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6599 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6600 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6601 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6602 case X86ISD::FLD: return "X86ISD::FLD";
6603 case X86ISD::FST: return "X86ISD::FST";
6604 case X86ISD::CALL: return "X86ISD::CALL";
6605 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6606 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6607 case X86ISD::BT: return "X86ISD::BT";
6608 case X86ISD::CMP: return "X86ISD::CMP";
6609 case X86ISD::COMI: return "X86ISD::COMI";
6610 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6611 case X86ISD::SETCC: return "X86ISD::SETCC";
6612 case X86ISD::CMOV: return "X86ISD::CMOV";
6613 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6614 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6615 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6616 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6617 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6618 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6619 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6620 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6621 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6622 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6623 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6624 case X86ISD::FMAX: return "X86ISD::FMAX";
6625 case X86ISD::FMIN: return "X86ISD::FMIN";
6626 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6627 case X86ISD::FRCP: return "X86ISD::FRCP";
6628 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6629 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6630 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6631 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6632 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6633 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6634 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6635 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6636 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6637 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6638 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6639 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6640 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6641 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6642 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6643 case X86ISD::VSHL: return "X86ISD::VSHL";
6644 case X86ISD::VSRL: return "X86ISD::VSRL";
6645 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6646 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6647 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6648 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6649 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6650 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6651 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6652 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6653 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6654 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6655 case X86ISD::ADD: return "X86ISD::ADD";
6656 case X86ISD::SUB: return "X86ISD::SUB";
6657 case X86ISD::SMUL: return "X86ISD::SMUL";
6658 case X86ISD::UMUL: return "X86ISD::UMUL";
6662 // isLegalAddressingMode - Return true if the addressing mode represented
6663 // by AM is legal for this target, for a load/store of the specified type.
6664 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6665 const Type *Ty) const {
6666 // X86 supports extremely general addressing modes.
6668 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6669 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6673 // We can only fold this if we don't need an extra load.
6674 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6676 // If BaseGV requires a register, we cannot also have a BaseReg.
6677 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6681 // X86-64 only supports addr of globals in small code model.
6682 if (Subtarget->is64Bit()) {
6683 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6685 // If lower 4G is not available, then we must use rip-relative addressing.
6686 if (AM.BaseOffs || AM.Scale > 1)
6697 // These scales always work.
6702 // These scales are formed with basereg+scalereg. Only accept if there is
6707 default: // Other stuff never works.
6715 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6716 if (!Ty1->isInteger() || !Ty2->isInteger())
6718 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6719 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6720 if (NumBits1 <= NumBits2)
6722 return Subtarget->is64Bit() || NumBits1 < 64;
6725 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6726 if (!VT1.isInteger() || !VT2.isInteger())
6728 unsigned NumBits1 = VT1.getSizeInBits();
6729 unsigned NumBits2 = VT2.getSizeInBits();
6730 if (NumBits1 <= NumBits2)
6732 return Subtarget->is64Bit() || NumBits1 < 64;
6735 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6736 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6737 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6738 /// are assumed to be legal.
6740 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6741 // Only do shuffles on 128-bit vector types for now.
6742 if (VT.getSizeInBits() == 64) return false;
6743 return (Mask.getNode()->getNumOperands() <= 4 ||
6744 isIdentityMask(Mask.getNode()) ||
6745 isIdentityMask(Mask.getNode(), true) ||
6746 isSplatMask(Mask.getNode()) ||
6747 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6748 X86::isUNPCKLMask(Mask.getNode()) ||
6749 X86::isUNPCKHMask(Mask.getNode()) ||
6750 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6751 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6755 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6756 MVT EVT, SelectionDAG &DAG) const {
6757 unsigned NumElts = BVOps.size();
6758 // Only do shuffles on 128-bit vector types for now.
6759 if (EVT.getSizeInBits() * NumElts == 64) return false;
6760 if (NumElts == 2) return true;
6762 return (isMOVLMask(&BVOps[0], 4) ||
6763 isCommutedMOVL(&BVOps[0], 4, true) ||
6764 isSHUFPMask(&BVOps[0], 4) ||
6765 isCommutedSHUFP(&BVOps[0], 4));
6770 //===----------------------------------------------------------------------===//
6771 // X86 Scheduler Hooks
6772 //===----------------------------------------------------------------------===//
6774 // private utility function
6776 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6777 MachineBasicBlock *MBB,
6785 TargetRegisterClass *RC,
6787 // For the atomic bitwise operator, we generate
6790 // ld t1 = [bitinstr.addr]
6791 // op t2 = t1, [bitinstr.val]
6793 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6795 // fallthrough -->nextMBB
6796 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6797 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6798 MachineFunction::iterator MBBIter = MBB;
6801 /// First build the CFG
6802 MachineFunction *F = MBB->getParent();
6803 MachineBasicBlock *thisMBB = MBB;
6804 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6805 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6806 F->insert(MBBIter, newMBB);
6807 F->insert(MBBIter, nextMBB);
6809 // Move all successors to thisMBB to nextMBB
6810 nextMBB->transferSuccessors(thisMBB);
6812 // Update thisMBB to fall through to newMBB
6813 thisMBB->addSuccessor(newMBB);
6815 // newMBB jumps to itself and fall through to nextMBB
6816 newMBB->addSuccessor(nextMBB);
6817 newMBB->addSuccessor(newMBB);
6819 // Insert instructions into newMBB based on incoming instruction
6820 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6821 MachineOperand& destOper = bInstr->getOperand(0);
6822 MachineOperand* argOpers[6];
6823 int numArgs = bInstr->getNumOperands() - 1;
6824 for (int i=0; i < numArgs; ++i)
6825 argOpers[i] = &bInstr->getOperand(i+1);
6827 // x86 address has 4 operands: base, index, scale, and displacement
6828 int lastAddrIndx = 3; // [0,3]
6831 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6832 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6833 for (int i=0; i <= lastAddrIndx; ++i)
6834 (*MIB).addOperand(*argOpers[i]);
6836 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6838 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6843 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6844 assert((argOpers[valArgIndx]->isReg() ||
6845 argOpers[valArgIndx]->isImm()) &&
6847 if (argOpers[valArgIndx]->isReg())
6848 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6850 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6852 (*MIB).addOperand(*argOpers[valArgIndx]);
6854 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6857 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6858 for (int i=0; i <= lastAddrIndx; ++i)
6859 (*MIB).addOperand(*argOpers[i]);
6861 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6862 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6864 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6868 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6870 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6874 // private utility function: 64 bit atomics on 32 bit host.
6876 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
6877 MachineBasicBlock *MBB,
6883 // For the atomic bitwise operator, we generate
6884 // thisMBB (instructions are in pairs, except cmpxchg8b)
6885 // ld t1,t2 = [bitinstr.addr]
6887 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
6888 // op t5, t6 <- out1, out2, [bitinstr.val]
6889 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
6890 // mov ECX, EBX <- t5, t6
6891 // mov EAX, EDX <- t1, t2
6892 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
6893 // mov t3, t4 <- EAX, EDX
6895 // result in out1, out2
6896 // fallthrough -->nextMBB
6898 const TargetRegisterClass *RC = X86::GR32RegisterClass;
6899 const unsigned LoadOpc = X86::MOV32rm;
6900 const unsigned copyOpc = X86::MOV32rr;
6901 const unsigned NotOpc = X86::NOT32r;
6902 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6903 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6904 MachineFunction::iterator MBBIter = MBB;
6907 /// First build the CFG
6908 MachineFunction *F = MBB->getParent();
6909 MachineBasicBlock *thisMBB = MBB;
6910 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6911 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6912 F->insert(MBBIter, newMBB);
6913 F->insert(MBBIter, nextMBB);
6915 // Move all successors to thisMBB to nextMBB
6916 nextMBB->transferSuccessors(thisMBB);
6918 // Update thisMBB to fall through to newMBB
6919 thisMBB->addSuccessor(newMBB);
6921 // newMBB jumps to itself and fall through to nextMBB
6922 newMBB->addSuccessor(nextMBB);
6923 newMBB->addSuccessor(newMBB);
6925 // Insert instructions into newMBB based on incoming instruction
6926 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
6927 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
6928 MachineOperand& dest1Oper = bInstr->getOperand(0);
6929 MachineOperand& dest2Oper = bInstr->getOperand(1);
6930 MachineOperand* argOpers[6];
6931 for (int i=0; i < 6; ++i)
6932 argOpers[i] = &bInstr->getOperand(i+2);
6934 // x86 address has 4 operands: base, index, scale, and displacement
6935 int lastAddrIndx = 3; // [0,3]
6937 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6938 MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
6939 for (int i=0; i <= lastAddrIndx; ++i)
6940 (*MIB).addOperand(*argOpers[i]);
6941 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6942 MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
6943 // add 4 to displacement.
6944 for (int i=0; i <= lastAddrIndx-1; ++i)
6945 (*MIB).addOperand(*argOpers[i]);
6946 MachineOperand newOp3 = *(argOpers[3]);
6948 newOp3.setImm(newOp3.getImm()+4);
6950 newOp3.setOffset(newOp3.getOffset()+4);
6951 (*MIB).addOperand(newOp3);
6953 // t3/4 are defined later, at the bottom of the loop
6954 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
6955 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
6956 BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
6957 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
6958 BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
6959 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
6961 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
6962 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
6964 MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
6965 MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
6971 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
6973 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
6974 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
6975 if (argOpers[4]->isReg())
6976 MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
6978 MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
6979 if (regOpcL != X86::MOV32rr)
6981 (*MIB).addOperand(*argOpers[4]);
6982 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
6983 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
6984 if (argOpers[5]->isReg())
6985 MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
6987 MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
6988 if (regOpcH != X86::MOV32rr)
6990 (*MIB).addOperand(*argOpers[5]);
6992 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
6994 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
6997 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
6999 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
7002 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
7003 for (int i=0; i <= lastAddrIndx; ++i)
7004 (*MIB).addOperand(*argOpers[i]);
7006 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7007 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7009 MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
7010 MIB.addReg(X86::EAX);
7011 MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
7012 MIB.addReg(X86::EDX);
7015 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7017 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7021 // private utility function
7023 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7024 MachineBasicBlock *MBB,
7026 // For the atomic min/max operator, we generate
7029 // ld t1 = [min/max.addr]
7030 // mov t2 = [min/max.val]
7032 // cmov[cond] t2 = t1
7034 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7036 // fallthrough -->nextMBB
7038 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7039 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7040 MachineFunction::iterator MBBIter = MBB;
7043 /// First build the CFG
7044 MachineFunction *F = MBB->getParent();
7045 MachineBasicBlock *thisMBB = MBB;
7046 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7047 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7048 F->insert(MBBIter, newMBB);
7049 F->insert(MBBIter, nextMBB);
7051 // Move all successors to thisMBB to nextMBB
7052 nextMBB->transferSuccessors(thisMBB);
7054 // Update thisMBB to fall through to newMBB
7055 thisMBB->addSuccessor(newMBB);
7057 // newMBB jumps to newMBB and fall through to nextMBB
7058 newMBB->addSuccessor(nextMBB);
7059 newMBB->addSuccessor(newMBB);
7061 // Insert instructions into newMBB based on incoming instruction
7062 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7063 MachineOperand& destOper = mInstr->getOperand(0);
7064 MachineOperand* argOpers[6];
7065 int numArgs = mInstr->getNumOperands() - 1;
7066 for (int i=0; i < numArgs; ++i)
7067 argOpers[i] = &mInstr->getOperand(i+1);
7069 // x86 address has 4 operands: base, index, scale, and displacement
7070 int lastAddrIndx = 3; // [0,3]
7073 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7074 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
7075 for (int i=0; i <= lastAddrIndx; ++i)
7076 (*MIB).addOperand(*argOpers[i]);
7078 // We only support register and immediate values
7079 assert((argOpers[valArgIndx]->isReg() ||
7080 argOpers[valArgIndx]->isImm()) &&
7083 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7084 if (argOpers[valArgIndx]->isReg())
7085 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7087 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7088 (*MIB).addOperand(*argOpers[valArgIndx]);
7090 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
7093 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
7098 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7099 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
7103 // Cmp and exchange if none has modified the memory location
7104 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
7105 for (int i=0; i <= lastAddrIndx; ++i)
7106 (*MIB).addOperand(*argOpers[i]);
7108 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7109 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7111 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
7112 MIB.addReg(X86::EAX);
7115 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7117 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7123 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7124 MachineBasicBlock *BB) {
7125 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7126 switch (MI->getOpcode()) {
7127 default: assert(false && "Unexpected instr type to insert");
7128 case X86::CMOV_V1I64:
7129 case X86::CMOV_FR32:
7130 case X86::CMOV_FR64:
7131 case X86::CMOV_V4F32:
7132 case X86::CMOV_V2F64:
7133 case X86::CMOV_V2I64: {
7134 // To "insert" a SELECT_CC instruction, we actually have to insert the
7135 // diamond control-flow pattern. The incoming instruction knows the
7136 // destination vreg to set, the condition code register to branch on, the
7137 // true/false values to select between, and a branch opcode to use.
7138 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7139 MachineFunction::iterator It = BB;
7145 // cmpTY ccX, r1, r2
7147 // fallthrough --> copy0MBB
7148 MachineBasicBlock *thisMBB = BB;
7149 MachineFunction *F = BB->getParent();
7150 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7151 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7153 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7154 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
7155 F->insert(It, copy0MBB);
7156 F->insert(It, sinkMBB);
7157 // Update machine-CFG edges by transferring all successors of the current
7158 // block to the new block which will contain the Phi node for the select.
7159 sinkMBB->transferSuccessors(BB);
7161 // Add the true and fallthrough blocks as its successors.
7162 BB->addSuccessor(copy0MBB);
7163 BB->addSuccessor(sinkMBB);
7166 // %FalseValue = ...
7167 // # fallthrough to sinkMBB
7170 // Update machine-CFG edges
7171 BB->addSuccessor(sinkMBB);
7174 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7177 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
7178 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7179 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7181 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7185 case X86::FP32_TO_INT16_IN_MEM:
7186 case X86::FP32_TO_INT32_IN_MEM:
7187 case X86::FP32_TO_INT64_IN_MEM:
7188 case X86::FP64_TO_INT16_IN_MEM:
7189 case X86::FP64_TO_INT32_IN_MEM:
7190 case X86::FP64_TO_INT64_IN_MEM:
7191 case X86::FP80_TO_INT16_IN_MEM:
7192 case X86::FP80_TO_INT32_IN_MEM:
7193 case X86::FP80_TO_INT64_IN_MEM: {
7194 // Change the floating point control register to use "round towards zero"
7195 // mode when truncating to an integer value.
7196 MachineFunction *F = BB->getParent();
7197 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7198 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7200 // Load the old value of the high byte of the control word...
7202 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7203 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
7205 // Set the high part to be round to zero...
7206 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
7209 // Reload the modified control word now...
7210 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7212 // Restore the memory image of control word to original value
7213 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
7216 // Get the X86 opcode to use.
7218 switch (MI->getOpcode()) {
7219 default: assert(0 && "illegal opcode!");
7220 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7221 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7222 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7223 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7224 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7225 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7226 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7227 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7228 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7232 MachineOperand &Op = MI->getOperand(0);
7234 AM.BaseType = X86AddressMode::RegBase;
7235 AM.Base.Reg = Op.getReg();
7237 AM.BaseType = X86AddressMode::FrameIndexBase;
7238 AM.Base.FrameIndex = Op.getIndex();
7240 Op = MI->getOperand(1);
7242 AM.Scale = Op.getImm();
7243 Op = MI->getOperand(2);
7245 AM.IndexReg = Op.getImm();
7246 Op = MI->getOperand(3);
7247 if (Op.isGlobal()) {
7248 AM.GV = Op.getGlobal();
7250 AM.Disp = Op.getImm();
7252 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
7253 .addReg(MI->getOperand(4).getReg());
7255 // Reload the original control word now.
7256 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7258 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7261 case X86::ATOMAND32:
7262 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7263 X86::AND32ri, X86::MOV32rm,
7264 X86::LCMPXCHG32, X86::MOV32rr,
7265 X86::NOT32r, X86::EAX,
7266 X86::GR32RegisterClass);
7268 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7269 X86::OR32ri, X86::MOV32rm,
7270 X86::LCMPXCHG32, X86::MOV32rr,
7271 X86::NOT32r, X86::EAX,
7272 X86::GR32RegisterClass);
7273 case X86::ATOMXOR32:
7274 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7275 X86::XOR32ri, X86::MOV32rm,
7276 X86::LCMPXCHG32, X86::MOV32rr,
7277 X86::NOT32r, X86::EAX,
7278 X86::GR32RegisterClass);
7279 case X86::ATOMNAND32:
7280 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7281 X86::AND32ri, X86::MOV32rm,
7282 X86::LCMPXCHG32, X86::MOV32rr,
7283 X86::NOT32r, X86::EAX,
7284 X86::GR32RegisterClass, true);
7285 case X86::ATOMMIN32:
7286 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7287 case X86::ATOMMAX32:
7288 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7289 case X86::ATOMUMIN32:
7290 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7291 case X86::ATOMUMAX32:
7292 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7294 case X86::ATOMAND16:
7295 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7296 X86::AND16ri, X86::MOV16rm,
7297 X86::LCMPXCHG16, X86::MOV16rr,
7298 X86::NOT16r, X86::AX,
7299 X86::GR16RegisterClass);
7301 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7302 X86::OR16ri, X86::MOV16rm,
7303 X86::LCMPXCHG16, X86::MOV16rr,
7304 X86::NOT16r, X86::AX,
7305 X86::GR16RegisterClass);
7306 case X86::ATOMXOR16:
7307 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7308 X86::XOR16ri, X86::MOV16rm,
7309 X86::LCMPXCHG16, X86::MOV16rr,
7310 X86::NOT16r, X86::AX,
7311 X86::GR16RegisterClass);
7312 case X86::ATOMNAND16:
7313 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7314 X86::AND16ri, X86::MOV16rm,
7315 X86::LCMPXCHG16, X86::MOV16rr,
7316 X86::NOT16r, X86::AX,
7317 X86::GR16RegisterClass, true);
7318 case X86::ATOMMIN16:
7319 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7320 case X86::ATOMMAX16:
7321 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7322 case X86::ATOMUMIN16:
7323 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7324 case X86::ATOMUMAX16:
7325 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7328 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7329 X86::AND8ri, X86::MOV8rm,
7330 X86::LCMPXCHG8, X86::MOV8rr,
7331 X86::NOT8r, X86::AL,
7332 X86::GR8RegisterClass);
7334 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7335 X86::OR8ri, X86::MOV8rm,
7336 X86::LCMPXCHG8, X86::MOV8rr,
7337 X86::NOT8r, X86::AL,
7338 X86::GR8RegisterClass);
7340 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7341 X86::XOR8ri, X86::MOV8rm,
7342 X86::LCMPXCHG8, X86::MOV8rr,
7343 X86::NOT8r, X86::AL,
7344 X86::GR8RegisterClass);
7345 case X86::ATOMNAND8:
7346 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7347 X86::AND8ri, X86::MOV8rm,
7348 X86::LCMPXCHG8, X86::MOV8rr,
7349 X86::NOT8r, X86::AL,
7350 X86::GR8RegisterClass, true);
7351 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7352 // This group is for 64-bit host.
7353 case X86::ATOMAND64:
7354 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7355 X86::AND64ri32, X86::MOV64rm,
7356 X86::LCMPXCHG64, X86::MOV64rr,
7357 X86::NOT64r, X86::RAX,
7358 X86::GR64RegisterClass);
7360 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7361 X86::OR64ri32, X86::MOV64rm,
7362 X86::LCMPXCHG64, X86::MOV64rr,
7363 X86::NOT64r, X86::RAX,
7364 X86::GR64RegisterClass);
7365 case X86::ATOMXOR64:
7366 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7367 X86::XOR64ri32, X86::MOV64rm,
7368 X86::LCMPXCHG64, X86::MOV64rr,
7369 X86::NOT64r, X86::RAX,
7370 X86::GR64RegisterClass);
7371 case X86::ATOMNAND64:
7372 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7373 X86::AND64ri32, X86::MOV64rm,
7374 X86::LCMPXCHG64, X86::MOV64rr,
7375 X86::NOT64r, X86::RAX,
7376 X86::GR64RegisterClass, true);
7377 case X86::ATOMMIN64:
7378 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7379 case X86::ATOMMAX64:
7380 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7381 case X86::ATOMUMIN64:
7382 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7383 case X86::ATOMUMAX64:
7384 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7386 // This group does 64-bit operations on a 32-bit host.
7387 case X86::ATOMAND6432:
7388 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7389 X86::AND32rr, X86::AND32rr,
7390 X86::AND32ri, X86::AND32ri,
7392 case X86::ATOMOR6432:
7393 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7394 X86::OR32rr, X86::OR32rr,
7395 X86::OR32ri, X86::OR32ri,
7397 case X86::ATOMXOR6432:
7398 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7399 X86::XOR32rr, X86::XOR32rr,
7400 X86::XOR32ri, X86::XOR32ri,
7402 case X86::ATOMNAND6432:
7403 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7404 X86::AND32rr, X86::AND32rr,
7405 X86::AND32ri, X86::AND32ri,
7407 case X86::ATOMADD6432:
7408 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7409 X86::ADD32rr, X86::ADC32rr,
7410 X86::ADD32ri, X86::ADC32ri,
7412 case X86::ATOMSUB6432:
7413 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7414 X86::SUB32rr, X86::SBB32rr,
7415 X86::SUB32ri, X86::SBB32ri,
7417 case X86::ATOMSWAP6432:
7418 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7419 X86::MOV32rr, X86::MOV32rr,
7420 X86::MOV32ri, X86::MOV32ri,
7425 //===----------------------------------------------------------------------===//
7426 // X86 Optimization Hooks
7427 //===----------------------------------------------------------------------===//
7429 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7433 const SelectionDAG &DAG,
7434 unsigned Depth) const {
7435 unsigned Opc = Op.getOpcode();
7436 assert((Opc >= ISD::BUILTIN_OP_END ||
7437 Opc == ISD::INTRINSIC_WO_CHAIN ||
7438 Opc == ISD::INTRINSIC_W_CHAIN ||
7439 Opc == ISD::INTRINSIC_VOID) &&
7440 "Should use MaskedValueIsZero if you don't know whether Op"
7441 " is a target node!");
7443 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7447 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7448 Mask.getBitWidth() - 1);
7453 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7454 /// node is a GlobalAddress + offset.
7455 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7456 GlobalValue* &GA, int64_t &Offset) const{
7457 if (N->getOpcode() == X86ISD::Wrapper) {
7458 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7459 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7460 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7464 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7467 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7468 const TargetLowering &TLI) {
7471 if (TLI.isGAPlusOffset(Base, GV, Offset))
7472 return (GV->getAlignment() >= N && (Offset % N) == 0);
7473 // DAG combine handles the stack object case.
7477 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7478 unsigned NumElems, MVT EVT,
7480 SelectionDAG &DAG, MachineFrameInfo *MFI,
7481 const TargetLowering &TLI) {
7483 for (unsigned i = 0; i < NumElems; ++i) {
7484 SDValue Idx = PermMask.getOperand(i);
7485 if (Idx.getOpcode() == ISD::UNDEF) {
7491 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7492 if (!Elt.getNode() ||
7493 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7496 Base = Elt.getNode();
7497 if (Base->getOpcode() == ISD::UNDEF)
7501 if (Elt.getOpcode() == ISD::UNDEF)
7504 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7505 EVT.getSizeInBits()/8, i, MFI))
7511 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7512 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7513 /// if the load addresses are consecutive, non-overlapping, and in the right
7515 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7516 const TargetLowering &TLI) {
7517 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7518 MVT VT = N->getValueType(0);
7519 MVT EVT = VT.getVectorElementType();
7520 SDValue PermMask = N->getOperand(2);
7521 unsigned NumElems = PermMask.getNumOperands();
7522 SDNode *Base = NULL;
7523 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7527 LoadSDNode *LD = cast<LoadSDNode>(Base);
7528 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7529 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7530 LD->getSrcValueOffset(), LD->isVolatile());
7531 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7532 LD->getSrcValueOffset(), LD->isVolatile(),
7533 LD->getAlignment());
7536 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7537 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7538 const X86Subtarget *Subtarget,
7539 const TargetLowering &TLI) {
7540 unsigned NumOps = N->getNumOperands();
7542 // Ignore single operand BUILD_VECTOR.
7546 MVT VT = N->getValueType(0);
7547 MVT EVT = VT.getVectorElementType();
7548 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7549 // We are looking for load i64 and zero extend. We want to transform
7550 // it before legalizer has a chance to expand it. Also look for i64
7551 // BUILD_PAIR bit casted to f64.
7553 // This must be an insertion into a zero vector.
7554 SDValue HighElt = N->getOperand(1);
7555 if (!isZeroNode(HighElt))
7558 // Value must be a load.
7559 SDNode *Base = N->getOperand(0).getNode();
7560 if (!isa<LoadSDNode>(Base)) {
7561 if (Base->getOpcode() != ISD::BIT_CONVERT)
7563 Base = Base->getOperand(0).getNode();
7564 if (!isa<LoadSDNode>(Base))
7568 // Transform it into VZEXT_LOAD addr.
7569 LoadSDNode *LD = cast<LoadSDNode>(Base);
7571 // Load must not be an extload.
7572 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7575 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7576 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7577 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7578 DAG.ReplaceAllUsesOfValueWith(SDValue(Base, 1), ResNode.getValue(1));
7582 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7583 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7584 const X86Subtarget *Subtarget) {
7585 SDValue Cond = N->getOperand(0);
7587 // If we have SSE[12] support, try to form min/max nodes.
7588 if (Subtarget->hasSSE2() &&
7589 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7590 if (Cond.getOpcode() == ISD::SETCC) {
7591 // Get the LHS/RHS of the select.
7592 SDValue LHS = N->getOperand(1);
7593 SDValue RHS = N->getOperand(2);
7594 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7596 unsigned Opcode = 0;
7597 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7600 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7603 if (!UnsafeFPMath) break;
7605 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7607 Opcode = X86ISD::FMIN;
7610 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7613 if (!UnsafeFPMath) break;
7615 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7617 Opcode = X86ISD::FMAX;
7620 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7623 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7626 if (!UnsafeFPMath) break;
7628 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7630 Opcode = X86ISD::FMIN;
7633 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7636 if (!UnsafeFPMath) break;
7638 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7640 Opcode = X86ISD::FMAX;
7646 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7654 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7655 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7656 const X86Subtarget *Subtarget) {
7657 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7658 // the FP state in cases where an emms may be missing.
7659 // A preferable solution to the general problem is to figure out the right
7660 // places to insert EMMS. This qualifies as a quick hack.
7661 StoreSDNode *St = cast<StoreSDNode>(N);
7662 if (St->getValue().getValueType().isVector() &&
7663 St->getValue().getValueType().getSizeInBits() == 64 &&
7664 isa<LoadSDNode>(St->getValue()) &&
7665 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7666 St->getChain().hasOneUse() && !St->isVolatile()) {
7667 SDNode* LdVal = St->getValue().getNode();
7669 int TokenFactorIndex = -1;
7670 SmallVector<SDValue, 8> Ops;
7671 SDNode* ChainVal = St->getChain().getNode();
7672 // Must be a store of a load. We currently handle two cases: the load
7673 // is a direct child, and it's under an intervening TokenFactor. It is
7674 // possible to dig deeper under nested TokenFactors.
7675 if (ChainVal == LdVal)
7676 Ld = cast<LoadSDNode>(St->getChain());
7677 else if (St->getValue().hasOneUse() &&
7678 ChainVal->getOpcode() == ISD::TokenFactor) {
7679 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7680 if (ChainVal->getOperand(i).getNode() == LdVal) {
7681 TokenFactorIndex = i;
7682 Ld = cast<LoadSDNode>(St->getValue());
7684 Ops.push_back(ChainVal->getOperand(i));
7688 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7689 if (Subtarget->is64Bit()) {
7690 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
7691 Ld->getBasePtr(), Ld->getSrcValue(),
7692 Ld->getSrcValueOffset(), Ld->isVolatile(),
7693 Ld->getAlignment());
7694 SDValue NewChain = NewLd.getValue(1);
7695 if (TokenFactorIndex != -1) {
7696 Ops.push_back(NewChain);
7697 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7700 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7701 St->getSrcValue(), St->getSrcValueOffset(),
7702 St->isVolatile(), St->getAlignment());
7705 // Otherwise, lower to two 32-bit copies.
7706 SDValue LoAddr = Ld->getBasePtr();
7707 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7708 DAG.getConstant(4, MVT::i32));
7710 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7711 Ld->getSrcValue(), Ld->getSrcValueOffset(),
7712 Ld->isVolatile(), Ld->getAlignment());
7713 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7714 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7716 MinAlign(Ld->getAlignment(), 4));
7718 SDValue NewChain = LoLd.getValue(1);
7719 if (TokenFactorIndex != -1) {
7720 Ops.push_back(LoLd);
7721 Ops.push_back(HiLd);
7722 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7726 LoAddr = St->getBasePtr();
7727 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7728 DAG.getConstant(4, MVT::i32));
7730 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7731 St->getSrcValue(), St->getSrcValueOffset(),
7732 St->isVolatile(), St->getAlignment());
7733 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7735 St->getSrcValueOffset() + 4,
7737 MinAlign(St->getAlignment(), 4));
7738 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7744 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7745 /// X86ISD::FXOR nodes.
7746 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7747 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7748 // F[X]OR(0.0, x) -> x
7749 // F[X]OR(x, 0.0) -> x
7750 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7751 if (C->getValueAPF().isPosZero())
7752 return N->getOperand(1);
7753 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7754 if (C->getValueAPF().isPosZero())
7755 return N->getOperand(0);
7759 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7760 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7761 // FAND(0.0, x) -> 0.0
7762 // FAND(x, 0.0) -> 0.0
7763 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7764 if (C->getValueAPF().isPosZero())
7765 return N->getOperand(0);
7766 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7767 if (C->getValueAPF().isPosZero())
7768 return N->getOperand(1);
7773 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7774 DAGCombinerInfo &DCI) const {
7775 SelectionDAG &DAG = DCI.DAG;
7776 switch (N->getOpcode()) {
7778 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7779 case ISD::BUILD_VECTOR:
7780 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7781 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
7782 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
7784 case X86ISD::FOR: return PerformFORCombine(N, DAG);
7785 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
7791 //===----------------------------------------------------------------------===//
7792 // X86 Inline Assembly Support
7793 //===----------------------------------------------------------------------===//
7795 /// getConstraintType - Given a constraint letter, return the type of
7796 /// constraint it is for this target.
7797 X86TargetLowering::ConstraintType
7798 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7799 if (Constraint.size() == 1) {
7800 switch (Constraint[0]) {
7812 return C_RegisterClass;
7817 return TargetLowering::getConstraintType(Constraint);
7820 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7821 /// with another that has more specific requirements based on the type of the
7822 /// corresponding operand.
7823 const char *X86TargetLowering::
7824 LowerXConstraint(MVT ConstraintVT) const {
7825 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7826 // 'f' like normal targets.
7827 if (ConstraintVT.isFloatingPoint()) {
7828 if (Subtarget->hasSSE2())
7830 if (Subtarget->hasSSE1())
7834 return TargetLowering::LowerXConstraint(ConstraintVT);
7837 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7838 /// vector. If it is invalid, don't add anything to Ops.
7839 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7842 std::vector<SDValue>&Ops,
7843 SelectionDAG &DAG) const {
7844 SDValue Result(0, 0);
7846 switch (Constraint) {
7849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7850 if (C->getZExtValue() <= 31) {
7851 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7857 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7858 if (C->getZExtValue() <= 63) {
7859 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7865 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7866 if (C->getZExtValue() <= 255) {
7867 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7873 // Literal immediates are always ok.
7874 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7875 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7879 // If we are in non-pic codegen mode, we allow the address of a global (with
7880 // an optional displacement) to be used with 'i'.
7881 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7884 // Match either (GA) or (GA+C)
7886 Offset = GA->getOffset();
7887 } else if (Op.getOpcode() == ISD::ADD) {
7888 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7889 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7891 Offset = GA->getOffset()+C->getZExtValue();
7893 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7894 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7896 Offset = GA->getOffset()+C->getZExtValue();
7904 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
7906 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7912 // Otherwise, not valid for this mode.
7917 if (Result.getNode()) {
7918 Ops.push_back(Result);
7921 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
7925 std::vector<unsigned> X86TargetLowering::
7926 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7928 if (Constraint.size() == 1) {
7929 // FIXME: not handling fp-stack yet!
7930 switch (Constraint[0]) { // GCC X86 Constraint Letters
7931 default: break; // Unknown constraint letter
7932 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
7935 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7936 else if (VT == MVT::i16)
7937 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7938 else if (VT == MVT::i8)
7939 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7940 else if (VT == MVT::i64)
7941 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7946 return std::vector<unsigned>();
7949 std::pair<unsigned, const TargetRegisterClass*>
7950 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7952 // First, see if this is a constraint that directly corresponds to an LLVM
7954 if (Constraint.size() == 1) {
7955 // GCC Constraint Letters
7956 switch (Constraint[0]) {
7958 case 'r': // GENERAL_REGS
7959 case 'R': // LEGACY_REGS
7960 case 'l': // INDEX_REGS
7962 return std::make_pair(0U, X86::GR8RegisterClass);
7964 return std::make_pair(0U, X86::GR16RegisterClass);
7965 if (VT == MVT::i32 || !Subtarget->is64Bit())
7966 return std::make_pair(0U, X86::GR32RegisterClass);
7967 return std::make_pair(0U, X86::GR64RegisterClass);
7968 case 'f': // FP Stack registers.
7969 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7970 // value to the correct fpstack register class.
7971 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7972 return std::make_pair(0U, X86::RFP32RegisterClass);
7973 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7974 return std::make_pair(0U, X86::RFP64RegisterClass);
7975 return std::make_pair(0U, X86::RFP80RegisterClass);
7976 case 'y': // MMX_REGS if MMX allowed.
7977 if (!Subtarget->hasMMX()) break;
7978 return std::make_pair(0U, X86::VR64RegisterClass);
7979 case 'Y': // SSE_REGS if SSE2 allowed
7980 if (!Subtarget->hasSSE2()) break;
7982 case 'x': // SSE_REGS if SSE1 allowed
7983 if (!Subtarget->hasSSE1()) break;
7985 switch (VT.getSimpleVT()) {
7987 // Scalar SSE types.
7990 return std::make_pair(0U, X86::FR32RegisterClass);
7993 return std::make_pair(0U, X86::FR64RegisterClass);
8001 return std::make_pair(0U, X86::VR128RegisterClass);
8007 // Use the default implementation in TargetLowering to convert the register
8008 // constraint into a member of a register class.
8009 std::pair<unsigned, const TargetRegisterClass*> Res;
8010 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8012 // Not found as a standard register?
8013 if (Res.second == 0) {
8014 // GCC calls "st(0)" just plain "st".
8015 if (StringsEqualNoCase("{st}", Constraint)) {
8016 Res.first = X86::ST0;
8017 Res.second = X86::RFP80RegisterClass;
8019 // 'A' means EAX + EDX.
8020 if (Constraint == "A") {
8021 Res.first = X86::EAX;
8022 Res.second = X86::GRADRegisterClass;
8027 // Otherwise, check to see if this is a register class of the wrong value
8028 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8029 // turn into {ax},{dx}.
8030 if (Res.second->hasType(VT))
8031 return Res; // Correct type already, nothing to do.
8033 // All of the single-register GCC register classes map their values onto
8034 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8035 // really want an 8-bit or 32-bit register, map to the appropriate register
8036 // class and return the appropriate register.
8037 if (Res.second == X86::GR16RegisterClass) {
8038 if (VT == MVT::i8) {
8039 unsigned DestReg = 0;
8040 switch (Res.first) {
8042 case X86::AX: DestReg = X86::AL; break;
8043 case X86::DX: DestReg = X86::DL; break;
8044 case X86::CX: DestReg = X86::CL; break;
8045 case X86::BX: DestReg = X86::BL; break;
8048 Res.first = DestReg;
8049 Res.second = Res.second = X86::GR8RegisterClass;
8051 } else if (VT == MVT::i32) {
8052 unsigned DestReg = 0;
8053 switch (Res.first) {
8055 case X86::AX: DestReg = X86::EAX; break;
8056 case X86::DX: DestReg = X86::EDX; break;
8057 case X86::CX: DestReg = X86::ECX; break;
8058 case X86::BX: DestReg = X86::EBX; break;
8059 case X86::SI: DestReg = X86::ESI; break;
8060 case X86::DI: DestReg = X86::EDI; break;
8061 case X86::BP: DestReg = X86::EBP; break;
8062 case X86::SP: DestReg = X86::ESP; break;
8065 Res.first = DestReg;
8066 Res.second = Res.second = X86::GR32RegisterClass;
8068 } else if (VT == MVT::i64) {
8069 unsigned DestReg = 0;
8070 switch (Res.first) {
8072 case X86::AX: DestReg = X86::RAX; break;
8073 case X86::DX: DestReg = X86::RDX; break;
8074 case X86::CX: DestReg = X86::RCX; break;
8075 case X86::BX: DestReg = X86::RBX; break;
8076 case X86::SI: DestReg = X86::RSI; break;
8077 case X86::DI: DestReg = X86::RDI; break;
8078 case X86::BP: DestReg = X86::RBP; break;
8079 case X86::SP: DestReg = X86::RSP; break;
8082 Res.first = DestReg;
8083 Res.second = Res.second = X86::GR64RegisterClass;
8086 } else if (Res.second == X86::FR32RegisterClass ||
8087 Res.second == X86::FR64RegisterClass ||
8088 Res.second == X86::VR128RegisterClass) {
8089 // Handle references to XMM physical registers that got mapped into the
8090 // wrong class. This can happen with constraints like {xmm0} where the
8091 // target independent register mapper will just pick the first match it can
8092 // find, ignoring the required type.
8094 Res.second = X86::FR32RegisterClass;
8095 else if (VT == MVT::f64)
8096 Res.second = X86::FR64RegisterClass;
8097 else if (X86::VR128RegisterClass->hasType(VT))
8098 Res.second = X86::VR128RegisterClass;
8104 //===----------------------------------------------------------------------===//
8105 // X86 Widen vector type
8106 //===----------------------------------------------------------------------===//
8108 /// getWidenVectorType: given a vector type, returns the type to widen
8109 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8110 /// If there is no vector type that we want to widen to, returns MVT::Other
8111 /// When and where to widen is target dependent based on the cost of
8112 /// scalarizing vs using the wider vector type.
8114 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8115 assert(VT.isVector());
8116 if (isTypeLegal(VT))
8119 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8120 // type based on element type. This would speed up our search (though
8121 // it may not be worth it since the size of the list is relatively
8123 MVT EltVT = VT.getVectorElementType();
8124 unsigned NElts = VT.getVectorNumElements();
8126 // On X86, it make sense to widen any vector wider than 1
8130 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8131 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8132 MVT SVT = (MVT::SimpleValueType)nVT;
8134 if (isTypeLegal(SVT) &&
8135 SVT.getVectorElementType() == EltVT &&
8136 SVT.getVectorNumElements() > NElts)