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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
54 STATISTIC(NumTailCalls, "Number of tail calls");
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference. Idx is an index in the 128 bits we
63 /// want. It need not be aligned to a 128-bit bounday. That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66 SelectionDAG &DAG, DebugLoc dl) {
67 EVT VT = Vec.getValueType();
68 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/128;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
79 // we can match to VEXTRACTF128.
80 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82 // This is the index of the first element of the 128-bit chunk
84 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
87 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference. Idx is an index in the 128 bits
97 /// we want. It need not be aligned to a 128-bit bounday. That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100 unsigned IdxVal, SelectionDAG &DAG,
102 // Inserting UNDEF is Result
103 if (Vec.getOpcode() == ISD::UNDEF)
106 EVT VT = Vec.getValueType();
107 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
109 EVT ElVT = VT.getVectorElementType();
110 EVT ResultVT = Result.getValueType();
112 // Insert the relevant 128 bits.
113 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115 // This is the index of the first element of the 128-bit chunk
117 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
120 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
121 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
125 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
126 /// instructions. This is used because creating CONCAT_VECTOR nodes of
127 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
128 /// large BUILD_VECTORS.
129 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
130 unsigned NumElems, SelectionDAG &DAG,
132 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
133 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
136 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
137 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
138 bool is64Bit = Subtarget->is64Bit();
140 if (Subtarget->isTargetEnvMacho()) {
142 return new X86_64MachoTargetObjectFile();
143 return new TargetLoweringObjectFileMachO();
146 if (Subtarget->isTargetLinux())
147 return new X86LinuxTargetObjectFile();
148 if (Subtarget->isTargetELF())
149 return new TargetLoweringObjectFileELF();
150 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
151 return new TargetLoweringObjectFileCOFF();
152 llvm_unreachable("unknown subtarget type");
155 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
156 : TargetLowering(TM, createTLOF(TM)) {
157 Subtarget = &TM.getSubtarget<X86Subtarget>();
158 X86ScalarSSEf64 = Subtarget->hasSSE2();
159 X86ScalarSSEf32 = Subtarget->hasSSE1();
160 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162 RegInfo = TM.getRegisterInfo();
163 TD = getTargetData();
165 // Set up the TargetLowering object.
166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168 // X86 is weird, it always uses i8 for shift amounts and setcc results.
169 setBooleanContents(ZeroOrOneBooleanContent);
170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 // For 64-bit since we have so many registers use the ILP scheduler, for
174 // 32-bit code use the register pressure specific scheduling.
175 // For Atom, always use ILP scheduling.
176 if (Subtarget->isAtom())
177 setSchedulingPreference(Sched::ILP);
178 else if (Subtarget->is64Bit())
179 setSchedulingPreference(Sched::ILP);
181 setSchedulingPreference(Sched::RegPressure);
182 setStackPointerRegisterToSaveRestore(X86StackPtr);
184 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
185 // Setup Windows compiler runtime calls.
186 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
187 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
188 setLibcallName(RTLIB::SREM_I64, "_allrem");
189 setLibcallName(RTLIB::UREM_I64, "_aullrem");
190 setLibcallName(RTLIB::MUL_I64, "_allmul");
191 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
192 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
193 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
194 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
195 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
197 // The _ftol2 runtime function has an unusual calling conv, which
198 // is modeled by a special pseudo-instruction.
199 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
200 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
201 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
202 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
205 if (Subtarget->isTargetDarwin()) {
206 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
207 setUseUnderscoreSetJmp(false);
208 setUseUnderscoreLongJmp(false);
209 } else if (Subtarget->isTargetMingw()) {
210 // MS runtime is weird: it exports _setjmp, but longjmp!
211 setUseUnderscoreSetJmp(true);
212 setUseUnderscoreLongJmp(false);
214 setUseUnderscoreSetJmp(true);
215 setUseUnderscoreLongJmp(true);
218 // Set up the register classes.
219 addRegisterClass(MVT::i8, &X86::GR8RegClass);
220 addRegisterClass(MVT::i16, &X86::GR16RegClass);
221 addRegisterClass(MVT::i32, &X86::GR32RegClass);
222 if (Subtarget->is64Bit())
223 addRegisterClass(MVT::i64, &X86::GR64RegClass);
225 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
227 // We don't accept any truncstore of integer registers.
228 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
229 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
230 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
231 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
232 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
233 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
235 // SETOEQ and SETUNE require checking two conditions.
236 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
237 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
238 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
239 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
240 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
241 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
243 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
245 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
246 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
247 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
249 if (Subtarget->is64Bit()) {
250 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
252 } else if (!TM.Options.UseSoftFloat) {
253 // We have an algorithm for SSE2->double, and we turn this into a
254 // 64-bit FILD followed by conditional FADD for other targets.
255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
256 // We have an algorithm for SSE2, and we turn this into a 64-bit
257 // FILD for other targets.
258 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
261 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
263 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
264 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
266 if (!TM.Options.UseSoftFloat) {
267 // SSE has no i16 to fp conversion, only i32
268 if (X86ScalarSSEf32) {
269 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
270 // f32 and f64 cases are Legal, f80 case is not
271 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
274 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
281 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
282 // are Legal, f80 is custom lowered.
283 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
284 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
286 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
288 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
289 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
291 if (X86ScalarSSEf32) {
292 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
293 // f32 and f64 cases are Legal, f80 case is not
294 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
300 // Handle FP_TO_UINT by promoting the destination to a larger signed
302 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
303 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
304 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
306 if (Subtarget->is64Bit()) {
307 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
309 } else if (!TM.Options.UseSoftFloat) {
310 // Since AVX is a superset of SSE3, only check for SSE here.
311 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
312 // Expand FP_TO_UINT into a select.
313 // FIXME: We would like to use a Custom expander here eventually to do
314 // the optimal thing for SSE vs. the default expansion in the legalizer.
315 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
317 // With SSE3 we can use fisttpll to convert to a signed i64; without
318 // SSE, we're stuck with a fistpll.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
322 if (isTargetFTOL()) {
323 // Use the _ftol2 runtime function, which has a pseudo-instruction
324 // to handle its weird calling convention.
325 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
328 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
329 if (!X86ScalarSSEf64) {
330 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
331 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
332 if (Subtarget->is64Bit()) {
333 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
334 // Without SSE, i64->f64 goes through memory.
335 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
339 // Scalar integer divide and remainder are lowered to use operations that
340 // produce two results, to match the available instructions. This exposes
341 // the two-result form to trivial CSE, which is able to combine x/y and x%y
342 // into a single instruction.
344 // Scalar integer multiply-high is also lowered to use two-result
345 // operations, to match the available instructions. However, plain multiply
346 // (low) operations are left as Legal, as there are single-result
347 // instructions for this in x86. Using the two-result multiply instructions
348 // when both high and low results are needed must be arranged by dagcombine.
349 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
351 setOperationAction(ISD::MULHS, VT, Expand);
352 setOperationAction(ISD::MULHU, VT, Expand);
353 setOperationAction(ISD::SDIV, VT, Expand);
354 setOperationAction(ISD::UDIV, VT, Expand);
355 setOperationAction(ISD::SREM, VT, Expand);
356 setOperationAction(ISD::UREM, VT, Expand);
358 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
359 setOperationAction(ISD::ADDC, VT, Custom);
360 setOperationAction(ISD::ADDE, VT, Custom);
361 setOperationAction(ISD::SUBC, VT, Custom);
362 setOperationAction(ISD::SUBE, VT, Custom);
365 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
366 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
367 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
368 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
369 if (Subtarget->is64Bit())
370 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
374 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
375 setOperationAction(ISD::FREM , MVT::f32 , Expand);
376 setOperationAction(ISD::FREM , MVT::f64 , Expand);
377 setOperationAction(ISD::FREM , MVT::f80 , Expand);
378 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
380 // Promote the i8 variants and force them on up to i32 which has a shorter
382 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
383 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
384 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
385 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
386 if (Subtarget->hasBMI()) {
387 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
389 if (Subtarget->is64Bit())
390 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
392 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
393 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
398 if (Subtarget->hasLZCNT()) {
399 // When promoting the i8 variants, force them to i32 for a shorter
401 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
402 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
403 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
404 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
405 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
406 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
407 if (Subtarget->is64Bit())
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
410 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
411 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
412 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
422 if (Subtarget->hasPOPCNT()) {
423 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
425 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
426 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
427 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
428 if (Subtarget->is64Bit())
429 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
432 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
433 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
435 // These should be promoted to a larger select which is supported.
436 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
437 // X86 wants to expand cmov itself.
438 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
439 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
440 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
441 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
442 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
443 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
444 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
445 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
446 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
447 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
448 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
449 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
450 if (Subtarget->is64Bit()) {
451 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
452 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
454 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
457 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
458 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
459 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
460 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
461 if (Subtarget->is64Bit())
462 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
463 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
464 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
465 if (Subtarget->is64Bit()) {
466 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
467 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
468 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
469 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
470 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
472 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
473 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
474 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
475 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
476 if (Subtarget->is64Bit()) {
477 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
478 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
479 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
482 if (Subtarget->hasSSE1())
483 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
485 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
486 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
488 // On X86 and X86-64, atomic operations are lowered to locked instructions.
489 // Locked instructions, in turn, have implicit fence semantics (all memory
490 // operations are flushed before issuing the locked instruction, and they
491 // are not buffered), so we can fold away the common pattern of
492 // fence-atomic-fence.
493 setShouldFoldAtomicFences(true);
495 // Expand certain atomics
496 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
498 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
499 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
500 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
503 if (!Subtarget->is64Bit()) {
504 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
505 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
514 if (Subtarget->hasCmpxchg16b()) {
515 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
518 // FIXME - use subtarget debug flags
519 if (!Subtarget->isTargetDarwin() &&
520 !Subtarget->isTargetELF() &&
521 !Subtarget->isTargetCygMing()) {
522 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
525 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
526 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
527 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
528 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
529 if (Subtarget->is64Bit()) {
530 setExceptionPointerRegister(X86::RAX);
531 setExceptionSelectorRegister(X86::RDX);
533 setExceptionPointerRegister(X86::EAX);
534 setExceptionSelectorRegister(X86::EDX);
536 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
537 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
539 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
540 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
542 setOperationAction(ISD::TRAP, MVT::Other, Legal);
544 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
545 setOperationAction(ISD::VASTART , MVT::Other, Custom);
546 setOperationAction(ISD::VAEND , MVT::Other, Expand);
547 if (Subtarget->is64Bit()) {
548 setOperationAction(ISD::VAARG , MVT::Other, Custom);
549 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
551 setOperationAction(ISD::VAARG , MVT::Other, Expand);
552 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
555 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
556 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
558 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
559 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
560 MVT::i64 : MVT::i32, Custom);
561 else if (TM.Options.EnableSegmentedStacks)
562 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
563 MVT::i64 : MVT::i32, Custom);
565 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
566 MVT::i64 : MVT::i32, Expand);
568 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
569 // f32 and f64 use SSE.
570 // Set up the FP register classes.
571 addRegisterClass(MVT::f32, &X86::FR32RegClass);
572 addRegisterClass(MVT::f64, &X86::FR64RegClass);
574 // Use ANDPD to simulate FABS.
575 setOperationAction(ISD::FABS , MVT::f64, Custom);
576 setOperationAction(ISD::FABS , MVT::f32, Custom);
578 // Use XORP to simulate FNEG.
579 setOperationAction(ISD::FNEG , MVT::f64, Custom);
580 setOperationAction(ISD::FNEG , MVT::f32, Custom);
582 // Use ANDPD and ORPD to simulate FCOPYSIGN.
583 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
584 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
586 // Lower this to FGETSIGNx86 plus an AND.
587 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
588 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
590 // We don't support sin/cos/fmod
591 setOperationAction(ISD::FSIN , MVT::f64, Expand);
592 setOperationAction(ISD::FCOS , MVT::f64, Expand);
593 setOperationAction(ISD::FSIN , MVT::f32, Expand);
594 setOperationAction(ISD::FCOS , MVT::f32, Expand);
596 // Expand FP immediates into loads from the stack, except for the special
598 addLegalFPImmediate(APFloat(+0.0)); // xorpd
599 addLegalFPImmediate(APFloat(+0.0f)); // xorps
600 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
601 // Use SSE for f32, x87 for f64.
602 // Set up the FP register classes.
603 addRegisterClass(MVT::f32, &X86::FR32RegClass);
604 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
606 // Use ANDPS to simulate FABS.
607 setOperationAction(ISD::FABS , MVT::f32, Custom);
609 // Use XORP to simulate FNEG.
610 setOperationAction(ISD::FNEG , MVT::f32, Custom);
612 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
614 // Use ANDPS and ORPS to simulate FCOPYSIGN.
615 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
616 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
618 // We don't support sin/cos/fmod
619 setOperationAction(ISD::FSIN , MVT::f32, Expand);
620 setOperationAction(ISD::FCOS , MVT::f32, Expand);
622 // Special cases we handle for FP constants.
623 addLegalFPImmediate(APFloat(+0.0f)); // xorps
624 addLegalFPImmediate(APFloat(+0.0)); // FLD0
625 addLegalFPImmediate(APFloat(+1.0)); // FLD1
626 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
627 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
629 if (!TM.Options.UnsafeFPMath) {
630 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
631 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
633 } else if (!TM.Options.UseSoftFloat) {
634 // f32 and f64 in x87.
635 // Set up the FP register classes.
636 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
637 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
639 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
640 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
641 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
642 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
644 if (!TM.Options.UnsafeFPMath) {
645 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
646 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
648 addLegalFPImmediate(APFloat(+0.0)); // FLD0
649 addLegalFPImmediate(APFloat(+1.0)); // FLD1
650 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
651 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
652 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
653 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
654 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
655 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
658 // We don't support FMA.
659 setOperationAction(ISD::FMA, MVT::f64, Expand);
660 setOperationAction(ISD::FMA, MVT::f32, Expand);
662 // Long double always uses X87.
663 if (!TM.Options.UseSoftFloat) {
664 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
665 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
666 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
668 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
669 addLegalFPImmediate(TmpFlt); // FLD0
671 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
674 APFloat TmpFlt2(+1.0);
675 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
677 addLegalFPImmediate(TmpFlt2); // FLD1
678 TmpFlt2.changeSign();
679 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
682 if (!TM.Options.UnsafeFPMath) {
683 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
684 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
687 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
688 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
689 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
690 setOperationAction(ISD::FRINT, MVT::f80, Expand);
691 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
692 setOperationAction(ISD::FMA, MVT::f80, Expand);
695 // Always use a library call for pow.
696 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
697 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
698 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
700 setOperationAction(ISD::FLOG, MVT::f80, Expand);
701 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
702 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
703 setOperationAction(ISD::FEXP, MVT::f80, Expand);
704 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
706 // First set operation action for all vector types to either promote
707 // (for widening) or expand (for scalarization). Then we will selectively
708 // turn on ones that can be effectively codegen'd.
709 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
710 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
711 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
726 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
728 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
763 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
768 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
769 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
770 setTruncStoreAction((MVT::SimpleValueType)VT,
771 (MVT::SimpleValueType)InnerVT, Expand);
772 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
773 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
774 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
777 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
778 // with -msoft-float, disable use of MMX as well.
779 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
780 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
781 // No operations on x86mmx supported, everything uses intrinsics.
784 // MMX-sized vectors (other than x86mmx) are expected to be expanded
785 // into smaller operations.
786 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
787 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
788 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
789 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
790 setOperationAction(ISD::AND, MVT::v8i8, Expand);
791 setOperationAction(ISD::AND, MVT::v4i16, Expand);
792 setOperationAction(ISD::AND, MVT::v2i32, Expand);
793 setOperationAction(ISD::AND, MVT::v1i64, Expand);
794 setOperationAction(ISD::OR, MVT::v8i8, Expand);
795 setOperationAction(ISD::OR, MVT::v4i16, Expand);
796 setOperationAction(ISD::OR, MVT::v2i32, Expand);
797 setOperationAction(ISD::OR, MVT::v1i64, Expand);
798 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
799 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
800 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
801 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
802 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
803 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
804 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
805 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
806 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
807 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
808 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
809 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
810 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
811 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
812 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
813 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
814 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
816 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
817 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
819 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
820 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
821 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
822 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
823 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
824 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
825 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
826 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
827 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
828 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
829 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
830 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
833 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
834 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
836 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
837 // registers cannot be used even for integer operations.
838 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
839 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
840 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
841 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
843 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
844 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
845 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
846 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
847 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
848 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
849 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
850 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
851 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
852 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
853 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
854 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
855 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
856 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
857 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
858 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
860 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
861 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
862 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
863 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
865 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
866 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
867 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
868 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
871 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
872 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
873 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
874 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
875 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
877 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
879 EVT VT = (MVT::SimpleValueType)i;
880 // Do not attempt to custom lower non-power-of-2 vectors
881 if (!isPowerOf2_32(VT.getVectorNumElements()))
883 // Do not attempt to custom lower non-128-bit vectors
884 if (!VT.is128BitVector())
886 setOperationAction(ISD::BUILD_VECTOR,
887 VT.getSimpleVT().SimpleTy, Custom);
888 setOperationAction(ISD::VECTOR_SHUFFLE,
889 VT.getSimpleVT().SimpleTy, Custom);
890 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
891 VT.getSimpleVT().SimpleTy, Custom);
894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
895 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
897 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
899 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
901 if (Subtarget->is64Bit()) {
902 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
903 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
906 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
907 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
908 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
911 // Do not attempt to promote non-128-bit vectors
912 if (!VT.is128BitVector())
915 setOperationAction(ISD::AND, SVT, Promote);
916 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
917 setOperationAction(ISD::OR, SVT, Promote);
918 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
919 setOperationAction(ISD::XOR, SVT, Promote);
920 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
921 setOperationAction(ISD::LOAD, SVT, Promote);
922 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
923 setOperationAction(ISD::SELECT, SVT, Promote);
924 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
927 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
929 // Custom lower v2i64 and v2f64 selects.
930 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
931 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
932 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
933 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
935 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
936 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
939 if (Subtarget->hasSSE41()) {
940 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
941 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
942 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
943 setOperationAction(ISD::FRINT, MVT::f32, Legal);
944 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
945 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
946 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
947 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
948 setOperationAction(ISD::FRINT, MVT::f64, Legal);
949 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
951 // FIXME: Do we need to handle scalar-to-vector here?
952 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
954 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
955 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
956 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
957 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
958 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
960 // i8 and i16 vectors are custom , because the source register and source
961 // source memory operand types are not the same width. f32 vectors are
962 // custom since the immediate controlling the insert encodes additional
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
969 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
970 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
974 // FIXME: these should be Legal but thats only for the case where
975 // the index is constant. For now custom expand to deal with that.
976 if (Subtarget->is64Bit()) {
977 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
982 if (Subtarget->hasSSE2()) {
983 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
984 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
986 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
987 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
989 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
990 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
992 if (Subtarget->hasAVX2()) {
993 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
994 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
996 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
997 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
999 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1001 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1002 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1004 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1005 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1007 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1011 if (Subtarget->hasSSE42())
1012 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1014 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1015 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1016 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1017 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1018 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1019 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1020 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1022 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1023 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1024 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1026 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1027 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1028 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1029 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1030 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1031 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1033 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1034 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1035 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1036 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1037 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1038 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1040 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1041 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1042 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1044 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1045 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1046 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1047 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1048 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1049 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1051 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1052 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1054 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1055 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1057 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1058 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1060 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1061 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1062 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1063 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1065 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1066 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1067 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1069 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1074 if (Subtarget->hasAVX2()) {
1075 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1076 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1077 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1078 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1080 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1081 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1082 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1083 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1085 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1086 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1087 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1088 // Don't lower v32i8 because there is no 128-bit byte mul
1090 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1092 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1093 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1095 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1096 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1098 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1100 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1101 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1102 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1103 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1105 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1106 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1107 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1108 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1110 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1111 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1112 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1113 // Don't lower v32i8 because there is no 128-bit byte mul
1115 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1116 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1118 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1119 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1121 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1124 // Custom lower several nodes for 256-bit types.
1125 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1126 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1127 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1130 // Extract subvector is special because the value type
1131 // (result) is 128-bit but the source is 256-bit wide.
1132 if (VT.is128BitVector())
1133 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1135 // Do not attempt to custom lower other non-256-bit vectors
1136 if (!VT.is256BitVector())
1139 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1140 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1141 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1142 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1143 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1144 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1147 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1148 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1149 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1152 // Do not attempt to promote non-256-bit vectors
1153 if (!VT.is256BitVector())
1156 setOperationAction(ISD::AND, SVT, Promote);
1157 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1158 setOperationAction(ISD::OR, SVT, Promote);
1159 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1160 setOperationAction(ISD::XOR, SVT, Promote);
1161 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1162 setOperationAction(ISD::LOAD, SVT, Promote);
1163 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1164 setOperationAction(ISD::SELECT, SVT, Promote);
1165 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1169 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1170 // of this type with custom code.
1171 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1172 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1173 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1177 // We want to custom lower some of our intrinsics.
1178 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1181 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1182 // handle type legalization for these operations here.
1184 // FIXME: We really should do custom legalization for addition and
1185 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1186 // than generic legalization for 64-bit multiplication-with-overflow, though.
1187 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1188 // Add/Sub/Mul with overflow operations are custom lowered.
1190 setOperationAction(ISD::SADDO, VT, Custom);
1191 setOperationAction(ISD::UADDO, VT, Custom);
1192 setOperationAction(ISD::SSUBO, VT, Custom);
1193 setOperationAction(ISD::USUBO, VT, Custom);
1194 setOperationAction(ISD::SMULO, VT, Custom);
1195 setOperationAction(ISD::UMULO, VT, Custom);
1198 // There are no 8-bit 3-address imul/mul instructions
1199 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1200 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1202 if (!Subtarget->is64Bit()) {
1203 // These libcalls are not available in 32-bit.
1204 setLibcallName(RTLIB::SHL_I128, 0);
1205 setLibcallName(RTLIB::SRL_I128, 0);
1206 setLibcallName(RTLIB::SRA_I128, 0);
1209 // We have target-specific dag combine patterns for the following nodes:
1210 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1211 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1212 setTargetDAGCombine(ISD::VSELECT);
1213 setTargetDAGCombine(ISD::SELECT);
1214 setTargetDAGCombine(ISD::SHL);
1215 setTargetDAGCombine(ISD::SRA);
1216 setTargetDAGCombine(ISD::SRL);
1217 setTargetDAGCombine(ISD::OR);
1218 setTargetDAGCombine(ISD::AND);
1219 setTargetDAGCombine(ISD::ADD);
1220 setTargetDAGCombine(ISD::FADD);
1221 setTargetDAGCombine(ISD::FSUB);
1222 setTargetDAGCombine(ISD::SUB);
1223 setTargetDAGCombine(ISD::LOAD);
1224 setTargetDAGCombine(ISD::STORE);
1225 setTargetDAGCombine(ISD::ZERO_EXTEND);
1226 setTargetDAGCombine(ISD::ANY_EXTEND);
1227 setTargetDAGCombine(ISD::SIGN_EXTEND);
1228 setTargetDAGCombine(ISD::TRUNCATE);
1229 setTargetDAGCombine(ISD::UINT_TO_FP);
1230 setTargetDAGCombine(ISD::SINT_TO_FP);
1231 setTargetDAGCombine(ISD::SETCC);
1232 setTargetDAGCombine(ISD::FP_TO_SINT);
1233 if (Subtarget->is64Bit())
1234 setTargetDAGCombine(ISD::MUL);
1235 setTargetDAGCombine(ISD::XOR);
1237 computeRegisterProperties();
1239 // On Darwin, -Os means optimize for size without hurting performance,
1240 // do not reduce the limit.
1241 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1242 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1243 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1244 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1245 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1246 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1247 setPrefLoopAlignment(4); // 2^4 bytes.
1248 benefitFromCodePlacementOpt = true;
1250 // Predictable cmov don't hurt on atom because it's in-order.
1251 predictableSelectIsExpensive = !Subtarget->isAtom();
1253 setPrefFunctionAlignment(4); // 2^4 bytes.
1257 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1258 if (!VT.isVector()) return MVT::i8;
1259 return VT.changeVectorElementTypeToInteger();
1263 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1264 /// the desired ByVal argument alignment.
1265 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1268 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1269 if (VTy->getBitWidth() == 128)
1271 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1272 unsigned EltAlign = 0;
1273 getMaxByValAlign(ATy->getElementType(), EltAlign);
1274 if (EltAlign > MaxAlign)
1275 MaxAlign = EltAlign;
1276 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1278 unsigned EltAlign = 0;
1279 getMaxByValAlign(STy->getElementType(i), EltAlign);
1280 if (EltAlign > MaxAlign)
1281 MaxAlign = EltAlign;
1288 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1289 /// function arguments in the caller parameter area. For X86, aggregates
1290 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1291 /// are at 4-byte boundaries.
1292 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1293 if (Subtarget->is64Bit()) {
1294 // Max of 8 and alignment of type.
1295 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1302 if (Subtarget->hasSSE1())
1303 getMaxByValAlign(Ty, Align);
1307 /// getOptimalMemOpType - Returns the target specific optimal type for load
1308 /// and store operations as a result of memset, memcpy, and memmove
1309 /// lowering. If DstAlign is zero that means it's safe to destination
1310 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1311 /// means there isn't a need to check it against alignment requirement,
1312 /// probably because the source does not need to be loaded. If
1313 /// 'IsZeroVal' is true, that means it's safe to return a
1314 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1315 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1316 /// constant so it does not need to be loaded.
1317 /// It returns EVT::Other if the type should be determined using generic
1318 /// target-independent logic.
1320 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1321 unsigned DstAlign, unsigned SrcAlign,
1324 MachineFunction &MF) const {
1325 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1326 // linux. This is because the stack realignment code can't handle certain
1327 // cases like PR2962. This should be removed when PR2962 is fixed.
1328 const Function *F = MF.getFunction();
1330 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1332 (Subtarget->isUnalignedMemAccessFast() ||
1333 ((DstAlign == 0 || DstAlign >= 16) &&
1334 (SrcAlign == 0 || SrcAlign >= 16))) &&
1335 Subtarget->getStackAlignment() >= 16) {
1336 if (Subtarget->getStackAlignment() >= 32) {
1337 if (Subtarget->hasAVX2())
1339 if (Subtarget->hasAVX())
1342 if (Subtarget->hasSSE2())
1344 if (Subtarget->hasSSE1())
1346 } else if (!MemcpyStrSrc && Size >= 8 &&
1347 !Subtarget->is64Bit() &&
1348 Subtarget->getStackAlignment() >= 8 &&
1349 Subtarget->hasSSE2()) {
1350 // Do not use f64 to lower memcpy if source is string constant. It's
1351 // better to use i32 to avoid the loads.
1355 if (Subtarget->is64Bit() && Size >= 8)
1360 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1361 /// current function. The returned value is a member of the
1362 /// MachineJumpTableInfo::JTEntryKind enum.
1363 unsigned X86TargetLowering::getJumpTableEncoding() const {
1364 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1366 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1367 Subtarget->isPICStyleGOT())
1368 return MachineJumpTableInfo::EK_Custom32;
1370 // Otherwise, use the normal jump table encoding heuristics.
1371 return TargetLowering::getJumpTableEncoding();
1375 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1376 const MachineBasicBlock *MBB,
1377 unsigned uid,MCContext &Ctx) const{
1378 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1379 Subtarget->isPICStyleGOT());
1380 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1382 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1383 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1386 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1388 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1389 SelectionDAG &DAG) const {
1390 if (!Subtarget->is64Bit())
1391 // This doesn't have DebugLoc associated with it, but is not really the
1392 // same as a Register.
1393 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1397 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1398 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1400 const MCExpr *X86TargetLowering::
1401 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1402 MCContext &Ctx) const {
1403 // X86-64 uses RIP relative addressing based on the jump table label.
1404 if (Subtarget->isPICStyleRIPRel())
1405 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1407 // Otherwise, the reference is relative to the PIC base.
1408 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1411 // FIXME: Why this routine is here? Move to RegInfo!
1412 std::pair<const TargetRegisterClass*, uint8_t>
1413 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1414 const TargetRegisterClass *RRC = 0;
1416 switch (VT.getSimpleVT().SimpleTy) {
1418 return TargetLowering::findRepresentativeClass(VT);
1419 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1420 RRC = Subtarget->is64Bit() ?
1421 (const TargetRegisterClass*)&X86::GR64RegClass :
1422 (const TargetRegisterClass*)&X86::GR32RegClass;
1425 RRC = &X86::VR64RegClass;
1427 case MVT::f32: case MVT::f64:
1428 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1429 case MVT::v4f32: case MVT::v2f64:
1430 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1432 RRC = &X86::VR128RegClass;
1435 return std::make_pair(RRC, Cost);
1438 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1439 unsigned &Offset) const {
1440 if (!Subtarget->isTargetLinux())
1443 if (Subtarget->is64Bit()) {
1444 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1446 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1459 //===----------------------------------------------------------------------===//
1460 // Return Value Calling Convention Implementation
1461 //===----------------------------------------------------------------------===//
1463 #include "X86GenCallingConv.inc"
1466 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1467 MachineFunction &MF, bool isVarArg,
1468 const SmallVectorImpl<ISD::OutputArg> &Outs,
1469 LLVMContext &Context) const {
1470 SmallVector<CCValAssign, 16> RVLocs;
1471 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1473 return CCInfo.CheckReturn(Outs, RetCC_X86);
1477 X86TargetLowering::LowerReturn(SDValue Chain,
1478 CallingConv::ID CallConv, bool isVarArg,
1479 const SmallVectorImpl<ISD::OutputArg> &Outs,
1480 const SmallVectorImpl<SDValue> &OutVals,
1481 DebugLoc dl, SelectionDAG &DAG) const {
1482 MachineFunction &MF = DAG.getMachineFunction();
1483 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1485 SmallVector<CCValAssign, 16> RVLocs;
1486 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1487 RVLocs, *DAG.getContext());
1488 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1490 // Add the regs to the liveout set for the function.
1491 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1492 for (unsigned i = 0; i != RVLocs.size(); ++i)
1493 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1494 MRI.addLiveOut(RVLocs[i].getLocReg());
1498 SmallVector<SDValue, 6> RetOps;
1499 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1500 // Operand #1 = Bytes To Pop
1501 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1504 // Copy the result values into the output registers.
1505 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1506 CCValAssign &VA = RVLocs[i];
1507 assert(VA.isRegLoc() && "Can only return in registers!");
1508 SDValue ValToCopy = OutVals[i];
1509 EVT ValVT = ValToCopy.getValueType();
1511 // Promote values to the appropriate types
1512 if (VA.getLocInfo() == CCValAssign::SExt)
1513 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1514 else if (VA.getLocInfo() == CCValAssign::ZExt)
1515 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1516 else if (VA.getLocInfo() == CCValAssign::AExt)
1517 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1518 else if (VA.getLocInfo() == CCValAssign::BCvt)
1519 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1521 // If this is x86-64, and we disabled SSE, we can't return FP values,
1522 // or SSE or MMX vectors.
1523 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1524 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1525 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1526 report_fatal_error("SSE register return with SSE disabled");
1528 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1529 // llvm-gcc has never done it right and no one has noticed, so this
1530 // should be OK for now.
1531 if (ValVT == MVT::f64 &&
1532 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1533 report_fatal_error("SSE2 register return with SSE2 disabled");
1535 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1536 // the RET instruction and handled by the FP Stackifier.
1537 if (VA.getLocReg() == X86::ST0 ||
1538 VA.getLocReg() == X86::ST1) {
1539 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1540 // change the value to the FP stack register class.
1541 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1542 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1543 RetOps.push_back(ValToCopy);
1544 // Don't emit a copytoreg.
1548 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1549 // which is returned in RAX / RDX.
1550 if (Subtarget->is64Bit()) {
1551 if (ValVT == MVT::x86mmx) {
1552 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1553 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1554 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1556 // If we don't have SSE2 available, convert to v4f32 so the generated
1557 // register is legal.
1558 if (!Subtarget->hasSSE2())
1559 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1564 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1565 Flag = Chain.getValue(1);
1568 // The x86-64 ABI for returning structs by value requires that we copy
1569 // the sret argument into %rax for the return. We saved the argument into
1570 // a virtual register in the entry block, so now we copy the value out
1572 if (Subtarget->is64Bit() &&
1573 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1574 MachineFunction &MF = DAG.getMachineFunction();
1575 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1576 unsigned Reg = FuncInfo->getSRetReturnReg();
1578 "SRetReturnReg should have been set in LowerFormalArguments().");
1579 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1581 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1582 Flag = Chain.getValue(1);
1584 // RAX now acts like a return value.
1585 MRI.addLiveOut(X86::RAX);
1588 RetOps[0] = Chain; // Update chain.
1590 // Add the flag if we have it.
1592 RetOps.push_back(Flag);
1594 return DAG.getNode(X86ISD::RET_FLAG, dl,
1595 MVT::Other, &RetOps[0], RetOps.size());
1598 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1599 if (N->getNumValues() != 1)
1601 if (!N->hasNUsesOfValue(1, 0))
1604 SDValue TCChain = Chain;
1605 SDNode *Copy = *N->use_begin();
1606 if (Copy->getOpcode() == ISD::CopyToReg) {
1607 // If the copy has a glue operand, we conservatively assume it isn't safe to
1608 // perform a tail call.
1609 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1611 TCChain = Copy->getOperand(0);
1612 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1615 bool HasRet = false;
1616 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1618 if (UI->getOpcode() != X86ISD::RET_FLAG)
1631 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1632 ISD::NodeType ExtendKind) const {
1634 // TODO: Is this also valid on 32-bit?
1635 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1636 ReturnMVT = MVT::i8;
1638 ReturnMVT = MVT::i32;
1640 EVT MinVT = getRegisterType(Context, ReturnMVT);
1641 return VT.bitsLT(MinVT) ? MinVT : VT;
1644 /// LowerCallResult - Lower the result values of a call into the
1645 /// appropriate copies out of appropriate physical registers.
1648 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1649 CallingConv::ID CallConv, bool isVarArg,
1650 const SmallVectorImpl<ISD::InputArg> &Ins,
1651 DebugLoc dl, SelectionDAG &DAG,
1652 SmallVectorImpl<SDValue> &InVals) const {
1654 // Assign locations to each value returned by this call.
1655 SmallVector<CCValAssign, 16> RVLocs;
1656 bool Is64Bit = Subtarget->is64Bit();
1657 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1658 getTargetMachine(), RVLocs, *DAG.getContext());
1659 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1661 // Copy all of the result registers out of their specified physreg.
1662 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1663 CCValAssign &VA = RVLocs[i];
1664 EVT CopyVT = VA.getValVT();
1666 // If this is x86-64, and we disabled SSE, we can't return FP values
1667 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1668 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1669 report_fatal_error("SSE register return with SSE disabled");
1674 // If this is a call to a function that returns an fp value on the floating
1675 // point stack, we must guarantee the the value is popped from the stack, so
1676 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1677 // if the return value is not used. We use the FpPOP_RETVAL instruction
1679 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1680 // If we prefer to use the value in xmm registers, copy it out as f80 and
1681 // use a truncate to move it from fp stack reg to xmm reg.
1682 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1683 SDValue Ops[] = { Chain, InFlag };
1684 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1685 MVT::Other, MVT::Glue, Ops, 2), 1);
1686 Val = Chain.getValue(0);
1688 // Round the f80 to the right size, which also moves it to the appropriate
1690 if (CopyVT != VA.getValVT())
1691 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1692 // This truncation won't change the value.
1693 DAG.getIntPtrConstant(1));
1695 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1696 CopyVT, InFlag).getValue(1);
1697 Val = Chain.getValue(0);
1699 InFlag = Chain.getValue(2);
1700 InVals.push_back(Val);
1707 //===----------------------------------------------------------------------===//
1708 // C & StdCall & Fast Calling Convention implementation
1709 //===----------------------------------------------------------------------===//
1710 // StdCall calling convention seems to be standard for many Windows' API
1711 // routines and around. It differs from C calling convention just a little:
1712 // callee should clean up the stack, not caller. Symbols should be also
1713 // decorated in some fancy way :) It doesn't support any vector arguments.
1714 // For info on fast calling convention see Fast Calling Convention (tail call)
1715 // implementation LowerX86_32FastCCCallTo.
1717 /// CallIsStructReturn - Determines whether a call uses struct return
1719 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1723 return Outs[0].Flags.isSRet();
1726 /// ArgsAreStructReturn - Determines whether a function uses struct
1727 /// return semantics.
1729 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1733 return Ins[0].Flags.isSRet();
1736 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1737 /// by "Src" to address "Dst" with size and alignment information specified by
1738 /// the specific parameter attribute. The copy will be passed as a byval
1739 /// function parameter.
1741 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1742 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1744 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1746 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1747 /*isVolatile*/false, /*AlwaysInline=*/true,
1748 MachinePointerInfo(), MachinePointerInfo());
1751 /// IsTailCallConvention - Return true if the calling convention is one that
1752 /// supports tail call optimization.
1753 static bool IsTailCallConvention(CallingConv::ID CC) {
1754 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1757 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1758 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1762 CallingConv::ID CalleeCC = CS.getCallingConv();
1763 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1769 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1770 /// a tailcall target by changing its ABI.
1771 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1772 bool GuaranteedTailCallOpt) {
1773 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1777 X86TargetLowering::LowerMemArgument(SDValue Chain,
1778 CallingConv::ID CallConv,
1779 const SmallVectorImpl<ISD::InputArg> &Ins,
1780 DebugLoc dl, SelectionDAG &DAG,
1781 const CCValAssign &VA,
1782 MachineFrameInfo *MFI,
1784 // Create the nodes corresponding to a load from this parameter slot.
1785 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1786 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1787 getTargetMachine().Options.GuaranteedTailCallOpt);
1788 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1791 // If value is passed by pointer we have address passed instead of the value
1793 if (VA.getLocInfo() == CCValAssign::Indirect)
1794 ValVT = VA.getLocVT();
1796 ValVT = VA.getValVT();
1798 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1799 // changed with more analysis.
1800 // In case of tail call optimization mark all arguments mutable. Since they
1801 // could be overwritten by lowering of arguments in case of a tail call.
1802 if (Flags.isByVal()) {
1803 unsigned Bytes = Flags.getByValSize();
1804 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1805 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1806 return DAG.getFrameIndex(FI, getPointerTy());
1808 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1809 VA.getLocMemOffset(), isImmutable);
1810 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1811 return DAG.getLoad(ValVT, dl, Chain, FIN,
1812 MachinePointerInfo::getFixedStack(FI),
1813 false, false, false, 0);
1818 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1819 CallingConv::ID CallConv,
1821 const SmallVectorImpl<ISD::InputArg> &Ins,
1824 SmallVectorImpl<SDValue> &InVals)
1826 MachineFunction &MF = DAG.getMachineFunction();
1827 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1829 const Function* Fn = MF.getFunction();
1830 if (Fn->hasExternalLinkage() &&
1831 Subtarget->isTargetCygMing() &&
1832 Fn->getName() == "main")
1833 FuncInfo->setForceFramePointer(true);
1835 MachineFrameInfo *MFI = MF.getFrameInfo();
1836 bool Is64Bit = Subtarget->is64Bit();
1837 bool IsWindows = Subtarget->isTargetWindows();
1838 bool IsWin64 = Subtarget->isTargetWin64();
1840 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1841 "Var args not supported with calling convention fastcc or ghc");
1843 // Assign locations to all of the incoming arguments.
1844 SmallVector<CCValAssign, 16> ArgLocs;
1845 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1846 ArgLocs, *DAG.getContext());
1848 // Allocate shadow area for Win64
1850 CCInfo.AllocateStack(32, 8);
1853 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1855 unsigned LastVal = ~0U;
1857 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1858 CCValAssign &VA = ArgLocs[i];
1859 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1861 assert(VA.getValNo() != LastVal &&
1862 "Don't support value assigned to multiple locs yet");
1864 LastVal = VA.getValNo();
1866 if (VA.isRegLoc()) {
1867 EVT RegVT = VA.getLocVT();
1868 const TargetRegisterClass *RC;
1869 if (RegVT == MVT::i32)
1870 RC = &X86::GR32RegClass;
1871 else if (Is64Bit && RegVT == MVT::i64)
1872 RC = &X86::GR64RegClass;
1873 else if (RegVT == MVT::f32)
1874 RC = &X86::FR32RegClass;
1875 else if (RegVT == MVT::f64)
1876 RC = &X86::FR64RegClass;
1877 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1878 RC = &X86::VR256RegClass;
1879 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1880 RC = &X86::VR128RegClass;
1881 else if (RegVT == MVT::x86mmx)
1882 RC = &X86::VR64RegClass;
1884 llvm_unreachable("Unknown argument type!");
1886 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1887 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1889 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1890 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1892 if (VA.getLocInfo() == CCValAssign::SExt)
1893 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1894 DAG.getValueType(VA.getValVT()));
1895 else if (VA.getLocInfo() == CCValAssign::ZExt)
1896 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1897 DAG.getValueType(VA.getValVT()));
1898 else if (VA.getLocInfo() == CCValAssign::BCvt)
1899 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1901 if (VA.isExtInLoc()) {
1902 // Handle MMX values passed in XMM regs.
1903 if (RegVT.isVector()) {
1904 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1907 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1910 assert(VA.isMemLoc());
1911 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1914 // If value is passed via pointer - do a load.
1915 if (VA.getLocInfo() == CCValAssign::Indirect)
1916 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1917 MachinePointerInfo(), false, false, false, 0);
1919 InVals.push_back(ArgValue);
1922 // The x86-64 ABI for returning structs by value requires that we copy
1923 // the sret argument into %rax for the return. Save the argument into
1924 // a virtual register so that we can access it from the return points.
1925 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1926 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1927 unsigned Reg = FuncInfo->getSRetReturnReg();
1929 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1930 FuncInfo->setSRetReturnReg(Reg);
1932 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1933 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1936 unsigned StackSize = CCInfo.getNextStackOffset();
1937 // Align stack specially for tail calls.
1938 if (FuncIsMadeTailCallSafe(CallConv,
1939 MF.getTarget().Options.GuaranteedTailCallOpt))
1940 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1942 // If the function takes variable number of arguments, make a frame index for
1943 // the start of the first vararg value... for expansion of llvm.va_start.
1945 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1946 CallConv != CallingConv::X86_ThisCall)) {
1947 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1950 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1952 // FIXME: We should really autogenerate these arrays
1953 static const uint16_t GPR64ArgRegsWin64[] = {
1954 X86::RCX, X86::RDX, X86::R8, X86::R9
1956 static const uint16_t GPR64ArgRegs64Bit[] = {
1957 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1959 static const uint16_t XMMArgRegs64Bit[] = {
1960 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1961 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1963 const uint16_t *GPR64ArgRegs;
1964 unsigned NumXMMRegs = 0;
1967 // The XMM registers which might contain var arg parameters are shadowed
1968 // in their paired GPR. So we only need to save the GPR to their home
1970 TotalNumIntRegs = 4;
1971 GPR64ArgRegs = GPR64ArgRegsWin64;
1973 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1974 GPR64ArgRegs = GPR64ArgRegs64Bit;
1976 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1979 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1982 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1983 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1984 "SSE register cannot be used when SSE is disabled!");
1985 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1986 NoImplicitFloatOps) &&
1987 "SSE register cannot be used when SSE is disabled!");
1988 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1989 !Subtarget->hasSSE1())
1990 // Kernel mode asks for SSE to be disabled, so don't push them
1992 TotalNumXMMRegs = 0;
1995 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1996 // Get to the caller-allocated home save location. Add 8 to account
1997 // for the return address.
1998 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1999 FuncInfo->setRegSaveFrameIndex(
2000 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2001 // Fixup to set vararg frame on shadow area (4 x i64).
2003 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2005 // For X86-64, if there are vararg parameters that are passed via
2006 // registers, then we must store them to their spots on the stack so
2007 // they may be loaded by deferencing the result of va_next.
2008 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2009 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2010 FuncInfo->setRegSaveFrameIndex(
2011 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2015 // Store the integer parameter registers.
2016 SmallVector<SDValue, 8> MemOps;
2017 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2019 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2020 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2021 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2022 DAG.getIntPtrConstant(Offset));
2023 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2024 &X86::GR64RegClass);
2025 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2027 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2028 MachinePointerInfo::getFixedStack(
2029 FuncInfo->getRegSaveFrameIndex(), Offset),
2031 MemOps.push_back(Store);
2035 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2036 // Now store the XMM (fp + vector) parameter registers.
2037 SmallVector<SDValue, 11> SaveXMMOps;
2038 SaveXMMOps.push_back(Chain);
2040 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2041 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2042 SaveXMMOps.push_back(ALVal);
2044 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2045 FuncInfo->getRegSaveFrameIndex()));
2046 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2047 FuncInfo->getVarArgsFPOffset()));
2049 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2050 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2051 &X86::VR128RegClass);
2052 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2053 SaveXMMOps.push_back(Val);
2055 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2057 &SaveXMMOps[0], SaveXMMOps.size()));
2060 if (!MemOps.empty())
2061 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2062 &MemOps[0], MemOps.size());
2066 // Some CCs need callee pop.
2067 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2068 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2069 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2071 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2072 // If this is an sret function, the return should pop the hidden pointer.
2073 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2074 ArgsAreStructReturn(Ins))
2075 FuncInfo->setBytesToPopOnReturn(4);
2079 // RegSaveFrameIndex is X86-64 only.
2080 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2081 if (CallConv == CallingConv::X86_FastCall ||
2082 CallConv == CallingConv::X86_ThisCall)
2083 // fastcc functions can't have varargs.
2084 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2087 FuncInfo->setArgumentStackSize(StackSize);
2093 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2094 SDValue StackPtr, SDValue Arg,
2095 DebugLoc dl, SelectionDAG &DAG,
2096 const CCValAssign &VA,
2097 ISD::ArgFlagsTy Flags) const {
2098 unsigned LocMemOffset = VA.getLocMemOffset();
2099 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2100 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2101 if (Flags.isByVal())
2102 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2104 return DAG.getStore(Chain, dl, Arg, PtrOff,
2105 MachinePointerInfo::getStack(LocMemOffset),
2109 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2110 /// optimization is performed and it is required.
2112 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2113 SDValue &OutRetAddr, SDValue Chain,
2114 bool IsTailCall, bool Is64Bit,
2115 int FPDiff, DebugLoc dl) const {
2116 // Adjust the Return address stack slot.
2117 EVT VT = getPointerTy();
2118 OutRetAddr = getReturnAddressFrameIndex(DAG);
2120 // Load the "old" Return address.
2121 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2122 false, false, false, 0);
2123 return SDValue(OutRetAddr.getNode(), 1);
2126 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2127 /// optimization is performed and it is required (FPDiff!=0).
2129 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2130 SDValue Chain, SDValue RetAddrFrIdx,
2131 bool Is64Bit, int FPDiff, DebugLoc dl) {
2132 // Store the return address to the appropriate stack slot.
2133 if (!FPDiff) return Chain;
2134 // Calculate the new stack slot for the return address.
2135 int SlotSize = Is64Bit ? 8 : 4;
2136 int NewReturnAddrFI =
2137 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2138 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2139 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2140 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2141 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2147 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2148 SmallVectorImpl<SDValue> &InVals) const {
2149 SelectionDAG &DAG = CLI.DAG;
2150 DebugLoc &dl = CLI.DL;
2151 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2152 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2153 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2154 SDValue Chain = CLI.Chain;
2155 SDValue Callee = CLI.Callee;
2156 CallingConv::ID CallConv = CLI.CallConv;
2157 bool &isTailCall = CLI.IsTailCall;
2158 bool isVarArg = CLI.IsVarArg;
2160 MachineFunction &MF = DAG.getMachineFunction();
2161 bool Is64Bit = Subtarget->is64Bit();
2162 bool IsWin64 = Subtarget->isTargetWin64();
2163 bool IsWindows = Subtarget->isTargetWindows();
2164 bool IsStructRet = CallIsStructReturn(Outs);
2165 bool IsSibcall = false;
2167 if (MF.getTarget().Options.DisableTailCalls)
2171 // Check if it's really possible to do a tail call.
2172 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2173 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2174 Outs, OutVals, Ins, DAG);
2176 // Sibcalls are automatically detected tailcalls which do not require
2178 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2185 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2186 "Var args not supported with calling convention fastcc or ghc");
2188 // Analyze operands of the call, assigning locations to each operand.
2189 SmallVector<CCValAssign, 16> ArgLocs;
2190 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2191 ArgLocs, *DAG.getContext());
2193 // Allocate shadow area for Win64
2195 CCInfo.AllocateStack(32, 8);
2198 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2200 // Get a count of how many bytes are to be pushed on the stack.
2201 unsigned NumBytes = CCInfo.getNextStackOffset();
2203 // This is a sibcall. The memory operands are available in caller's
2204 // own caller's stack.
2206 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2207 IsTailCallConvention(CallConv))
2208 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2211 if (isTailCall && !IsSibcall) {
2212 // Lower arguments at fp - stackoffset + fpdiff.
2213 unsigned NumBytesCallerPushed =
2214 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2215 FPDiff = NumBytesCallerPushed - NumBytes;
2217 // Set the delta of movement of the returnaddr stackslot.
2218 // But only set if delta is greater than previous delta.
2219 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2220 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2224 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2226 SDValue RetAddrFrIdx;
2227 // Load return address for tail calls.
2228 if (isTailCall && FPDiff)
2229 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2230 Is64Bit, FPDiff, dl);
2232 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2233 SmallVector<SDValue, 8> MemOpChains;
2236 // Walk the register/memloc assignments, inserting copies/loads. In the case
2237 // of tail call optimization arguments are handle later.
2238 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2239 CCValAssign &VA = ArgLocs[i];
2240 EVT RegVT = VA.getLocVT();
2241 SDValue Arg = OutVals[i];
2242 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2243 bool isByVal = Flags.isByVal();
2245 // Promote the value if needed.
2246 switch (VA.getLocInfo()) {
2247 default: llvm_unreachable("Unknown loc info!");
2248 case CCValAssign::Full: break;
2249 case CCValAssign::SExt:
2250 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2252 case CCValAssign::ZExt:
2253 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2255 case CCValAssign::AExt:
2256 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2257 // Special case: passing MMX values in XMM registers.
2258 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2259 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2260 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2262 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2264 case CCValAssign::BCvt:
2265 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2267 case CCValAssign::Indirect: {
2268 // Store the argument.
2269 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2270 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2271 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2272 MachinePointerInfo::getFixedStack(FI),
2279 if (VA.isRegLoc()) {
2280 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2281 if (isVarArg && IsWin64) {
2282 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2283 // shadow reg if callee is a varargs function.
2284 unsigned ShadowReg = 0;
2285 switch (VA.getLocReg()) {
2286 case X86::XMM0: ShadowReg = X86::RCX; break;
2287 case X86::XMM1: ShadowReg = X86::RDX; break;
2288 case X86::XMM2: ShadowReg = X86::R8; break;
2289 case X86::XMM3: ShadowReg = X86::R9; break;
2292 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2294 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2295 assert(VA.isMemLoc());
2296 if (StackPtr.getNode() == 0)
2297 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2298 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2299 dl, DAG, VA, Flags));
2303 if (!MemOpChains.empty())
2304 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2305 &MemOpChains[0], MemOpChains.size());
2307 if (Subtarget->isPICStyleGOT()) {
2308 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2311 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2312 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2314 // If we are tail calling and generating PIC/GOT style code load the
2315 // address of the callee into ECX. The value in ecx is used as target of
2316 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2317 // for tail calls on PIC/GOT architectures. Normally we would just put the
2318 // address of GOT into ebx and then call target@PLT. But for tail calls
2319 // ebx would be restored (since ebx is callee saved) before jumping to the
2322 // Note: The actual moving to ECX is done further down.
2323 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2324 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2325 !G->getGlobal()->hasProtectedVisibility())
2326 Callee = LowerGlobalAddress(Callee, DAG);
2327 else if (isa<ExternalSymbolSDNode>(Callee))
2328 Callee = LowerExternalSymbol(Callee, DAG);
2332 if (Is64Bit && isVarArg && !IsWin64) {
2333 // From AMD64 ABI document:
2334 // For calls that may call functions that use varargs or stdargs
2335 // (prototype-less calls or calls to functions containing ellipsis (...) in
2336 // the declaration) %al is used as hidden argument to specify the number
2337 // of SSE registers used. The contents of %al do not need to match exactly
2338 // the number of registers, but must be an ubound on the number of SSE
2339 // registers used and is in the range 0 - 8 inclusive.
2341 // Count the number of XMM registers allocated.
2342 static const uint16_t XMMArgRegs[] = {
2343 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2344 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2346 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2347 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2348 && "SSE registers cannot be used when SSE is disabled");
2350 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2351 DAG.getConstant(NumXMMRegs, MVT::i8)));
2354 // For tail calls lower the arguments to the 'real' stack slot.
2356 // Force all the incoming stack arguments to be loaded from the stack
2357 // before any new outgoing arguments are stored to the stack, because the
2358 // outgoing stack slots may alias the incoming argument stack slots, and
2359 // the alias isn't otherwise explicit. This is slightly more conservative
2360 // than necessary, because it means that each store effectively depends
2361 // on every argument instead of just those arguments it would clobber.
2362 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2364 SmallVector<SDValue, 8> MemOpChains2;
2367 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2368 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2369 CCValAssign &VA = ArgLocs[i];
2372 assert(VA.isMemLoc());
2373 SDValue Arg = OutVals[i];
2374 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2375 // Create frame index.
2376 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2377 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2378 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2379 FIN = DAG.getFrameIndex(FI, getPointerTy());
2381 if (Flags.isByVal()) {
2382 // Copy relative to framepointer.
2383 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2384 if (StackPtr.getNode() == 0)
2385 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2387 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2389 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2393 // Store relative to framepointer.
2394 MemOpChains2.push_back(
2395 DAG.getStore(ArgChain, dl, Arg, FIN,
2396 MachinePointerInfo::getFixedStack(FI),
2402 if (!MemOpChains2.empty())
2403 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2404 &MemOpChains2[0], MemOpChains2.size());
2406 // Store the return address to the appropriate stack slot.
2407 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2411 // Build a sequence of copy-to-reg nodes chained together with token chain
2412 // and flag operands which copy the outgoing args into registers.
2414 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2415 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2416 RegsToPass[i].second, InFlag);
2417 InFlag = Chain.getValue(1);
2420 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2421 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2422 // In the 64-bit large code model, we have to make all calls
2423 // through a register, since the call instruction's 32-bit
2424 // pc-relative offset may not be large enough to hold the whole
2426 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2427 // If the callee is a GlobalAddress node (quite common, every direct call
2428 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2431 // We should use extra load for direct calls to dllimported functions in
2433 const GlobalValue *GV = G->getGlobal();
2434 if (!GV->hasDLLImportLinkage()) {
2435 unsigned char OpFlags = 0;
2436 bool ExtraLoad = false;
2437 unsigned WrapperKind = ISD::DELETED_NODE;
2439 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2440 // external symbols most go through the PLT in PIC mode. If the symbol
2441 // has hidden or protected visibility, or if it is static or local, then
2442 // we don't need to use the PLT - we can directly call it.
2443 if (Subtarget->isTargetELF() &&
2444 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2445 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2446 OpFlags = X86II::MO_PLT;
2447 } else if (Subtarget->isPICStyleStubAny() &&
2448 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2449 (!Subtarget->getTargetTriple().isMacOSX() ||
2450 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2451 // PC-relative references to external symbols should go through $stub,
2452 // unless we're building with the leopard linker or later, which
2453 // automatically synthesizes these stubs.
2454 OpFlags = X86II::MO_DARWIN_STUB;
2455 } else if (Subtarget->isPICStyleRIPRel() &&
2456 isa<Function>(GV) &&
2457 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2458 // If the function is marked as non-lazy, generate an indirect call
2459 // which loads from the GOT directly. This avoids runtime overhead
2460 // at the cost of eager binding (and one extra byte of encoding).
2461 OpFlags = X86II::MO_GOTPCREL;
2462 WrapperKind = X86ISD::WrapperRIP;
2466 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2467 G->getOffset(), OpFlags);
2469 // Add a wrapper if needed.
2470 if (WrapperKind != ISD::DELETED_NODE)
2471 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2472 // Add extra indirection if needed.
2474 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2475 MachinePointerInfo::getGOT(),
2476 false, false, false, 0);
2478 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2479 unsigned char OpFlags = 0;
2481 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2482 // external symbols should go through the PLT.
2483 if (Subtarget->isTargetELF() &&
2484 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2485 OpFlags = X86II::MO_PLT;
2486 } else if (Subtarget->isPICStyleStubAny() &&
2487 (!Subtarget->getTargetTriple().isMacOSX() ||
2488 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2489 // PC-relative references to external symbols should go through $stub,
2490 // unless we're building with the leopard linker or later, which
2491 // automatically synthesizes these stubs.
2492 OpFlags = X86II::MO_DARWIN_STUB;
2495 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2499 // Returns a chain & a flag for retval copy to use.
2500 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2501 SmallVector<SDValue, 8> Ops;
2503 if (!IsSibcall && isTailCall) {
2504 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2505 DAG.getIntPtrConstant(0, true), InFlag);
2506 InFlag = Chain.getValue(1);
2509 Ops.push_back(Chain);
2510 Ops.push_back(Callee);
2513 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2515 // Add argument registers to the end of the list so that they are known live
2517 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2518 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2519 RegsToPass[i].second.getValueType()));
2521 // Add a register mask operand representing the call-preserved registers.
2522 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2523 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2524 assert(Mask && "Missing call preserved mask for calling convention");
2525 Ops.push_back(DAG.getRegisterMask(Mask));
2527 if (InFlag.getNode())
2528 Ops.push_back(InFlag);
2532 //// If this is the first return lowered for this function, add the regs
2533 //// to the liveout set for the function.
2534 // This isn't right, although it's probably harmless on x86; liveouts
2535 // should be computed from returns not tail calls. Consider a void
2536 // function making a tail call to a function returning int.
2537 return DAG.getNode(X86ISD::TC_RETURN, dl,
2538 NodeTys, &Ops[0], Ops.size());
2541 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2542 InFlag = Chain.getValue(1);
2544 // Create the CALLSEQ_END node.
2545 unsigned NumBytesForCalleeToPush;
2546 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2547 getTargetMachine().Options.GuaranteedTailCallOpt))
2548 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2549 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2551 // If this is a call to a struct-return function, the callee
2552 // pops the hidden struct pointer, so we have to push it back.
2553 // This is common for Darwin/X86, Linux & Mingw32 targets.
2554 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2555 NumBytesForCalleeToPush = 4;
2557 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2559 // Returns a flag for retval copy to use.
2561 Chain = DAG.getCALLSEQ_END(Chain,
2562 DAG.getIntPtrConstant(NumBytes, true),
2563 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2566 InFlag = Chain.getValue(1);
2569 // Handle result values, copying them out of physregs into vregs that we
2571 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2572 Ins, dl, DAG, InVals);
2576 //===----------------------------------------------------------------------===//
2577 // Fast Calling Convention (tail call) implementation
2578 //===----------------------------------------------------------------------===//
2580 // Like std call, callee cleans arguments, convention except that ECX is
2581 // reserved for storing the tail called function address. Only 2 registers are
2582 // free for argument passing (inreg). Tail call optimization is performed
2584 // * tailcallopt is enabled
2585 // * caller/callee are fastcc
2586 // On X86_64 architecture with GOT-style position independent code only local
2587 // (within module) calls are supported at the moment.
2588 // To keep the stack aligned according to platform abi the function
2589 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2590 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2591 // If a tail called function callee has more arguments than the caller the
2592 // caller needs to make sure that there is room to move the RETADDR to. This is
2593 // achieved by reserving an area the size of the argument delta right after the
2594 // original REtADDR, but before the saved framepointer or the spilled registers
2595 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2607 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2608 /// for a 16 byte align requirement.
2610 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2611 SelectionDAG& DAG) const {
2612 MachineFunction &MF = DAG.getMachineFunction();
2613 const TargetMachine &TM = MF.getTarget();
2614 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2615 unsigned StackAlignment = TFI.getStackAlignment();
2616 uint64_t AlignMask = StackAlignment - 1;
2617 int64_t Offset = StackSize;
2618 uint64_t SlotSize = TD->getPointerSize();
2619 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2620 // Number smaller than 12 so just add the difference.
2621 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2623 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2624 Offset = ((~AlignMask) & Offset) + StackAlignment +
2625 (StackAlignment-SlotSize);
2630 /// MatchingStackOffset - Return true if the given stack call argument is
2631 /// already available in the same position (relatively) of the caller's
2632 /// incoming argument stack.
2634 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2635 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2636 const X86InstrInfo *TII) {
2637 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2639 if (Arg.getOpcode() == ISD::CopyFromReg) {
2640 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2641 if (!TargetRegisterInfo::isVirtualRegister(VR))
2643 MachineInstr *Def = MRI->getVRegDef(VR);
2646 if (!Flags.isByVal()) {
2647 if (!TII->isLoadFromStackSlot(Def, FI))
2650 unsigned Opcode = Def->getOpcode();
2651 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2652 Def->getOperand(1).isFI()) {
2653 FI = Def->getOperand(1).getIndex();
2654 Bytes = Flags.getByValSize();
2658 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2659 if (Flags.isByVal())
2660 // ByVal argument is passed in as a pointer but it's now being
2661 // dereferenced. e.g.
2662 // define @foo(%struct.X* %A) {
2663 // tail call @bar(%struct.X* byval %A)
2666 SDValue Ptr = Ld->getBasePtr();
2667 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2670 FI = FINode->getIndex();
2671 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2672 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2673 FI = FINode->getIndex();
2674 Bytes = Flags.getByValSize();
2678 assert(FI != INT_MAX);
2679 if (!MFI->isFixedObjectIndex(FI))
2681 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2684 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2685 /// for tail call optimization. Targets which want to do tail call
2686 /// optimization should implement this function.
2688 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2689 CallingConv::ID CalleeCC,
2691 bool isCalleeStructRet,
2692 bool isCallerStructRet,
2693 const SmallVectorImpl<ISD::OutputArg> &Outs,
2694 const SmallVectorImpl<SDValue> &OutVals,
2695 const SmallVectorImpl<ISD::InputArg> &Ins,
2696 SelectionDAG& DAG) const {
2697 if (!IsTailCallConvention(CalleeCC) &&
2698 CalleeCC != CallingConv::C)
2701 // If -tailcallopt is specified, make fastcc functions tail-callable.
2702 const MachineFunction &MF = DAG.getMachineFunction();
2703 const Function *CallerF = DAG.getMachineFunction().getFunction();
2704 CallingConv::ID CallerCC = CallerF->getCallingConv();
2705 bool CCMatch = CallerCC == CalleeCC;
2707 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2708 if (IsTailCallConvention(CalleeCC) && CCMatch)
2713 // Look for obvious safe cases to perform tail call optimization that do not
2714 // require ABI changes. This is what gcc calls sibcall.
2716 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2717 // emit a special epilogue.
2718 if (RegInfo->needsStackRealignment(MF))
2721 // Also avoid sibcall optimization if either caller or callee uses struct
2722 // return semantics.
2723 if (isCalleeStructRet || isCallerStructRet)
2726 // An stdcall caller is expected to clean up its arguments; the callee
2727 // isn't going to do that.
2728 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2731 // Do not sibcall optimize vararg calls unless all arguments are passed via
2733 if (isVarArg && !Outs.empty()) {
2735 // Optimizing for varargs on Win64 is unlikely to be safe without
2736 // additional testing.
2737 if (Subtarget->isTargetWin64())
2740 SmallVector<CCValAssign, 16> ArgLocs;
2741 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2742 getTargetMachine(), ArgLocs, *DAG.getContext());
2744 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2745 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2746 if (!ArgLocs[i].isRegLoc())
2750 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2751 // stack. Therefore, if it's not used by the call it is not safe to optimize
2752 // this into a sibcall.
2753 bool Unused = false;
2754 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2761 SmallVector<CCValAssign, 16> RVLocs;
2762 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2763 getTargetMachine(), RVLocs, *DAG.getContext());
2764 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2765 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2766 CCValAssign &VA = RVLocs[i];
2767 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2772 // If the calling conventions do not match, then we'd better make sure the
2773 // results are returned in the same way as what the caller expects.
2775 SmallVector<CCValAssign, 16> RVLocs1;
2776 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2777 getTargetMachine(), RVLocs1, *DAG.getContext());
2778 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2780 SmallVector<CCValAssign, 16> RVLocs2;
2781 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2782 getTargetMachine(), RVLocs2, *DAG.getContext());
2783 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2785 if (RVLocs1.size() != RVLocs2.size())
2787 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2788 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2790 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2792 if (RVLocs1[i].isRegLoc()) {
2793 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2796 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2802 // If the callee takes no arguments then go on to check the results of the
2804 if (!Outs.empty()) {
2805 // Check if stack adjustment is needed. For now, do not do this if any
2806 // argument is passed on the stack.
2807 SmallVector<CCValAssign, 16> ArgLocs;
2808 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2809 getTargetMachine(), ArgLocs, *DAG.getContext());
2811 // Allocate shadow area for Win64
2812 if (Subtarget->isTargetWin64()) {
2813 CCInfo.AllocateStack(32, 8);
2816 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2817 if (CCInfo.getNextStackOffset()) {
2818 MachineFunction &MF = DAG.getMachineFunction();
2819 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2822 // Check if the arguments are already laid out in the right way as
2823 // the caller's fixed stack objects.
2824 MachineFrameInfo *MFI = MF.getFrameInfo();
2825 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2826 const X86InstrInfo *TII =
2827 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2828 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2829 CCValAssign &VA = ArgLocs[i];
2830 SDValue Arg = OutVals[i];
2831 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2832 if (VA.getLocInfo() == CCValAssign::Indirect)
2834 if (!VA.isRegLoc()) {
2835 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2842 // If the tailcall address may be in a register, then make sure it's
2843 // possible to register allocate for it. In 32-bit, the call address can
2844 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2845 // callee-saved registers are restored. These happen to be the same
2846 // registers used to pass 'inreg' arguments so watch out for those.
2847 if (!Subtarget->is64Bit() &&
2848 !isa<GlobalAddressSDNode>(Callee) &&
2849 !isa<ExternalSymbolSDNode>(Callee)) {
2850 unsigned NumInRegs = 0;
2851 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2852 CCValAssign &VA = ArgLocs[i];
2855 unsigned Reg = VA.getLocReg();
2858 case X86::EAX: case X86::EDX: case X86::ECX:
2859 if (++NumInRegs == 3)
2871 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2872 return X86::createFastISel(funcInfo);
2876 //===----------------------------------------------------------------------===//
2877 // Other Lowering Hooks
2878 //===----------------------------------------------------------------------===//
2880 static bool MayFoldLoad(SDValue Op) {
2881 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2884 static bool MayFoldIntoStore(SDValue Op) {
2885 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2888 static bool isTargetShuffle(unsigned Opcode) {
2890 default: return false;
2891 case X86ISD::PSHUFD:
2892 case X86ISD::PSHUFHW:
2893 case X86ISD::PSHUFLW:
2895 case X86ISD::PALIGN:
2896 case X86ISD::MOVLHPS:
2897 case X86ISD::MOVLHPD:
2898 case X86ISD::MOVHLPS:
2899 case X86ISD::MOVLPS:
2900 case X86ISD::MOVLPD:
2901 case X86ISD::MOVSHDUP:
2902 case X86ISD::MOVSLDUP:
2903 case X86ISD::MOVDDUP:
2906 case X86ISD::UNPCKL:
2907 case X86ISD::UNPCKH:
2908 case X86ISD::VPERMILP:
2909 case X86ISD::VPERM2X128:
2910 case X86ISD::VPERMI:
2915 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2916 SDValue V1, SelectionDAG &DAG) {
2918 default: llvm_unreachable("Unknown x86 shuffle node");
2919 case X86ISD::MOVSHDUP:
2920 case X86ISD::MOVSLDUP:
2921 case X86ISD::MOVDDUP:
2922 return DAG.getNode(Opc, dl, VT, V1);
2926 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2927 SDValue V1, unsigned TargetMask,
2928 SelectionDAG &DAG) {
2930 default: llvm_unreachable("Unknown x86 shuffle node");
2931 case X86ISD::PSHUFD:
2932 case X86ISD::PSHUFHW:
2933 case X86ISD::PSHUFLW:
2934 case X86ISD::VPERMILP:
2935 case X86ISD::VPERMI:
2936 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2940 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2941 SDValue V1, SDValue V2, unsigned TargetMask,
2942 SelectionDAG &DAG) {
2944 default: llvm_unreachable("Unknown x86 shuffle node");
2945 case X86ISD::PALIGN:
2947 case X86ISD::VPERM2X128:
2948 return DAG.getNode(Opc, dl, VT, V1, V2,
2949 DAG.getConstant(TargetMask, MVT::i8));
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2956 default: llvm_unreachable("Unknown x86 shuffle node");
2957 case X86ISD::MOVLHPS:
2958 case X86ISD::MOVLHPD:
2959 case X86ISD::MOVHLPS:
2960 case X86ISD::MOVLPS:
2961 case X86ISD::MOVLPD:
2964 case X86ISD::UNPCKL:
2965 case X86ISD::UNPCKH:
2966 return DAG.getNode(Opc, dl, VT, V1, V2);
2970 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2971 MachineFunction &MF = DAG.getMachineFunction();
2972 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2973 int ReturnAddrIndex = FuncInfo->getRAIndex();
2975 if (ReturnAddrIndex == 0) {
2976 // Set up a frame object for the return address.
2977 uint64_t SlotSize = TD->getPointerSize();
2978 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2980 FuncInfo->setRAIndex(ReturnAddrIndex);
2983 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2987 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2988 bool hasSymbolicDisplacement) {
2989 // Offset should fit into 32 bit immediate field.
2990 if (!isInt<32>(Offset))
2993 // If we don't have a symbolic displacement - we don't have any extra
2995 if (!hasSymbolicDisplacement)
2998 // FIXME: Some tweaks might be needed for medium code model.
2999 if (M != CodeModel::Small && M != CodeModel::Kernel)
3002 // For small code model we assume that latest object is 16MB before end of 31
3003 // bits boundary. We may also accept pretty large negative constants knowing
3004 // that all objects are in the positive half of address space.
3005 if (M == CodeModel::Small && Offset < 16*1024*1024)
3008 // For kernel code model we know that all object resist in the negative half
3009 // of 32bits address space. We may not accept negative offsets, since they may
3010 // be just off and we may accept pretty large positive ones.
3011 if (M == CodeModel::Kernel && Offset > 0)
3017 /// isCalleePop - Determines whether the callee is required to pop its
3018 /// own arguments. Callee pop is necessary to support tail calls.
3019 bool X86::isCalleePop(CallingConv::ID CallingConv,
3020 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3024 switch (CallingConv) {
3027 case CallingConv::X86_StdCall:
3029 case CallingConv::X86_FastCall:
3031 case CallingConv::X86_ThisCall:
3033 case CallingConv::Fast:
3035 case CallingConv::GHC:
3040 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3041 /// specific condition code, returning the condition code and the LHS/RHS of the
3042 /// comparison to make.
3043 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3044 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3046 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3047 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3048 // X > -1 -> X == 0, jump !sign.
3049 RHS = DAG.getConstant(0, RHS.getValueType());
3050 return X86::COND_NS;
3052 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3053 // X < 0 -> X == 0, jump on sign.
3056 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3058 RHS = DAG.getConstant(0, RHS.getValueType());
3059 return X86::COND_LE;
3063 switch (SetCCOpcode) {
3064 default: llvm_unreachable("Invalid integer condition!");
3065 case ISD::SETEQ: return X86::COND_E;
3066 case ISD::SETGT: return X86::COND_G;
3067 case ISD::SETGE: return X86::COND_GE;
3068 case ISD::SETLT: return X86::COND_L;
3069 case ISD::SETLE: return X86::COND_LE;
3070 case ISD::SETNE: return X86::COND_NE;
3071 case ISD::SETULT: return X86::COND_B;
3072 case ISD::SETUGT: return X86::COND_A;
3073 case ISD::SETULE: return X86::COND_BE;
3074 case ISD::SETUGE: return X86::COND_AE;
3078 // First determine if it is required or is profitable to flip the operands.
3080 // If LHS is a foldable load, but RHS is not, flip the condition.
3081 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3082 !ISD::isNON_EXTLoad(RHS.getNode())) {
3083 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3084 std::swap(LHS, RHS);
3087 switch (SetCCOpcode) {
3093 std::swap(LHS, RHS);
3097 // On a floating point condition, the flags are set as follows:
3099 // 0 | 0 | 0 | X > Y
3100 // 0 | 0 | 1 | X < Y
3101 // 1 | 0 | 0 | X == Y
3102 // 1 | 1 | 1 | unordered
3103 switch (SetCCOpcode) {
3104 default: llvm_unreachable("Condcode should be pre-legalized away");
3106 case ISD::SETEQ: return X86::COND_E;
3107 case ISD::SETOLT: // flipped
3109 case ISD::SETGT: return X86::COND_A;
3110 case ISD::SETOLE: // flipped
3112 case ISD::SETGE: return X86::COND_AE;
3113 case ISD::SETUGT: // flipped
3115 case ISD::SETLT: return X86::COND_B;
3116 case ISD::SETUGE: // flipped
3118 case ISD::SETLE: return X86::COND_BE;
3120 case ISD::SETNE: return X86::COND_NE;
3121 case ISD::SETUO: return X86::COND_P;
3122 case ISD::SETO: return X86::COND_NP;
3124 case ISD::SETUNE: return X86::COND_INVALID;
3128 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3129 /// code. Current x86 isa includes the following FP cmov instructions:
3130 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3131 static bool hasFPCMov(unsigned X86CC) {
3147 /// isFPImmLegal - Returns true if the target can instruction select the
3148 /// specified FP immediate natively. If false, the legalizer will
3149 /// materialize the FP immediate as a load from a constant pool.
3150 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3151 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3152 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3158 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3159 /// the specified range (L, H].
3160 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3161 return (Val < 0) || (Val >= Low && Val < Hi);
3164 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3165 /// specified value.
3166 static bool isUndefOrEqual(int Val, int CmpVal) {
3167 if (Val < 0 || Val == CmpVal)
3172 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3173 /// from position Pos and ending in Pos+Size, falls within the specified
3174 /// sequential range (L, L+Pos]. or is undef.
3175 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3176 unsigned Pos, unsigned Size, int Low) {
3177 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3178 if (!isUndefOrEqual(Mask[i], Low))
3183 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3184 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3185 /// the second operand.
3186 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3187 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3188 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3189 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3190 return (Mask[0] < 2 && Mask[1] < 2);
3194 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3195 /// is suitable for input to PSHUFHW.
3196 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3197 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3200 // Lower quadword copied in order or undef.
3201 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3204 // Upper quadword shuffled.
3205 for (unsigned i = 4; i != 8; ++i)
3206 if (!isUndefOrInRange(Mask[i], 4, 8))
3209 if (VT == MVT::v16i16) {
3210 // Lower quadword copied in order or undef.
3211 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3214 // Upper quadword shuffled.
3215 for (unsigned i = 12; i != 16; ++i)
3216 if (!isUndefOrInRange(Mask[i], 12, 16))
3223 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3224 /// is suitable for input to PSHUFLW.
3225 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3226 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3229 // Upper quadword copied in order.
3230 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3233 // Lower quadword shuffled.
3234 for (unsigned i = 0; i != 4; ++i)
3235 if (!isUndefOrInRange(Mask[i], 0, 4))
3238 if (VT == MVT::v16i16) {
3239 // Upper quadword copied in order.
3240 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3243 // Lower quadword shuffled.
3244 for (unsigned i = 8; i != 12; ++i)
3245 if (!isUndefOrInRange(Mask[i], 8, 12))
3252 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3253 /// is suitable for input to PALIGNR.
3254 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3255 const X86Subtarget *Subtarget) {
3256 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3257 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3260 unsigned NumElts = VT.getVectorNumElements();
3261 unsigned NumLanes = VT.getSizeInBits()/128;
3262 unsigned NumLaneElts = NumElts/NumLanes;
3264 // Do not handle 64-bit element shuffles with palignr.
3265 if (NumLaneElts == 2)
3268 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3270 for (i = 0; i != NumLaneElts; ++i) {
3275 // Lane is all undef, go to next lane
3276 if (i == NumLaneElts)
3279 int Start = Mask[i+l];
3281 // Make sure its in this lane in one of the sources
3282 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3283 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3286 // If not lane 0, then we must match lane 0
3287 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3290 // Correct second source to be contiguous with first source
3291 if (Start >= (int)NumElts)
3292 Start -= NumElts - NumLaneElts;
3294 // Make sure we're shifting in the right direction.
3295 if (Start <= (int)(i+l))
3300 // Check the rest of the elements to see if they are consecutive.
3301 for (++i; i != NumLaneElts; ++i) {
3302 int Idx = Mask[i+l];
3304 // Make sure its in this lane
3305 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3306 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3309 // If not lane 0, then we must match lane 0
3310 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3313 if (Idx >= (int)NumElts)
3314 Idx -= NumElts - NumLaneElts;
3316 if (!isUndefOrEqual(Idx, Start+i))
3325 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3326 /// the two vector operands have swapped position.
3327 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3328 unsigned NumElems) {
3329 for (unsigned i = 0; i != NumElems; ++i) {
3333 else if (idx < (int)NumElems)
3334 Mask[i] = idx + NumElems;
3336 Mask[i] = idx - NumElems;
3340 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3341 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3342 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3343 /// reverse of what x86 shuffles want.
3344 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3345 bool Commuted = false) {
3346 if (!HasAVX && VT.getSizeInBits() == 256)
3349 unsigned NumElems = VT.getVectorNumElements();
3350 unsigned NumLanes = VT.getSizeInBits()/128;
3351 unsigned NumLaneElems = NumElems/NumLanes;
3353 if (NumLaneElems != 2 && NumLaneElems != 4)
3356 // VSHUFPSY divides the resulting vector into 4 chunks.
3357 // The sources are also splitted into 4 chunks, and each destination
3358 // chunk must come from a different source chunk.
3360 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3361 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3363 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3364 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3366 // VSHUFPDY divides the resulting vector into 4 chunks.
3367 // The sources are also splitted into 4 chunks, and each destination
3368 // chunk must come from a different source chunk.
3370 // SRC1 => X3 X2 X1 X0
3371 // SRC2 => Y3 Y2 Y1 Y0
3373 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3375 unsigned HalfLaneElems = NumLaneElems/2;
3376 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3377 for (unsigned i = 0; i != NumLaneElems; ++i) {
3378 int Idx = Mask[i+l];
3379 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3380 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3382 // For VSHUFPSY, the mask of the second half must be the same as the
3383 // first but with the appropriate offsets. This works in the same way as
3384 // VPERMILPS works with masks.
3385 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3387 if (!isUndefOrEqual(Idx, Mask[i]+l))
3395 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3396 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3397 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3398 unsigned NumElems = VT.getVectorNumElements();
3400 if (VT.getSizeInBits() != 128)
3406 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3407 return isUndefOrEqual(Mask[0], 6) &&
3408 isUndefOrEqual(Mask[1], 7) &&
3409 isUndefOrEqual(Mask[2], 2) &&
3410 isUndefOrEqual(Mask[3], 3);
3413 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3414 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3416 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3417 unsigned NumElems = VT.getVectorNumElements();
3419 if (VT.getSizeInBits() != 128)
3425 return isUndefOrEqual(Mask[0], 2) &&
3426 isUndefOrEqual(Mask[1], 3) &&
3427 isUndefOrEqual(Mask[2], 2) &&
3428 isUndefOrEqual(Mask[3], 3);
3431 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3432 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3433 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3434 if (VT.getSizeInBits() != 128)
3437 unsigned NumElems = VT.getVectorNumElements();
3439 if (NumElems != 2 && NumElems != 4)
3442 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3443 if (!isUndefOrEqual(Mask[i], i + NumElems))
3446 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3447 if (!isUndefOrEqual(Mask[i], i))
3453 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3455 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3456 unsigned NumElems = VT.getVectorNumElements();
3458 if ((NumElems != 2 && NumElems != 4)
3459 || VT.getSizeInBits() > 128)
3462 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3463 if (!isUndefOrEqual(Mask[i], i))
3466 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3467 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3474 // Some special combinations that can be optimized.
3477 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3478 SelectionDAG &DAG) {
3479 EVT VT = SVOp->getValueType(0);
3480 DebugLoc dl = SVOp->getDebugLoc();
3482 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3485 ArrayRef<int> Mask = SVOp->getMask();
3487 // These are the special masks that may be optimized.
3488 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3489 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3490 bool MatchEvenMask = true;
3491 bool MatchOddMask = true;
3492 for (int i=0; i<8; ++i) {
3493 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3494 MatchEvenMask = false;
3495 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3496 MatchOddMask = false;
3498 static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3499 static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3501 const int *CompactionMask;
3503 CompactionMask = CompactionMaskEven;
3504 else if (MatchOddMask)
3505 CompactionMask = CompactionMaskOdd;
3509 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3511 SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3512 UndefNode, CompactionMask);
3513 SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3514 UndefNode, CompactionMask);
3515 static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3516 return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3519 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3520 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3521 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3522 bool HasAVX2, bool V2IsSplat = false) {
3523 unsigned NumElts = VT.getVectorNumElements();
3525 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3526 "Unsupported vector type for unpckh");
3528 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3529 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3532 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3533 // independently on 128-bit lanes.
3534 unsigned NumLanes = VT.getSizeInBits()/128;
3535 unsigned NumLaneElts = NumElts/NumLanes;
3537 for (unsigned l = 0; l != NumLanes; ++l) {
3538 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3539 i != (l+1)*NumLaneElts;
3542 int BitI1 = Mask[i+1];
3543 if (!isUndefOrEqual(BitI, j))
3546 if (!isUndefOrEqual(BitI1, NumElts))
3549 if (!isUndefOrEqual(BitI1, j + NumElts))
3558 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3559 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3560 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3561 bool HasAVX2, bool V2IsSplat = false) {
3562 unsigned NumElts = VT.getVectorNumElements();
3564 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3565 "Unsupported vector type for unpckh");
3567 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3568 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3571 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3572 // independently on 128-bit lanes.
3573 unsigned NumLanes = VT.getSizeInBits()/128;
3574 unsigned NumLaneElts = NumElts/NumLanes;
3576 for (unsigned l = 0; l != NumLanes; ++l) {
3577 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3578 i != (l+1)*NumLaneElts; i += 2, ++j) {
3580 int BitI1 = Mask[i+1];
3581 if (!isUndefOrEqual(BitI, j))
3584 if (isUndefOrEqual(BitI1, NumElts))
3587 if (!isUndefOrEqual(BitI1, j+NumElts))
3595 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3596 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3598 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3600 unsigned NumElts = VT.getVectorNumElements();
3602 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3603 "Unsupported vector type for unpckh");
3605 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3606 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3609 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3610 // FIXME: Need a better way to get rid of this, there's no latency difference
3611 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3612 // the former later. We should also remove the "_undef" special mask.
3613 if (NumElts == 4 && VT.getSizeInBits() == 256)
3616 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3617 // independently on 128-bit lanes.
3618 unsigned NumLanes = VT.getSizeInBits()/128;
3619 unsigned NumLaneElts = NumElts/NumLanes;
3621 for (unsigned l = 0; l != NumLanes; ++l) {
3622 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3623 i != (l+1)*NumLaneElts;
3626 int BitI1 = Mask[i+1];
3628 if (!isUndefOrEqual(BitI, j))
3630 if (!isUndefOrEqual(BitI1, j))
3638 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3639 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3641 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3642 unsigned NumElts = VT.getVectorNumElements();
3644 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3645 "Unsupported vector type for unpckh");
3647 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3648 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3651 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3652 // independently on 128-bit lanes.
3653 unsigned NumLanes = VT.getSizeInBits()/128;
3654 unsigned NumLaneElts = NumElts/NumLanes;
3656 for (unsigned l = 0; l != NumLanes; ++l) {
3657 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3658 i != (l+1)*NumLaneElts; i += 2, ++j) {
3660 int BitI1 = Mask[i+1];
3661 if (!isUndefOrEqual(BitI, j))
3663 if (!isUndefOrEqual(BitI1, j))
3670 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3671 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3672 /// MOVSD, and MOVD, i.e. setting the lowest element.
3673 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3674 if (VT.getVectorElementType().getSizeInBits() < 32)
3676 if (VT.getSizeInBits() == 256)
3679 unsigned NumElts = VT.getVectorNumElements();
3681 if (!isUndefOrEqual(Mask[0], NumElts))
3684 for (unsigned i = 1; i != NumElts; ++i)
3685 if (!isUndefOrEqual(Mask[i], i))
3691 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3692 /// as permutations between 128-bit chunks or halves. As an example: this
3694 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3695 /// The first half comes from the second half of V1 and the second half from the
3696 /// the second half of V2.
3697 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3698 if (!HasAVX || VT.getSizeInBits() != 256)
3701 // The shuffle result is divided into half A and half B. In total the two
3702 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3703 // B must come from C, D, E or F.
3704 unsigned HalfSize = VT.getVectorNumElements()/2;
3705 bool MatchA = false, MatchB = false;
3707 // Check if A comes from one of C, D, E, F.
3708 for (unsigned Half = 0; Half != 4; ++Half) {
3709 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3715 // Check if B comes from one of C, D, E, F.
3716 for (unsigned Half = 0; Half != 4; ++Half) {
3717 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3723 return MatchA && MatchB;
3726 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3727 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3728 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3729 EVT VT = SVOp->getValueType(0);
3731 unsigned HalfSize = VT.getVectorNumElements()/2;
3733 unsigned FstHalf = 0, SndHalf = 0;
3734 for (unsigned i = 0; i < HalfSize; ++i) {
3735 if (SVOp->getMaskElt(i) > 0) {
3736 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3740 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3741 if (SVOp->getMaskElt(i) > 0) {
3742 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3747 return (FstHalf | (SndHalf << 4));
3750 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3751 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3752 /// Note that VPERMIL mask matching is different depending whether theunderlying
3753 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3754 /// to the same elements of the low, but to the higher half of the source.
3755 /// In VPERMILPD the two lanes could be shuffled independently of each other
3756 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3757 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3761 unsigned NumElts = VT.getVectorNumElements();
3762 // Only match 256-bit with 32/64-bit types
3763 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3766 unsigned NumLanes = VT.getSizeInBits()/128;
3767 unsigned LaneSize = NumElts/NumLanes;
3768 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3769 for (unsigned i = 0; i != LaneSize; ++i) {
3770 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3772 if (NumElts != 8 || l == 0)
3774 // VPERMILPS handling
3777 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3785 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3786 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3787 /// element of vector 2 and the other elements to come from vector 1 in order.
3788 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3789 bool V2IsSplat = false, bool V2IsUndef = false) {
3790 unsigned NumOps = VT.getVectorNumElements();
3791 if (VT.getSizeInBits() == 256)
3793 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3796 if (!isUndefOrEqual(Mask[0], 0))
3799 for (unsigned i = 1; i != NumOps; ++i)
3800 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3801 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3802 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3808 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3809 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3810 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3811 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3812 const X86Subtarget *Subtarget) {
3813 if (!Subtarget->hasSSE3())
3816 unsigned NumElems = VT.getVectorNumElements();
3818 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3819 (VT.getSizeInBits() == 256 && NumElems != 8))
3822 // "i+1" is the value the indexed mask element must have
3823 for (unsigned i = 0; i != NumElems; i += 2)
3824 if (!isUndefOrEqual(Mask[i], i+1) ||
3825 !isUndefOrEqual(Mask[i+1], i+1))
3831 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3832 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3833 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3834 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3835 const X86Subtarget *Subtarget) {
3836 if (!Subtarget->hasSSE3())
3839 unsigned NumElems = VT.getVectorNumElements();
3841 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3842 (VT.getSizeInBits() == 256 && NumElems != 8))
3845 // "i" is the value the indexed mask element must have
3846 for (unsigned i = 0; i != NumElems; i += 2)
3847 if (!isUndefOrEqual(Mask[i], i) ||
3848 !isUndefOrEqual(Mask[i+1], i))
3854 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to 256-bit
3856 /// version of MOVDDUP.
3857 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3858 unsigned NumElts = VT.getVectorNumElements();
3860 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3863 for (unsigned i = 0; i != NumElts/2; ++i)
3864 if (!isUndefOrEqual(Mask[i], 0))
3866 for (unsigned i = NumElts/2; i != NumElts; ++i)
3867 if (!isUndefOrEqual(Mask[i], NumElts/2))
3872 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3873 /// specifies a shuffle of elements that is suitable for input to 128-bit
3874 /// version of MOVDDUP.
3875 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3876 if (VT.getSizeInBits() != 128)
3879 unsigned e = VT.getVectorNumElements() / 2;
3880 for (unsigned i = 0; i != e; ++i)
3881 if (!isUndefOrEqual(Mask[i], i))
3883 for (unsigned i = 0; i != e; ++i)
3884 if (!isUndefOrEqual(Mask[e+i], i))
3889 /// isVEXTRACTF128Index - Return true if the specified
3890 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3891 /// suitable for input to VEXTRACTF128.
3892 bool X86::isVEXTRACTF128Index(SDNode *N) {
3893 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3896 // The index should be aligned on a 128-bit boundary.
3898 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3900 unsigned VL = N->getValueType(0).getVectorNumElements();
3901 unsigned VBits = N->getValueType(0).getSizeInBits();
3902 unsigned ElSize = VBits / VL;
3903 bool Result = (Index * ElSize) % 128 == 0;
3908 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3909 /// operand specifies a subvector insert that is suitable for input to
3911 bool X86::isVINSERTF128Index(SDNode *N) {
3912 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3915 // The index should be aligned on a 128-bit boundary.
3917 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3919 unsigned VL = N->getValueType(0).getVectorNumElements();
3920 unsigned VBits = N->getValueType(0).getSizeInBits();
3921 unsigned ElSize = VBits / VL;
3922 bool Result = (Index * ElSize) % 128 == 0;
3927 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3928 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3929 /// Handles 128-bit and 256-bit.
3930 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3931 EVT VT = N->getValueType(0);
3933 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3934 "Unsupported vector type for PSHUF/SHUFP");
3936 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3937 // independently on 128-bit lanes.
3938 unsigned NumElts = VT.getVectorNumElements();
3939 unsigned NumLanes = VT.getSizeInBits()/128;
3940 unsigned NumLaneElts = NumElts/NumLanes;
3942 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3943 "Only supports 2 or 4 elements per lane");
3945 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3947 for (unsigned i = 0; i != NumElts; ++i) {
3948 int Elt = N->getMaskElt(i);
3949 if (Elt < 0) continue;
3950 Elt &= NumLaneElts - 1;
3951 unsigned ShAmt = (i << Shift) % 8;
3952 Mask |= Elt << ShAmt;
3958 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3959 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3960 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3961 EVT VT = N->getValueType(0);
3963 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3964 "Unsupported vector type for PSHUFHW");
3966 unsigned NumElts = VT.getVectorNumElements();
3969 for (unsigned l = 0; l != NumElts; l += 8) {
3970 // 8 nodes per lane, but we only care about the last 4.
3971 for (unsigned i = 0; i < 4; ++i) {
3972 int Elt = N->getMaskElt(l+i+4);
3973 if (Elt < 0) continue;
3974 Elt &= 0x3; // only 2-bits.
3975 Mask |= Elt << (i * 2);
3982 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3983 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3984 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3985 EVT VT = N->getValueType(0);
3987 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3988 "Unsupported vector type for PSHUFHW");
3990 unsigned NumElts = VT.getVectorNumElements();
3993 for (unsigned l = 0; l != NumElts; l += 8) {
3994 // 8 nodes per lane, but we only care about the first 4.
3995 for (unsigned i = 0; i < 4; ++i) {
3996 int Elt = N->getMaskElt(l+i);
3997 if (Elt < 0) continue;
3998 Elt &= 0x3; // only 2-bits
3999 Mask |= Elt << (i * 2);
4006 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4007 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4008 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4009 EVT VT = SVOp->getValueType(0);
4010 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4012 unsigned NumElts = VT.getVectorNumElements();
4013 unsigned NumLanes = VT.getSizeInBits()/128;
4014 unsigned NumLaneElts = NumElts/NumLanes;
4018 for (i = 0; i != NumElts; ++i) {
4019 Val = SVOp->getMaskElt(i);
4023 if (Val >= (int)NumElts)
4024 Val -= NumElts - NumLaneElts;
4026 assert(Val - i > 0 && "PALIGNR imm should be positive");
4027 return (Val - i) * EltSize;
4030 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4031 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4033 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4034 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4035 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4038 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4040 EVT VecVT = N->getOperand(0).getValueType();
4041 EVT ElVT = VecVT.getVectorElementType();
4043 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4044 return Index / NumElemsPerChunk;
4047 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4048 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4050 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4051 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4052 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4055 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4057 EVT VecVT = N->getValueType(0);
4058 EVT ElVT = VecVT.getVectorElementType();
4060 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4061 return Index / NumElemsPerChunk;
4064 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4065 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4066 /// Handles 256-bit.
4067 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4068 EVT VT = N->getValueType(0);
4070 unsigned NumElts = VT.getVectorNumElements();
4072 assert((VT.is256BitVector() && NumElts == 4) &&
4073 "Unsupported vector type for VPERMQ/VPERMPD");
4076 for (unsigned i = 0; i != NumElts; ++i) {
4077 int Elt = N->getMaskElt(i);
4080 Mask |= Elt << (i*2);
4085 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4087 bool X86::isZeroNode(SDValue Elt) {
4088 return ((isa<ConstantSDNode>(Elt) &&
4089 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4090 (isa<ConstantFPSDNode>(Elt) &&
4091 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4094 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4095 /// their permute mask.
4096 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4097 SelectionDAG &DAG) {
4098 EVT VT = SVOp->getValueType(0);
4099 unsigned NumElems = VT.getVectorNumElements();
4100 SmallVector<int, 8> MaskVec;
4102 for (unsigned i = 0; i != NumElems; ++i) {
4103 int Idx = SVOp->getMaskElt(i);
4105 if (Idx < (int)NumElems)
4110 MaskVec.push_back(Idx);
4112 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4113 SVOp->getOperand(0), &MaskVec[0]);
4116 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4117 /// match movhlps. The lower half elements should come from upper half of
4118 /// V1 (and in order), and the upper half elements should come from the upper
4119 /// half of V2 (and in order).
4120 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4121 if (VT.getSizeInBits() != 128)
4123 if (VT.getVectorNumElements() != 4)
4125 for (unsigned i = 0, e = 2; i != e; ++i)
4126 if (!isUndefOrEqual(Mask[i], i+2))
4128 for (unsigned i = 2; i != 4; ++i)
4129 if (!isUndefOrEqual(Mask[i], i+4))
4134 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4135 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4137 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4138 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4140 N = N->getOperand(0).getNode();
4141 if (!ISD::isNON_EXTLoad(N))
4144 *LD = cast<LoadSDNode>(N);
4148 // Test whether the given value is a vector value which will be legalized
4150 static bool WillBeConstantPoolLoad(SDNode *N) {
4151 if (N->getOpcode() != ISD::BUILD_VECTOR)
4154 // Check for any non-constant elements.
4155 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4156 switch (N->getOperand(i).getNode()->getOpcode()) {
4158 case ISD::ConstantFP:
4165 // Vectors of all-zeros and all-ones are materialized with special
4166 // instructions rather than being loaded.
4167 return !ISD::isBuildVectorAllZeros(N) &&
4168 !ISD::isBuildVectorAllOnes(N);
4171 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4172 /// match movlp{s|d}. The lower half elements should come from lower half of
4173 /// V1 (and in order), and the upper half elements should come from the upper
4174 /// half of V2 (and in order). And since V1 will become the source of the
4175 /// MOVLP, it must be either a vector load or a scalar load to vector.
4176 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4177 ArrayRef<int> Mask, EVT VT) {
4178 if (VT.getSizeInBits() != 128)
4181 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4183 // Is V2 is a vector load, don't do this transformation. We will try to use
4184 // load folding shufps op.
4185 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4188 unsigned NumElems = VT.getVectorNumElements();
4190 if (NumElems != 2 && NumElems != 4)
4192 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4193 if (!isUndefOrEqual(Mask[i], i))
4195 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4196 if (!isUndefOrEqual(Mask[i], i+NumElems))
4201 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4203 static bool isSplatVector(SDNode *N) {
4204 if (N->getOpcode() != ISD::BUILD_VECTOR)
4207 SDValue SplatValue = N->getOperand(0);
4208 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4209 if (N->getOperand(i) != SplatValue)
4214 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4215 /// to an zero vector.
4216 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4217 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4218 SDValue V1 = N->getOperand(0);
4219 SDValue V2 = N->getOperand(1);
4220 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4221 for (unsigned i = 0; i != NumElems; ++i) {
4222 int Idx = N->getMaskElt(i);
4223 if (Idx >= (int)NumElems) {
4224 unsigned Opc = V2.getOpcode();
4225 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4227 if (Opc != ISD::BUILD_VECTOR ||
4228 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4230 } else if (Idx >= 0) {
4231 unsigned Opc = V1.getOpcode();
4232 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4234 if (Opc != ISD::BUILD_VECTOR ||
4235 !X86::isZeroNode(V1.getOperand(Idx)))
4242 /// getZeroVector - Returns a vector of specified type with all zero elements.
4244 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4245 SelectionDAG &DAG, DebugLoc dl) {
4246 assert(VT.isVector() && "Expected a vector type");
4247 unsigned Size = VT.getSizeInBits();
4249 // Always build SSE zero vectors as <4 x i32> bitcasted
4250 // to their dest type. This ensures they get CSE'd.
4252 if (Size == 128) { // SSE
4253 if (Subtarget->hasSSE2()) { // SSE2
4254 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4255 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4257 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4258 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4260 } else if (Size == 256) { // AVX
4261 if (Subtarget->hasAVX2()) { // AVX2
4262 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4263 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4264 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4266 // 256-bit logic and arithmetic instructions in AVX are all
4267 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4268 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4269 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4270 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4273 llvm_unreachable("Unexpected vector type");
4275 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4278 /// getOnesVector - Returns a vector of specified type with all bits set.
4279 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4280 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4281 /// Then bitcast to their original type, ensuring they get CSE'd.
4282 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4284 assert(VT.isVector() && "Expected a vector type");
4285 unsigned Size = VT.getSizeInBits();
4287 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4290 if (HasAVX2) { // AVX2
4291 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4292 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4294 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4295 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4297 } else if (Size == 128) {
4298 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4300 llvm_unreachable("Unexpected vector type");
4302 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4305 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4306 /// that point to V2 points to its first element.
4307 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4308 for (unsigned i = 0; i != NumElems; ++i) {
4309 if (Mask[i] > (int)NumElems) {
4315 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4316 /// operation of specified width.
4317 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4319 unsigned NumElems = VT.getVectorNumElements();
4320 SmallVector<int, 8> Mask;
4321 Mask.push_back(NumElems);
4322 for (unsigned i = 1; i != NumElems; ++i)
4324 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4327 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4328 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4330 unsigned NumElems = VT.getVectorNumElements();
4331 SmallVector<int, 8> Mask;
4332 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4334 Mask.push_back(i + NumElems);
4336 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4339 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4340 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4342 unsigned NumElems = VT.getVectorNumElements();
4343 SmallVector<int, 8> Mask;
4344 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4345 Mask.push_back(i + Half);
4346 Mask.push_back(i + NumElems + Half);
4348 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4351 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4352 // a generic shuffle instruction because the target has no such instructions.
4353 // Generate shuffles which repeat i16 and i8 several times until they can be
4354 // represented by v4f32 and then be manipulated by target suported shuffles.
4355 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4356 EVT VT = V.getValueType();
4357 int NumElems = VT.getVectorNumElements();
4358 DebugLoc dl = V.getDebugLoc();
4360 while (NumElems > 4) {
4361 if (EltNo < NumElems/2) {
4362 V = getUnpackl(DAG, dl, VT, V, V);
4364 V = getUnpackh(DAG, dl, VT, V, V);
4365 EltNo -= NumElems/2;
4372 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4373 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4374 EVT VT = V.getValueType();
4375 DebugLoc dl = V.getDebugLoc();
4376 unsigned Size = VT.getSizeInBits();
4379 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4380 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4381 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4383 } else if (Size == 256) {
4384 // To use VPERMILPS to splat scalars, the second half of indicies must
4385 // refer to the higher part, which is a duplication of the lower one,
4386 // because VPERMILPS can only handle in-lane permutations.
4387 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4388 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4390 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4391 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4394 llvm_unreachable("Vector size not supported");
4396 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4399 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4400 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4401 EVT SrcVT = SV->getValueType(0);
4402 SDValue V1 = SV->getOperand(0);
4403 DebugLoc dl = SV->getDebugLoc();
4405 int EltNo = SV->getSplatIndex();
4406 int NumElems = SrcVT.getVectorNumElements();
4407 unsigned Size = SrcVT.getSizeInBits();
4409 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4410 "Unknown how to promote splat for type");
4412 // Extract the 128-bit part containing the splat element and update
4413 // the splat element index when it refers to the higher register.
4415 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4416 if (EltNo >= NumElems/2)
4417 EltNo -= NumElems/2;
4420 // All i16 and i8 vector types can't be used directly by a generic shuffle
4421 // instruction because the target has no such instruction. Generate shuffles
4422 // which repeat i16 and i8 several times until they fit in i32, and then can
4423 // be manipulated by target suported shuffles.
4424 EVT EltVT = SrcVT.getVectorElementType();
4425 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4426 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4428 // Recreate the 256-bit vector and place the same 128-bit vector
4429 // into the low and high part. This is necessary because we want
4430 // to use VPERM* to shuffle the vectors
4432 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4435 return getLegalSplat(DAG, V1, EltNo);
4438 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4439 /// vector of zero or undef vector. This produces a shuffle where the low
4440 /// element of V2 is swizzled into the zero/undef vector, landing at element
4441 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4442 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4444 const X86Subtarget *Subtarget,
4445 SelectionDAG &DAG) {
4446 EVT VT = V2.getValueType();
4448 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4449 unsigned NumElems = VT.getVectorNumElements();
4450 SmallVector<int, 16> MaskVec;
4451 for (unsigned i = 0; i != NumElems; ++i)
4452 // If this is the insertion idx, put the low elt of V2 here.
4453 MaskVec.push_back(i == Idx ? NumElems : i);
4454 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4457 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4458 /// target specific opcode. Returns true if the Mask could be calculated.
4459 /// Sets IsUnary to true if only uses one source.
4460 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4461 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4462 unsigned NumElems = VT.getVectorNumElements();
4466 switch(N->getOpcode()) {
4468 ImmN = N->getOperand(N->getNumOperands()-1);
4469 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4471 case X86ISD::UNPCKH:
4472 DecodeUNPCKHMask(VT, Mask);
4474 case X86ISD::UNPCKL:
4475 DecodeUNPCKLMask(VT, Mask);
4477 case X86ISD::MOVHLPS:
4478 DecodeMOVHLPSMask(NumElems, Mask);
4480 case X86ISD::MOVLHPS:
4481 DecodeMOVLHPSMask(NumElems, Mask);
4483 case X86ISD::PSHUFD:
4484 case X86ISD::VPERMILP:
4485 ImmN = N->getOperand(N->getNumOperands()-1);
4486 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4489 case X86ISD::PSHUFHW:
4490 ImmN = N->getOperand(N->getNumOperands()-1);
4491 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4494 case X86ISD::PSHUFLW:
4495 ImmN = N->getOperand(N->getNumOperands()-1);
4496 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4499 case X86ISD::VPERMI:
4500 ImmN = N->getOperand(N->getNumOperands()-1);
4501 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505 case X86ISD::MOVSD: {
4506 // The index 0 always comes from the first element of the second source,
4507 // this is why MOVSS and MOVSD are used in the first place. The other
4508 // elements come from the other positions of the first source vector
4509 Mask.push_back(NumElems);
4510 for (unsigned i = 1; i != NumElems; ++i) {
4515 case X86ISD::VPERM2X128:
4516 ImmN = N->getOperand(N->getNumOperands()-1);
4517 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4518 if (Mask.empty()) return false;
4520 case X86ISD::MOVDDUP:
4521 case X86ISD::MOVLHPD:
4522 case X86ISD::MOVLPD:
4523 case X86ISD::MOVLPS:
4524 case X86ISD::MOVSHDUP:
4525 case X86ISD::MOVSLDUP:
4526 case X86ISD::PALIGN:
4527 // Not yet implemented
4529 default: llvm_unreachable("unknown target shuffle node");
4535 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4536 /// element of the result of the vector shuffle.
4537 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4540 return SDValue(); // Limit search depth.
4542 SDValue V = SDValue(N, 0);
4543 EVT VT = V.getValueType();
4544 unsigned Opcode = V.getOpcode();
4546 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4547 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4548 int Elt = SV->getMaskElt(Index);
4551 return DAG.getUNDEF(VT.getVectorElementType());
4553 unsigned NumElems = VT.getVectorNumElements();
4554 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4555 : SV->getOperand(1);
4556 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4559 // Recurse into target specific vector shuffles to find scalars.
4560 if (isTargetShuffle(Opcode)) {
4561 MVT ShufVT = V.getValueType().getSimpleVT();
4562 unsigned NumElems = ShufVT.getVectorNumElements();
4563 SmallVector<int, 16> ShuffleMask;
4567 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4570 int Elt = ShuffleMask[Index];
4572 return DAG.getUNDEF(ShufVT.getVectorElementType());
4574 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4576 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4580 // Actual nodes that may contain scalar elements
4581 if (Opcode == ISD::BITCAST) {
4582 V = V.getOperand(0);
4583 EVT SrcVT = V.getValueType();
4584 unsigned NumElems = VT.getVectorNumElements();
4586 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4590 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4591 return (Index == 0) ? V.getOperand(0)
4592 : DAG.getUNDEF(VT.getVectorElementType());
4594 if (V.getOpcode() == ISD::BUILD_VECTOR)
4595 return V.getOperand(Index);
4600 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4601 /// shuffle operation which come from a consecutively from a zero. The
4602 /// search can start in two different directions, from left or right.
4604 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4605 bool ZerosFromLeft, SelectionDAG &DAG) {
4607 for (i = 0; i != NumElems; ++i) {
4608 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4609 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4610 if (!(Elt.getNode() &&
4611 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4618 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4619 /// correspond consecutively to elements from one of the vector operands,
4620 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4622 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4623 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4624 unsigned NumElems, unsigned &OpNum) {
4625 bool SeenV1 = false;
4626 bool SeenV2 = false;
4628 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4629 int Idx = SVOp->getMaskElt(i);
4630 // Ignore undef indicies
4634 if (Idx < (int)NumElems)
4639 // Only accept consecutive elements from the same vector
4640 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4644 OpNum = SeenV1 ? 0 : 1;
4648 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4649 /// logical left shift of a vector.
4650 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4651 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4652 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4653 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4654 false /* check zeros from right */, DAG);
4660 // Considering the elements in the mask that are not consecutive zeros,
4661 // check if they consecutively come from only one of the source vectors.
4663 // V1 = {X, A, B, C} 0
4665 // vector_shuffle V1, V2 <1, 2, 3, X>
4667 if (!isShuffleMaskConsecutive(SVOp,
4668 0, // Mask Start Index
4669 NumElems-NumZeros, // Mask End Index(exclusive)
4670 NumZeros, // Where to start looking in the src vector
4671 NumElems, // Number of elements in vector
4672 OpSrc)) // Which source operand ?
4677 ShVal = SVOp->getOperand(OpSrc);
4681 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4682 /// logical left shift of a vector.
4683 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4684 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4685 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4686 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4687 true /* check zeros from left */, DAG);
4693 // Considering the elements in the mask that are not consecutive zeros,
4694 // check if they consecutively come from only one of the source vectors.
4696 // 0 { A, B, X, X } = V2
4698 // vector_shuffle V1, V2 <X, X, 4, 5>
4700 if (!isShuffleMaskConsecutive(SVOp,
4701 NumZeros, // Mask Start Index
4702 NumElems, // Mask End Index(exclusive)
4703 0, // Where to start looking in the src vector
4704 NumElems, // Number of elements in vector
4705 OpSrc)) // Which source operand ?
4710 ShVal = SVOp->getOperand(OpSrc);
4714 /// isVectorShift - Returns true if the shuffle can be implemented as a
4715 /// logical left or right shift of a vector.
4716 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4717 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4718 // Although the logic below support any bitwidth size, there are no
4719 // shift instructions which handle more than 128-bit vectors.
4720 if (SVOp->getValueType(0).getSizeInBits() > 128)
4723 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4724 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4730 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4732 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4733 unsigned NumNonZero, unsigned NumZero,
4735 const X86Subtarget* Subtarget,
4736 const TargetLowering &TLI) {
4740 DebugLoc dl = Op.getDebugLoc();
4743 for (unsigned i = 0; i < 16; ++i) {
4744 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4745 if (ThisIsNonZero && First) {
4747 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4749 V = DAG.getUNDEF(MVT::v8i16);
4754 SDValue ThisElt(0, 0), LastElt(0, 0);
4755 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4756 if (LastIsNonZero) {
4757 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4758 MVT::i16, Op.getOperand(i-1));
4760 if (ThisIsNonZero) {
4761 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4762 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4763 ThisElt, DAG.getConstant(8, MVT::i8));
4765 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4769 if (ThisElt.getNode())
4770 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4771 DAG.getIntPtrConstant(i/2));
4775 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4778 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4780 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4781 unsigned NumNonZero, unsigned NumZero,
4783 const X86Subtarget* Subtarget,
4784 const TargetLowering &TLI) {
4788 DebugLoc dl = Op.getDebugLoc();
4791 for (unsigned i = 0; i < 8; ++i) {
4792 bool isNonZero = (NonZeros & (1 << i)) != 0;
4796 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4798 V = DAG.getUNDEF(MVT::v8i16);
4801 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4802 MVT::v8i16, V, Op.getOperand(i),
4803 DAG.getIntPtrConstant(i));
4810 /// getVShift - Return a vector logical shift node.
4812 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4813 unsigned NumBits, SelectionDAG &DAG,
4814 const TargetLowering &TLI, DebugLoc dl) {
4815 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4816 EVT ShVT = MVT::v2i64;
4817 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4818 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4819 return DAG.getNode(ISD::BITCAST, dl, VT,
4820 DAG.getNode(Opc, dl, ShVT, SrcOp,
4821 DAG.getConstant(NumBits,
4822 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4826 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4827 SelectionDAG &DAG) const {
4829 // Check if the scalar load can be widened into a vector load. And if
4830 // the address is "base + cst" see if the cst can be "absorbed" into
4831 // the shuffle mask.
4832 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4833 SDValue Ptr = LD->getBasePtr();
4834 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4836 EVT PVT = LD->getValueType(0);
4837 if (PVT != MVT::i32 && PVT != MVT::f32)
4842 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4843 FI = FINode->getIndex();
4845 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4846 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4847 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4848 Offset = Ptr.getConstantOperandVal(1);
4849 Ptr = Ptr.getOperand(0);
4854 // FIXME: 256-bit vector instructions don't require a strict alignment,
4855 // improve this code to support it better.
4856 unsigned RequiredAlign = VT.getSizeInBits()/8;
4857 SDValue Chain = LD->getChain();
4858 // Make sure the stack object alignment is at least 16 or 32.
4859 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4860 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4861 if (MFI->isFixedObjectIndex(FI)) {
4862 // Can't change the alignment. FIXME: It's possible to compute
4863 // the exact stack offset and reference FI + adjust offset instead.
4864 // If someone *really* cares about this. That's the way to implement it.
4867 MFI->setObjectAlignment(FI, RequiredAlign);
4871 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4872 // Ptr + (Offset & ~15).
4875 if ((Offset % RequiredAlign) & 3)
4877 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4879 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4880 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4882 int EltNo = (Offset - StartOffset) >> 2;
4883 unsigned NumElems = VT.getVectorNumElements();
4885 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4886 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4887 LD->getPointerInfo().getWithOffset(StartOffset),
4888 false, false, false, 0);
4890 SmallVector<int, 8> Mask;
4891 for (unsigned i = 0; i != NumElems; ++i)
4892 Mask.push_back(EltNo);
4894 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4900 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4901 /// vector of type 'VT', see if the elements can be replaced by a single large
4902 /// load which has the same value as a build_vector whose operands are 'elts'.
4904 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4906 /// FIXME: we'd also like to handle the case where the last elements are zero
4907 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4908 /// There's even a handy isZeroNode for that purpose.
4909 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4910 DebugLoc &DL, SelectionDAG &DAG) {
4911 EVT EltVT = VT.getVectorElementType();
4912 unsigned NumElems = Elts.size();
4914 LoadSDNode *LDBase = NULL;
4915 unsigned LastLoadedElt = -1U;
4917 // For each element in the initializer, see if we've found a load or an undef.
4918 // If we don't find an initial load element, or later load elements are
4919 // non-consecutive, bail out.
4920 for (unsigned i = 0; i < NumElems; ++i) {
4921 SDValue Elt = Elts[i];
4923 if (!Elt.getNode() ||
4924 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4927 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4929 LDBase = cast<LoadSDNode>(Elt.getNode());
4933 if (Elt.getOpcode() == ISD::UNDEF)
4936 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4937 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4942 // If we have found an entire vector of loads and undefs, then return a large
4943 // load of the entire vector width starting at the base pointer. If we found
4944 // consecutive loads for the low half, generate a vzext_load node.
4945 if (LastLoadedElt == NumElems - 1) {
4946 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4947 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4948 LDBase->getPointerInfo(),
4949 LDBase->isVolatile(), LDBase->isNonTemporal(),
4950 LDBase->isInvariant(), 0);
4951 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4952 LDBase->getPointerInfo(),
4953 LDBase->isVolatile(), LDBase->isNonTemporal(),
4954 LDBase->isInvariant(), LDBase->getAlignment());
4956 if (NumElems == 4 && LastLoadedElt == 1 &&
4957 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4958 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4959 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4961 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4962 LDBase->getPointerInfo(),
4963 LDBase->getAlignment(),
4964 false/*isVolatile*/, true/*ReadMem*/,
4966 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4971 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4972 /// to generate a splat value for the following cases:
4973 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4974 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4975 /// a scalar load, or a constant.
4976 /// The VBROADCAST node is returned when a pattern is found,
4977 /// or SDValue() otherwise.
4979 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4980 if (!Subtarget->hasAVX())
4983 EVT VT = Op.getValueType();
4984 DebugLoc dl = Op.getDebugLoc();
4986 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4987 "Unsupported vector type for broadcast.");
4992 switch (Op.getOpcode()) {
4994 // Unknown pattern found.
4997 case ISD::BUILD_VECTOR: {
4998 // The BUILD_VECTOR node must be a splat.
4999 if (!isSplatVector(Op.getNode()))
5002 Ld = Op.getOperand(0);
5003 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5004 Ld.getOpcode() == ISD::ConstantFP);
5006 // The suspected load node has several users. Make sure that all
5007 // of its users are from the BUILD_VECTOR node.
5008 // Constants may have multiple users.
5009 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5014 case ISD::VECTOR_SHUFFLE: {
5015 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5017 // Shuffles must have a splat mask where the first element is
5019 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5022 SDValue Sc = Op.getOperand(0);
5023 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5024 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5026 if (!Subtarget->hasAVX2())
5029 // Use the register form of the broadcast instruction available on AVX2.
5030 if (VT.is256BitVector())
5031 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5032 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5035 Ld = Sc.getOperand(0);
5036 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5037 Ld.getOpcode() == ISD::ConstantFP);
5039 // The scalar_to_vector node and the suspected
5040 // load node must have exactly one user.
5041 // Constants may have multiple users.
5042 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5048 bool Is256 = VT.getSizeInBits() == 256;
5050 // Handle the broadcasting a single constant scalar from the constant pool
5051 // into a vector. On Sandybridge it is still better to load a constant vector
5052 // from the constant pool and not to broadcast it from a scalar.
5053 if (ConstSplatVal && Subtarget->hasAVX2()) {
5054 EVT CVT = Ld.getValueType();
5055 assert(!CVT.isVector() && "Must not broadcast a vector type");
5056 unsigned ScalarSize = CVT.getSizeInBits();
5058 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5059 const Constant *C = 0;
5060 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5061 C = CI->getConstantIntValue();
5062 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5063 C = CF->getConstantFPValue();
5065 assert(C && "Invalid constant type");
5067 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5068 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5069 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5070 MachinePointerInfo::getConstantPool(),
5071 false, false, false, Alignment);
5073 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5077 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5078 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5080 // Handle AVX2 in-register broadcasts.
5081 if (!IsLoad && Subtarget->hasAVX2() &&
5082 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5083 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5085 // The scalar source must be a normal load.
5089 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5090 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5092 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5093 // double since there is no vbroadcastsd xmm
5094 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5095 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5096 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5099 // Unsupported broadcast.
5104 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5105 DebugLoc dl = Op.getDebugLoc();
5107 EVT VT = Op.getValueType();
5108 EVT ExtVT = VT.getVectorElementType();
5109 unsigned NumElems = Op.getNumOperands();
5111 // Vectors containing all zeros can be matched by pxor and xorps later
5112 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5113 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5114 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5115 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5118 return getZeroVector(VT, Subtarget, DAG, dl);
5121 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5122 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5123 // vpcmpeqd on 256-bit vectors.
5124 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5125 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5128 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5131 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5132 if (Broadcast.getNode())
5135 unsigned EVTBits = ExtVT.getSizeInBits();
5137 unsigned NumZero = 0;
5138 unsigned NumNonZero = 0;
5139 unsigned NonZeros = 0;
5140 bool IsAllConstants = true;
5141 SmallSet<SDValue, 8> Values;
5142 for (unsigned i = 0; i < NumElems; ++i) {
5143 SDValue Elt = Op.getOperand(i);
5144 if (Elt.getOpcode() == ISD::UNDEF)
5147 if (Elt.getOpcode() != ISD::Constant &&
5148 Elt.getOpcode() != ISD::ConstantFP)
5149 IsAllConstants = false;
5150 if (X86::isZeroNode(Elt))
5153 NonZeros |= (1 << i);
5158 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5159 if (NumNonZero == 0)
5160 return DAG.getUNDEF(VT);
5162 // Special case for single non-zero, non-undef, element.
5163 if (NumNonZero == 1) {
5164 unsigned Idx = CountTrailingZeros_32(NonZeros);
5165 SDValue Item = Op.getOperand(Idx);
5167 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5168 // the value are obviously zero, truncate the value to i32 and do the
5169 // insertion that way. Only do this if the value is non-constant or if the
5170 // value is a constant being inserted into element 0. It is cheaper to do
5171 // a constant pool load than it is to do a movd + shuffle.
5172 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5173 (!IsAllConstants || Idx == 0)) {
5174 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5176 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5177 EVT VecVT = MVT::v4i32;
5178 unsigned VecElts = 4;
5180 // Truncate the value (which may itself be a constant) to i32, and
5181 // convert it to a vector with movd (S2V+shuffle to zero extend).
5182 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5183 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5184 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5186 // Now we have our 32-bit value zero extended in the low element of
5187 // a vector. If Idx != 0, swizzle it into place.
5189 SmallVector<int, 4> Mask;
5190 Mask.push_back(Idx);
5191 for (unsigned i = 1; i != VecElts; ++i)
5193 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5196 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5200 // If we have a constant or non-constant insertion into the low element of
5201 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5202 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5203 // depending on what the source datatype is.
5206 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5208 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5209 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5210 if (VT.getSizeInBits() == 256) {
5211 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5212 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5213 Item, DAG.getIntPtrConstant(0));
5215 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5216 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5217 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5218 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5221 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5222 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5223 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5224 if (VT.getSizeInBits() == 256) {
5225 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5226 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5228 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5229 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5231 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5235 // Is it a vector logical left shift?
5236 if (NumElems == 2 && Idx == 1 &&
5237 X86::isZeroNode(Op.getOperand(0)) &&
5238 !X86::isZeroNode(Op.getOperand(1))) {
5239 unsigned NumBits = VT.getSizeInBits();
5240 return getVShift(true, VT,
5241 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5242 VT, Op.getOperand(1)),
5243 NumBits/2, DAG, *this, dl);
5246 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5249 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5250 // is a non-constant being inserted into an element other than the low one,
5251 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5252 // movd/movss) to move this into the low element, then shuffle it into
5254 if (EVTBits == 32) {
5255 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5257 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5258 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5259 SmallVector<int, 8> MaskVec;
5260 for (unsigned i = 0; i != NumElems; ++i)
5261 MaskVec.push_back(i == Idx ? 0 : 1);
5262 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5266 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5267 if (Values.size() == 1) {
5268 if (EVTBits == 32) {
5269 // Instead of a shuffle like this:
5270 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5271 // Check if it's possible to issue this instead.
5272 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5273 unsigned Idx = CountTrailingZeros_32(NonZeros);
5274 SDValue Item = Op.getOperand(Idx);
5275 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5276 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5281 // A vector full of immediates; various special cases are already
5282 // handled, so this is best done with a single constant-pool load.
5286 // For AVX-length vectors, build the individual 128-bit pieces and use
5287 // shuffles to put them in place.
5288 if (VT.getSizeInBits() == 256) {
5289 SmallVector<SDValue, 32> V;
5290 for (unsigned i = 0; i != NumElems; ++i)
5291 V.push_back(Op.getOperand(i));
5293 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5295 // Build both the lower and upper subvector.
5296 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5297 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5300 // Recreate the wider vector with the lower and upper part.
5301 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5304 // Let legalizer expand 2-wide build_vectors.
5305 if (EVTBits == 64) {
5306 if (NumNonZero == 1) {
5307 // One half is zero or undef.
5308 unsigned Idx = CountTrailingZeros_32(NonZeros);
5309 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5310 Op.getOperand(Idx));
5311 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5316 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5317 if (EVTBits == 8 && NumElems == 16) {
5318 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5320 if (V.getNode()) return V;
5323 if (EVTBits == 16 && NumElems == 8) {
5324 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5326 if (V.getNode()) return V;
5329 // If element VT is == 32 bits, turn it into a number of shuffles.
5330 SmallVector<SDValue, 8> V(NumElems);
5331 if (NumElems == 4 && NumZero > 0) {
5332 for (unsigned i = 0; i < 4; ++i) {
5333 bool isZero = !(NonZeros & (1 << i));
5335 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5337 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5340 for (unsigned i = 0; i < 2; ++i) {
5341 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5344 V[i] = V[i*2]; // Must be a zero vector.
5347 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5350 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5353 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5358 bool Reverse1 = (NonZeros & 0x3) == 2;
5359 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5363 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5364 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5366 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5369 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5370 // Check for a build vector of consecutive loads.
5371 for (unsigned i = 0; i < NumElems; ++i)
5372 V[i] = Op.getOperand(i);
5374 // Check for elements which are consecutive loads.
5375 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5379 // For SSE 4.1, use insertps to put the high elements into the low element.
5380 if (getSubtarget()->hasSSE41()) {
5382 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5383 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5385 Result = DAG.getUNDEF(VT);
5387 for (unsigned i = 1; i < NumElems; ++i) {
5388 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5389 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5390 Op.getOperand(i), DAG.getIntPtrConstant(i));
5395 // Otherwise, expand into a number of unpckl*, start by extending each of
5396 // our (non-undef) elements to the full vector width with the element in the
5397 // bottom slot of the vector (which generates no code for SSE).
5398 for (unsigned i = 0; i < NumElems; ++i) {
5399 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5400 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5402 V[i] = DAG.getUNDEF(VT);
5405 // Next, we iteratively mix elements, e.g. for v4f32:
5406 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5407 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5408 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5409 unsigned EltStride = NumElems >> 1;
5410 while (EltStride != 0) {
5411 for (unsigned i = 0; i < EltStride; ++i) {
5412 // If V[i+EltStride] is undef and this is the first round of mixing,
5413 // then it is safe to just drop this shuffle: V[i] is already in the
5414 // right place, the one element (since it's the first round) being
5415 // inserted as undef can be dropped. This isn't safe for successive
5416 // rounds because they will permute elements within both vectors.
5417 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5418 EltStride == NumElems/2)
5421 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5430 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5431 // them in a MMX register. This is better than doing a stack convert.
5432 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5433 DebugLoc dl = Op.getDebugLoc();
5434 EVT ResVT = Op.getValueType();
5436 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5437 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5439 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5440 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5441 InVec = Op.getOperand(1);
5442 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5443 unsigned NumElts = ResVT.getVectorNumElements();
5444 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5445 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5446 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5448 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5449 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5450 Mask[0] = 0; Mask[1] = 2;
5451 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5453 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5456 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5457 // to create 256-bit vectors from two other 128-bit ones.
5458 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5459 DebugLoc dl = Op.getDebugLoc();
5460 EVT ResVT = Op.getValueType();
5462 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5464 SDValue V1 = Op.getOperand(0);
5465 SDValue V2 = Op.getOperand(1);
5466 unsigned NumElems = ResVT.getVectorNumElements();
5468 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5472 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5473 EVT ResVT = Op.getValueType();
5475 assert(Op.getNumOperands() == 2);
5476 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5477 "Unsupported CONCAT_VECTORS for value type");
5479 // We support concatenate two MMX registers and place them in a MMX register.
5480 // This is better than doing a stack convert.
5481 if (ResVT.is128BitVector())
5482 return LowerMMXCONCAT_VECTORS(Op, DAG);
5484 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5485 // from two other 128-bit ones.
5486 return LowerAVXCONCAT_VECTORS(Op, DAG);
5489 // Try to lower a shuffle node into a simple blend instruction.
5490 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5491 const X86Subtarget *Subtarget,
5492 SelectionDAG &DAG) {
5493 SDValue V1 = SVOp->getOperand(0);
5494 SDValue V2 = SVOp->getOperand(1);
5495 DebugLoc dl = SVOp->getDebugLoc();
5496 MVT VT = SVOp->getValueType(0).getSimpleVT();
5497 unsigned NumElems = VT.getVectorNumElements();
5499 if (!Subtarget->hasSSE41())
5505 switch (VT.SimpleTy) {
5506 default: return SDValue();
5508 ISDNo = X86ISD::BLENDPW;
5513 ISDNo = X86ISD::BLENDPS;
5518 ISDNo = X86ISD::BLENDPD;
5523 if (!Subtarget->hasAVX())
5525 ISDNo = X86ISD::BLENDPS;
5530 if (!Subtarget->hasAVX())
5532 ISDNo = X86ISD::BLENDPD;
5536 assert(ISDNo && "Invalid Op Number");
5538 unsigned MaskVals = 0;
5540 for (unsigned i = 0; i != NumElems; ++i) {
5541 int EltIdx = SVOp->getMaskElt(i);
5542 if (EltIdx == (int)i || EltIdx < 0)
5544 else if (EltIdx == (int)(i + NumElems))
5545 continue; // Bit is set to zero;
5550 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5551 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5552 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5553 DAG.getConstant(MaskVals, MVT::i32));
5554 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5557 // v8i16 shuffles - Prefer shuffles in the following order:
5558 // 1. [all] pshuflw, pshufhw, optional move
5559 // 2. [ssse3] 1 x pshufb
5560 // 3. [ssse3] 2 x pshufb + 1 x por
5561 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5563 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5564 SelectionDAG &DAG) const {
5565 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5566 SDValue V1 = SVOp->getOperand(0);
5567 SDValue V2 = SVOp->getOperand(1);
5568 DebugLoc dl = SVOp->getDebugLoc();
5569 SmallVector<int, 8> MaskVals;
5571 // Determine if more than 1 of the words in each of the low and high quadwords
5572 // of the result come from the same quadword of one of the two inputs. Undef
5573 // mask values count as coming from any quadword, for better codegen.
5574 unsigned LoQuad[] = { 0, 0, 0, 0 };
5575 unsigned HiQuad[] = { 0, 0, 0, 0 };
5576 std::bitset<4> InputQuads;
5577 for (unsigned i = 0; i < 8; ++i) {
5578 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5579 int EltIdx = SVOp->getMaskElt(i);
5580 MaskVals.push_back(EltIdx);
5589 InputQuads.set(EltIdx / 4);
5592 int BestLoQuad = -1;
5593 unsigned MaxQuad = 1;
5594 for (unsigned i = 0; i < 4; ++i) {
5595 if (LoQuad[i] > MaxQuad) {
5597 MaxQuad = LoQuad[i];
5601 int BestHiQuad = -1;
5603 for (unsigned i = 0; i < 4; ++i) {
5604 if (HiQuad[i] > MaxQuad) {
5606 MaxQuad = HiQuad[i];
5610 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5611 // of the two input vectors, shuffle them into one input vector so only a
5612 // single pshufb instruction is necessary. If There are more than 2 input
5613 // quads, disable the next transformation since it does not help SSSE3.
5614 bool V1Used = InputQuads[0] || InputQuads[1];
5615 bool V2Used = InputQuads[2] || InputQuads[3];
5616 if (Subtarget->hasSSSE3()) {
5617 if (InputQuads.count() == 2 && V1Used && V2Used) {
5618 BestLoQuad = InputQuads[0] ? 0 : 1;
5619 BestHiQuad = InputQuads[2] ? 2 : 3;
5621 if (InputQuads.count() > 2) {
5627 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5628 // the shuffle mask. If a quad is scored as -1, that means that it contains
5629 // words from all 4 input quadwords.
5631 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5633 BestLoQuad < 0 ? 0 : BestLoQuad,
5634 BestHiQuad < 0 ? 1 : BestHiQuad
5636 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5637 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5638 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5639 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5641 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5642 // source words for the shuffle, to aid later transformations.
5643 bool AllWordsInNewV = true;
5644 bool InOrder[2] = { true, true };
5645 for (unsigned i = 0; i != 8; ++i) {
5646 int idx = MaskVals[i];
5648 InOrder[i/4] = false;
5649 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5651 AllWordsInNewV = false;
5655 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5656 if (AllWordsInNewV) {
5657 for (int i = 0; i != 8; ++i) {
5658 int idx = MaskVals[i];
5661 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5662 if ((idx != i) && idx < 4)
5664 if ((idx != i) && idx > 3)
5673 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5674 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5675 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5676 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5677 unsigned TargetMask = 0;
5678 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5679 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5681 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5682 getShufflePSHUFLWImmediate(SVOp);
5683 V1 = NewV.getOperand(0);
5684 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5688 // If we have SSSE3, and all words of the result are from 1 input vector,
5689 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5690 // is present, fall back to case 4.
5691 if (Subtarget->hasSSSE3()) {
5692 SmallVector<SDValue,16> pshufbMask;
5694 // If we have elements from both input vectors, set the high bit of the
5695 // shuffle mask element to zero out elements that come from V2 in the V1
5696 // mask, and elements that come from V1 in the V2 mask, so that the two
5697 // results can be OR'd together.
5698 bool TwoInputs = V1Used && V2Used;
5699 for (unsigned i = 0; i != 8; ++i) {
5700 int EltIdx = MaskVals[i] * 2;
5701 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5702 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5703 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5704 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5706 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5707 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5708 DAG.getNode(ISD::BUILD_VECTOR, dl,
5709 MVT::v16i8, &pshufbMask[0], 16));
5711 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5713 // Calculate the shuffle mask for the second input, shuffle it, and
5714 // OR it with the first shuffled input.
5716 for (unsigned i = 0; i != 8; ++i) {
5717 int EltIdx = MaskVals[i] * 2;
5718 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5719 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5720 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5721 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5723 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5724 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5725 DAG.getNode(ISD::BUILD_VECTOR, dl,
5726 MVT::v16i8, &pshufbMask[0], 16));
5727 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5728 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5731 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5732 // and update MaskVals with new element order.
5733 std::bitset<8> InOrder;
5734 if (BestLoQuad >= 0) {
5735 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5736 for (int i = 0; i != 4; ++i) {
5737 int idx = MaskVals[i];
5740 } else if ((idx / 4) == BestLoQuad) {
5745 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5748 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5749 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5750 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5752 getShufflePSHUFLWImmediate(SVOp), DAG);
5756 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5757 // and update MaskVals with the new element order.
5758 if (BestHiQuad >= 0) {
5759 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5760 for (unsigned i = 4; i != 8; ++i) {
5761 int idx = MaskVals[i];
5764 } else if ((idx / 4) == BestHiQuad) {
5765 MaskV[i] = (idx & 3) + 4;
5769 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5772 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5773 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5774 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5776 getShufflePSHUFHWImmediate(SVOp), DAG);
5780 // In case BestHi & BestLo were both -1, which means each quadword has a word
5781 // from each of the four input quadwords, calculate the InOrder bitvector now
5782 // before falling through to the insert/extract cleanup.
5783 if (BestLoQuad == -1 && BestHiQuad == -1) {
5785 for (int i = 0; i != 8; ++i)
5786 if (MaskVals[i] < 0 || MaskVals[i] == i)
5790 // The other elements are put in the right place using pextrw and pinsrw.
5791 for (unsigned i = 0; i != 8; ++i) {
5794 int EltIdx = MaskVals[i];
5797 SDValue ExtOp = (EltIdx < 8) ?
5798 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5799 DAG.getIntPtrConstant(EltIdx)) :
5800 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5801 DAG.getIntPtrConstant(EltIdx - 8));
5802 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5803 DAG.getIntPtrConstant(i));
5808 // v16i8 shuffles - Prefer shuffles in the following order:
5809 // 1. [ssse3] 1 x pshufb
5810 // 2. [ssse3] 2 x pshufb + 1 x por
5811 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5813 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5815 const X86TargetLowering &TLI) {
5816 SDValue V1 = SVOp->getOperand(0);
5817 SDValue V2 = SVOp->getOperand(1);
5818 DebugLoc dl = SVOp->getDebugLoc();
5819 ArrayRef<int> MaskVals = SVOp->getMask();
5821 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5823 // If we have SSSE3, case 1 is generated when all result bytes come from
5824 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5825 // present, fall back to case 3.
5827 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5828 if (TLI.getSubtarget()->hasSSSE3()) {
5829 SmallVector<SDValue,16> pshufbMask;
5831 // If all result elements are from one input vector, then only translate
5832 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5834 // Otherwise, we have elements from both input vectors, and must zero out
5835 // elements that come from V2 in the first mask, and V1 in the second mask
5836 // so that we can OR them together.
5837 for (unsigned i = 0; i != 16; ++i) {
5838 int EltIdx = MaskVals[i];
5839 if (EltIdx < 0 || EltIdx >= 16)
5841 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5843 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5844 DAG.getNode(ISD::BUILD_VECTOR, dl,
5845 MVT::v16i8, &pshufbMask[0], 16));
5849 // Calculate the shuffle mask for the second input, shuffle it, and
5850 // OR it with the first shuffled input.
5852 for (unsigned i = 0; i != 16; ++i) {
5853 int EltIdx = MaskVals[i];
5854 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5855 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5857 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5858 DAG.getNode(ISD::BUILD_VECTOR, dl,
5859 MVT::v16i8, &pshufbMask[0], 16));
5860 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5863 // No SSSE3 - Calculate in place words and then fix all out of place words
5864 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5865 // the 16 different words that comprise the two doublequadword input vectors.
5866 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5867 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5869 for (int i = 0; i != 8; ++i) {
5870 int Elt0 = MaskVals[i*2];
5871 int Elt1 = MaskVals[i*2+1];
5873 // This word of the result is all undef, skip it.
5874 if (Elt0 < 0 && Elt1 < 0)
5877 // This word of the result is already in the correct place, skip it.
5878 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5881 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5882 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5885 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5886 // using a single extract together, load it and store it.
5887 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5888 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5889 DAG.getIntPtrConstant(Elt1 / 2));
5890 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5891 DAG.getIntPtrConstant(i));
5895 // If Elt1 is defined, extract it from the appropriate source. If the
5896 // source byte is not also odd, shift the extracted word left 8 bits
5897 // otherwise clear the bottom 8 bits if we need to do an or.
5899 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5900 DAG.getIntPtrConstant(Elt1 / 2));
5901 if ((Elt1 & 1) == 0)
5902 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5904 TLI.getShiftAmountTy(InsElt.getValueType())));
5906 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5907 DAG.getConstant(0xFF00, MVT::i16));
5909 // If Elt0 is defined, extract it from the appropriate source. If the
5910 // source byte is not also even, shift the extracted word right 8 bits. If
5911 // Elt1 was also defined, OR the extracted values together before
5912 // inserting them in the result.
5914 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5915 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5916 if ((Elt0 & 1) != 0)
5917 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5919 TLI.getShiftAmountTy(InsElt0.getValueType())));
5921 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5922 DAG.getConstant(0x00FF, MVT::i16));
5923 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5926 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5927 DAG.getIntPtrConstant(i));
5929 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5932 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5933 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5934 /// done when every pair / quad of shuffle mask elements point to elements in
5935 /// the right sequence. e.g.
5936 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5938 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5939 SelectionDAG &DAG, DebugLoc dl) {
5940 MVT VT = SVOp->getValueType(0).getSimpleVT();
5941 unsigned NumElems = VT.getVectorNumElements();
5944 switch (VT.SimpleTy) {
5945 default: llvm_unreachable("Unexpected!");
5946 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
5947 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
5948 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
5949 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
5950 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5951 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
5954 SmallVector<int, 8> MaskVec;
5955 for (unsigned i = 0; i != NumElems; i += Scale) {
5957 for (unsigned j = 0; j != Scale; ++j) {
5958 int EltIdx = SVOp->getMaskElt(i+j);
5962 StartIdx = (EltIdx / Scale);
5963 if (EltIdx != (int)(StartIdx*Scale + j))
5966 MaskVec.push_back(StartIdx);
5969 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5970 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5971 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5974 /// getVZextMovL - Return a zero-extending vector move low node.
5976 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5977 SDValue SrcOp, SelectionDAG &DAG,
5978 const X86Subtarget *Subtarget, DebugLoc dl) {
5979 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5980 LoadSDNode *LD = NULL;
5981 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5982 LD = dyn_cast<LoadSDNode>(SrcOp);
5984 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5986 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5987 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5988 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5989 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5990 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5992 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5993 return DAG.getNode(ISD::BITCAST, dl, VT,
5994 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5995 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6003 return DAG.getNode(ISD::BITCAST, dl, VT,
6004 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6005 DAG.getNode(ISD::BITCAST, dl,
6009 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6010 /// which could not be matched by any known target speficic shuffle
6012 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6014 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6015 if (NewOp.getNode())
6018 EVT VT = SVOp->getValueType(0);
6020 unsigned NumElems = VT.getVectorNumElements();
6021 unsigned NumLaneElems = NumElems / 2;
6023 DebugLoc dl = SVOp->getDebugLoc();
6024 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6025 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6028 SmallVector<int, 16> Mask;
6029 for (unsigned l = 0; l < 2; ++l) {
6030 // Build a shuffle mask for the output, discovering on the fly which
6031 // input vectors to use as shuffle operands (recorded in InputUsed).
6032 // If building a suitable shuffle vector proves too hard, then bail
6033 // out with UseBuildVector set.
6034 bool UseBuildVector = false;
6035 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6036 unsigned LaneStart = l * NumLaneElems;
6037 for (unsigned i = 0; i != NumLaneElems; ++i) {
6038 // The mask element. This indexes into the input.
6039 int Idx = SVOp->getMaskElt(i+LaneStart);
6041 // the mask element does not index into any input vector.
6046 // The input vector this mask element indexes into.
6047 int Input = Idx / NumLaneElems;
6049 // Turn the index into an offset from the start of the input vector.
6050 Idx -= Input * NumLaneElems;
6052 // Find or create a shuffle vector operand to hold this input.
6054 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6055 if (InputUsed[OpNo] == Input)
6056 // This input vector is already an operand.
6058 if (InputUsed[OpNo] < 0) {
6059 // Create a new operand for this input vector.
6060 InputUsed[OpNo] = Input;
6065 if (OpNo >= array_lengthof(InputUsed)) {
6066 // More than two input vectors used! Give up on trying to create a
6067 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6068 UseBuildVector = true;
6072 // Add the mask index for the new shuffle vector.
6073 Mask.push_back(Idx + OpNo * NumLaneElems);
6076 if (UseBuildVector) {
6077 SmallVector<SDValue, 16> SVOps;
6078 for (unsigned i = 0; i != NumLaneElems; ++i) {
6079 // The mask element. This indexes into the input.
6080 int Idx = SVOp->getMaskElt(i+LaneStart);
6082 SVOps.push_back(DAG.getUNDEF(EltVT));
6086 // The input vector this mask element indexes into.
6087 int Input = Idx / NumElems;
6089 // Turn the index into an offset from the start of the input vector.
6090 Idx -= Input * NumElems;
6092 // Extract the vector element by hand.
6093 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6094 SVOp->getOperand(Input),
6095 DAG.getIntPtrConstant(Idx)));
6098 // Construct the output using a BUILD_VECTOR.
6099 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6101 } else if (InputUsed[0] < 0) {
6102 // No input vectors were used! The result is undefined.
6103 Output[l] = DAG.getUNDEF(NVT);
6105 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6106 (InputUsed[0] % 2) * NumLaneElems,
6108 // If only one input was used, use an undefined vector for the other.
6109 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6110 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6111 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6112 // At least one input vector was used. Create a new shuffle vector.
6113 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6119 // Concatenate the result back
6120 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6123 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6124 /// 4 elements, and match them with several different shuffle types.
6126 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6127 SDValue V1 = SVOp->getOperand(0);
6128 SDValue V2 = SVOp->getOperand(1);
6129 DebugLoc dl = SVOp->getDebugLoc();
6130 EVT VT = SVOp->getValueType(0);
6132 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6134 std::pair<int, int> Locs[4];
6135 int Mask1[] = { -1, -1, -1, -1 };
6136 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6140 for (unsigned i = 0; i != 4; ++i) {
6141 int Idx = PermMask[i];
6143 Locs[i] = std::make_pair(-1, -1);
6145 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6147 Locs[i] = std::make_pair(0, NumLo);
6151 Locs[i] = std::make_pair(1, NumHi);
6153 Mask1[2+NumHi] = Idx;
6159 if (NumLo <= 2 && NumHi <= 2) {
6160 // If no more than two elements come from either vector. This can be
6161 // implemented with two shuffles. First shuffle gather the elements.
6162 // The second shuffle, which takes the first shuffle as both of its
6163 // vector operands, put the elements into the right order.
6164 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6166 int Mask2[] = { -1, -1, -1, -1 };
6168 for (unsigned i = 0; i != 4; ++i)
6169 if (Locs[i].first != -1) {
6170 unsigned Idx = (i < 2) ? 0 : 4;
6171 Idx += Locs[i].first * 2 + Locs[i].second;
6175 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6178 if (NumLo == 3 || NumHi == 3) {
6179 // Otherwise, we must have three elements from one vector, call it X, and
6180 // one element from the other, call it Y. First, use a shufps to build an
6181 // intermediate vector with the one element from Y and the element from X
6182 // that will be in the same half in the final destination (the indexes don't
6183 // matter). Then, use a shufps to build the final vector, taking the half
6184 // containing the element from Y from the intermediate, and the other half
6187 // Normalize it so the 3 elements come from V1.
6188 CommuteVectorShuffleMask(PermMask, 4);
6192 // Find the element from V2.
6194 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6195 int Val = PermMask[HiIndex];
6202 Mask1[0] = PermMask[HiIndex];
6204 Mask1[2] = PermMask[HiIndex^1];
6206 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6209 Mask1[0] = PermMask[0];
6210 Mask1[1] = PermMask[1];
6211 Mask1[2] = HiIndex & 1 ? 6 : 4;
6212 Mask1[3] = HiIndex & 1 ? 4 : 6;
6213 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6216 Mask1[0] = HiIndex & 1 ? 2 : 0;
6217 Mask1[1] = HiIndex & 1 ? 0 : 2;
6218 Mask1[2] = PermMask[2];
6219 Mask1[3] = PermMask[3];
6224 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6227 // Break it into (shuffle shuffle_hi, shuffle_lo).
6228 int LoMask[] = { -1, -1, -1, -1 };
6229 int HiMask[] = { -1, -1, -1, -1 };
6231 int *MaskPtr = LoMask;
6232 unsigned MaskIdx = 0;
6235 for (unsigned i = 0; i != 4; ++i) {
6242 int Idx = PermMask[i];
6244 Locs[i] = std::make_pair(-1, -1);
6245 } else if (Idx < 4) {
6246 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6247 MaskPtr[LoIdx] = Idx;
6250 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6251 MaskPtr[HiIdx] = Idx;
6256 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6257 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6258 int MaskOps[] = { -1, -1, -1, -1 };
6259 for (unsigned i = 0; i != 4; ++i)
6260 if (Locs[i].first != -1)
6261 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6262 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6265 static bool MayFoldVectorLoad(SDValue V) {
6266 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6267 V = V.getOperand(0);
6268 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6269 V = V.getOperand(0);
6270 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6271 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6272 // BUILD_VECTOR (load), undef
6273 V = V.getOperand(0);
6279 // FIXME: the version above should always be used. Since there's
6280 // a bug where several vector shuffles can't be folded because the
6281 // DAG is not updated during lowering and a node claims to have two
6282 // uses while it only has one, use this version, and let isel match
6283 // another instruction if the load really happens to have more than
6284 // one use. Remove this version after this bug get fixed.
6285 // rdar://8434668, PR8156
6286 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6287 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6288 V = V.getOperand(0);
6289 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6290 V = V.getOperand(0);
6291 if (ISD::isNormalLoad(V.getNode()))
6297 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6298 EVT VT = Op.getValueType();
6300 // Canonizalize to v2f64.
6301 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6302 return DAG.getNode(ISD::BITCAST, dl, VT,
6303 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6308 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6310 SDValue V1 = Op.getOperand(0);
6311 SDValue V2 = Op.getOperand(1);
6312 EVT VT = Op.getValueType();
6314 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6316 if (HasSSE2 && VT == MVT::v2f64)
6317 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6319 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6320 return DAG.getNode(ISD::BITCAST, dl, VT,
6321 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6322 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6323 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6327 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6328 SDValue V1 = Op.getOperand(0);
6329 SDValue V2 = Op.getOperand(1);
6330 EVT VT = Op.getValueType();
6332 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6333 "unsupported shuffle type");
6335 if (V2.getOpcode() == ISD::UNDEF)
6339 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6343 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6344 SDValue V1 = Op.getOperand(0);
6345 SDValue V2 = Op.getOperand(1);
6346 EVT VT = Op.getValueType();
6347 unsigned NumElems = VT.getVectorNumElements();
6349 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6350 // operand of these instructions is only memory, so check if there's a
6351 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6353 bool CanFoldLoad = false;
6355 // Trivial case, when V2 comes from a load.
6356 if (MayFoldVectorLoad(V2))
6359 // When V1 is a load, it can be folded later into a store in isel, example:
6360 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6362 // (MOVLPSmr addr:$src1, VR128:$src2)
6363 // So, recognize this potential and also use MOVLPS or MOVLPD
6364 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6367 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6369 if (HasSSE2 && NumElems == 2)
6370 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6373 // If we don't care about the second element, proceed to use movss.
6374 if (SVOp->getMaskElt(1) != -1)
6375 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6378 // movl and movlp will both match v2i64, but v2i64 is never matched by
6379 // movl earlier because we make it strict to avoid messing with the movlp load
6380 // folding logic (see the code above getMOVLP call). Match it here then,
6381 // this is horrible, but will stay like this until we move all shuffle
6382 // matching to x86 specific nodes. Note that for the 1st condition all
6383 // types are matched with movsd.
6385 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6386 // as to remove this logic from here, as much as possible
6387 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6388 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6389 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6392 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6394 // Invert the operand order and use SHUFPS to match it.
6395 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6396 getShuffleSHUFImmediate(SVOp), DAG);
6400 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6401 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6402 EVT VT = Op.getValueType();
6403 DebugLoc dl = Op.getDebugLoc();
6404 SDValue V1 = Op.getOperand(0);
6405 SDValue V2 = Op.getOperand(1);
6407 if (isZeroShuffle(SVOp))
6408 return getZeroVector(VT, Subtarget, DAG, dl);
6410 // Handle splat operations
6411 if (SVOp->isSplat()) {
6412 unsigned NumElem = VT.getVectorNumElements();
6413 int Size = VT.getSizeInBits();
6415 // Use vbroadcast whenever the splat comes from a foldable load
6416 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6417 if (Broadcast.getNode())
6420 // Handle splats by matching through known shuffle masks
6421 if ((Size == 128 && NumElem <= 4) ||
6422 (Size == 256 && NumElem < 8))
6425 // All remaning splats are promoted to target supported vector shuffles.
6426 return PromoteSplat(SVOp, DAG);
6429 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6431 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6432 VT == MVT::v16i16 || VT == MVT::v32i8) {
6433 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6434 if (NewOp.getNode())
6435 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6436 } else if ((VT == MVT::v4i32 ||
6437 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6438 // FIXME: Figure out a cleaner way to do this.
6439 // Try to make use of movq to zero out the top part.
6440 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6441 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6442 if (NewOp.getNode()) {
6443 EVT NewVT = NewOp.getValueType();
6444 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6445 NewVT, true, false))
6446 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6447 DAG, Subtarget, dl);
6449 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6450 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6451 if (NewOp.getNode()) {
6452 EVT NewVT = NewOp.getValueType();
6453 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6454 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6455 DAG, Subtarget, dl);
6463 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6464 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6465 SDValue V1 = Op.getOperand(0);
6466 SDValue V2 = Op.getOperand(1);
6467 EVT VT = Op.getValueType();
6468 DebugLoc dl = Op.getDebugLoc();
6469 unsigned NumElems = VT.getVectorNumElements();
6470 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6471 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6472 bool V1IsSplat = false;
6473 bool V2IsSplat = false;
6474 bool HasSSE2 = Subtarget->hasSSE2();
6475 bool HasAVX = Subtarget->hasAVX();
6476 bool HasAVX2 = Subtarget->hasAVX2();
6477 MachineFunction &MF = DAG.getMachineFunction();
6478 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6480 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6482 if (V1IsUndef && V2IsUndef)
6483 return DAG.getUNDEF(VT);
6485 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6487 // Vector shuffle lowering takes 3 steps:
6489 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6490 // narrowing and commutation of operands should be handled.
6491 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6493 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6494 // so the shuffle can be broken into other shuffles and the legalizer can
6495 // try the lowering again.
6497 // The general idea is that no vector_shuffle operation should be left to
6498 // be matched during isel, all of them must be converted to a target specific
6501 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6502 // narrowing and commutation of operands should be handled. The actual code
6503 // doesn't include all of those, work in progress...
6504 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6505 if (NewOp.getNode())
6508 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6510 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6511 // unpckh_undef). Only use pshufd if speed is more important than size.
6512 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6513 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6514 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6515 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6517 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6518 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6519 return getMOVDDup(Op, dl, V1, DAG);
6521 if (isMOVHLPS_v_undef_Mask(M, VT))
6522 return getMOVHighToLow(Op, dl, DAG);
6524 // Use to match splats
6525 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6526 (VT == MVT::v2f64 || VT == MVT::v2i64))
6527 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6529 if (isPSHUFDMask(M, VT)) {
6530 // The actual implementation will match the mask in the if above and then
6531 // during isel it can match several different instructions, not only pshufd
6532 // as its name says, sad but true, emulate the behavior for now...
6533 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6534 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6536 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6538 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6539 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6541 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6542 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6544 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6548 // Check if this can be converted into a logical shift.
6549 bool isLeft = false;
6552 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6553 if (isShift && ShVal.hasOneUse()) {
6554 // If the shifted value has multiple uses, it may be cheaper to use
6555 // v_set0 + movlhps or movhlps, etc.
6556 EVT EltVT = VT.getVectorElementType();
6557 ShAmt *= EltVT.getSizeInBits();
6558 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6561 if (isMOVLMask(M, VT)) {
6562 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6563 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6564 if (!isMOVLPMask(M, VT)) {
6565 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6566 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6568 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6569 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6573 // FIXME: fold these into legal mask.
6574 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6575 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6577 if (isMOVHLPSMask(M, VT))
6578 return getMOVHighToLow(Op, dl, DAG);
6580 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6581 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6583 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6584 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6586 if (isMOVLPMask(M, VT))
6587 return getMOVLP(Op, dl, DAG, HasSSE2);
6589 if (ShouldXformToMOVHLPS(M, VT) ||
6590 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6591 return CommuteVectorShuffle(SVOp, DAG);
6594 // No better options. Use a vshldq / vsrldq.
6595 EVT EltVT = VT.getVectorElementType();
6596 ShAmt *= EltVT.getSizeInBits();
6597 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6600 bool Commuted = false;
6601 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6602 // 1,1,1,1 -> v8i16 though.
6603 V1IsSplat = isSplatVector(V1.getNode());
6604 V2IsSplat = isSplatVector(V2.getNode());
6606 // Canonicalize the splat or undef, if present, to be on the RHS.
6607 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6608 CommuteVectorShuffleMask(M, NumElems);
6610 std::swap(V1IsSplat, V2IsSplat);
6614 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6615 // Shuffling low element of v1 into undef, just return v1.
6618 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6619 // the instruction selector will not match, so get a canonical MOVL with
6620 // swapped operands to undo the commute.
6621 return getMOVL(DAG, dl, VT, V2, V1);
6624 if (isUNPCKLMask(M, VT, HasAVX2))
6625 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6627 if (isUNPCKHMask(M, VT, HasAVX2))
6628 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6631 // Normalize mask so all entries that point to V2 points to its first
6632 // element then try to match unpck{h|l} again. If match, return a
6633 // new vector_shuffle with the corrected mask.p
6634 SmallVector<int, 8> NewMask(M.begin(), M.end());
6635 NormalizeMask(NewMask, NumElems);
6636 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6637 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6638 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6639 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6643 // Commute is back and try unpck* again.
6644 // FIXME: this seems wrong.
6645 CommuteVectorShuffleMask(M, NumElems);
6647 std::swap(V1IsSplat, V2IsSplat);
6650 if (isUNPCKLMask(M, VT, HasAVX2))
6651 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6653 if (isUNPCKHMask(M, VT, HasAVX2))
6654 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6657 // Normalize the node to match x86 shuffle ops if needed
6658 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6659 return CommuteVectorShuffle(SVOp, DAG);
6661 // The checks below are all present in isShuffleMaskLegal, but they are
6662 // inlined here right now to enable us to directly emit target specific
6663 // nodes, and remove one by one until they don't return Op anymore.
6665 if (isPALIGNRMask(M, VT, Subtarget))
6666 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6667 getShufflePALIGNRImmediate(SVOp),
6670 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6671 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6672 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6673 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6676 if (isPSHUFHWMask(M, VT, HasAVX2))
6677 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6678 getShufflePSHUFHWImmediate(SVOp),
6681 if (isPSHUFLWMask(M, VT, HasAVX2))
6682 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6683 getShufflePSHUFLWImmediate(SVOp),
6686 if (isSHUFPMask(M, VT, HasAVX))
6687 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6688 getShuffleSHUFImmediate(SVOp), DAG);
6690 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6691 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6692 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6693 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6695 //===--------------------------------------------------------------------===//
6696 // Generate target specific nodes for 128 or 256-bit shuffles only
6697 // supported in the AVX instruction set.
6700 // Handle VMOVDDUPY permutations
6701 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6702 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6704 // Handle VPERMILPS/D* permutations
6705 if (isVPERMILPMask(M, VT, HasAVX)) {
6706 if (HasAVX2 && VT == MVT::v8i32)
6707 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6708 getShuffleSHUFImmediate(SVOp), DAG);
6709 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6710 getShuffleSHUFImmediate(SVOp), DAG);
6713 // Handle VPERM2F128/VPERM2I128 permutations
6714 if (isVPERM2X128Mask(M, VT, HasAVX))
6715 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6716 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6718 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6719 if (BlendOp.getNode())
6722 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6723 SmallVector<SDValue, 8> permclMask;
6724 for (unsigned i = 0; i != 8; ++i) {
6725 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6727 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6729 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6730 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6731 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6734 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6735 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6736 getShuffleCLImmediate(SVOp), DAG);
6739 //===--------------------------------------------------------------------===//
6740 // Since no target specific shuffle was selected for this generic one,
6741 // lower it into other known shuffles. FIXME: this isn't true yet, but
6742 // this is the plan.
6745 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6746 if (VT == MVT::v8i16) {
6747 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6748 if (NewOp.getNode())
6752 if (VT == MVT::v16i8) {
6753 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6754 if (NewOp.getNode())
6758 // Handle all 128-bit wide vectors with 4 elements, and match them with
6759 // several different shuffle types.
6760 if (NumElems == 4 && VT.getSizeInBits() == 128)
6761 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6763 // Handle general 256-bit shuffles
6764 if (VT.is256BitVector())
6765 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6771 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6772 SelectionDAG &DAG) const {
6773 EVT VT = Op.getValueType();
6774 DebugLoc dl = Op.getDebugLoc();
6776 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6779 if (VT.getSizeInBits() == 8) {
6780 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6781 Op.getOperand(0), Op.getOperand(1));
6782 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6783 DAG.getValueType(VT));
6784 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6787 if (VT.getSizeInBits() == 16) {
6788 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6789 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6791 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6792 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6793 DAG.getNode(ISD::BITCAST, dl,
6797 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6798 Op.getOperand(0), Op.getOperand(1));
6799 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6800 DAG.getValueType(VT));
6801 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6804 if (VT == MVT::f32) {
6805 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6806 // the result back to FR32 register. It's only worth matching if the
6807 // result has a single use which is a store or a bitcast to i32. And in
6808 // the case of a store, it's not worth it if the index is a constant 0,
6809 // because a MOVSSmr can be used instead, which is smaller and faster.
6810 if (!Op.hasOneUse())
6812 SDNode *User = *Op.getNode()->use_begin();
6813 if ((User->getOpcode() != ISD::STORE ||
6814 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6815 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6816 (User->getOpcode() != ISD::BITCAST ||
6817 User->getValueType(0) != MVT::i32))
6819 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6820 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6823 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6826 if (VT == MVT::i32 || VT == MVT::i64) {
6827 // ExtractPS/pextrq works with constant index.
6828 if (isa<ConstantSDNode>(Op.getOperand(1)))
6836 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6837 SelectionDAG &DAG) const {
6838 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6841 SDValue Vec = Op.getOperand(0);
6842 EVT VecVT = Vec.getValueType();
6844 // If this is a 256-bit vector result, first extract the 128-bit vector and
6845 // then extract the element from the 128-bit vector.
6846 if (VecVT.getSizeInBits() == 256) {
6847 DebugLoc dl = Op.getNode()->getDebugLoc();
6848 unsigned NumElems = VecVT.getVectorNumElements();
6849 SDValue Idx = Op.getOperand(1);
6850 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6852 // Get the 128-bit vector.
6853 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6855 if (IdxVal >= NumElems/2)
6856 IdxVal -= NumElems/2;
6857 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6858 DAG.getConstant(IdxVal, MVT::i32));
6861 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6863 if (Subtarget->hasSSE41()) {
6864 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6869 EVT VT = Op.getValueType();
6870 DebugLoc dl = Op.getDebugLoc();
6871 // TODO: handle v16i8.
6872 if (VT.getSizeInBits() == 16) {
6873 SDValue Vec = Op.getOperand(0);
6874 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6876 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6877 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6878 DAG.getNode(ISD::BITCAST, dl,
6881 // Transform it so it match pextrw which produces a 32-bit result.
6882 EVT EltVT = MVT::i32;
6883 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6884 Op.getOperand(0), Op.getOperand(1));
6885 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6886 DAG.getValueType(VT));
6887 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6890 if (VT.getSizeInBits() == 32) {
6891 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6895 // SHUFPS the element to the lowest double word, then movss.
6896 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6897 EVT VVT = Op.getOperand(0).getValueType();
6898 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6899 DAG.getUNDEF(VVT), Mask);
6900 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6901 DAG.getIntPtrConstant(0));
6904 if (VT.getSizeInBits() == 64) {
6905 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6906 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6907 // to match extract_elt for f64.
6908 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6912 // UNPCKHPD the element to the lowest double word, then movsd.
6913 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6914 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6915 int Mask[2] = { 1, -1 };
6916 EVT VVT = Op.getOperand(0).getValueType();
6917 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6918 DAG.getUNDEF(VVT), Mask);
6919 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6920 DAG.getIntPtrConstant(0));
6927 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6928 SelectionDAG &DAG) const {
6929 EVT VT = Op.getValueType();
6930 EVT EltVT = VT.getVectorElementType();
6931 DebugLoc dl = Op.getDebugLoc();
6933 SDValue N0 = Op.getOperand(0);
6934 SDValue N1 = Op.getOperand(1);
6935 SDValue N2 = Op.getOperand(2);
6937 if (VT.getSizeInBits() == 256)
6940 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6941 isa<ConstantSDNode>(N2)) {
6943 if (VT == MVT::v8i16)
6944 Opc = X86ISD::PINSRW;
6945 else if (VT == MVT::v16i8)
6946 Opc = X86ISD::PINSRB;
6948 Opc = X86ISD::PINSRB;
6950 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6952 if (N1.getValueType() != MVT::i32)
6953 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6954 if (N2.getValueType() != MVT::i32)
6955 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6956 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6959 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6960 // Bits [7:6] of the constant are the source select. This will always be
6961 // zero here. The DAG Combiner may combine an extract_elt index into these
6962 // bits. For example (insert (extract, 3), 2) could be matched by putting
6963 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6964 // Bits [5:4] of the constant are the destination select. This is the
6965 // value of the incoming immediate.
6966 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6967 // combine either bitwise AND or insert of float 0.0 to set these bits.
6968 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6969 // Create this as a scalar to vector..
6970 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6971 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6974 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6975 // PINSR* works with constant index.
6982 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6983 EVT VT = Op.getValueType();
6984 EVT EltVT = VT.getVectorElementType();
6986 DebugLoc dl = Op.getDebugLoc();
6987 SDValue N0 = Op.getOperand(0);
6988 SDValue N1 = Op.getOperand(1);
6989 SDValue N2 = Op.getOperand(2);
6991 // If this is a 256-bit vector result, first extract the 128-bit vector,
6992 // insert the element into the extracted half and then place it back.
6993 if (VT.getSizeInBits() == 256) {
6994 if (!isa<ConstantSDNode>(N2))
6997 // Get the desired 128-bit vector half.
6998 unsigned NumElems = VT.getVectorNumElements();
6999 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7000 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7002 // Insert the element into the desired half.
7003 bool Upper = IdxVal >= NumElems/2;
7004 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7005 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7007 // Insert the changed part back to the 256-bit vector
7008 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7011 if (Subtarget->hasSSE41())
7012 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7014 if (EltVT == MVT::i8)
7017 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7018 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7019 // as its second argument.
7020 if (N1.getValueType() != MVT::i32)
7021 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7022 if (N2.getValueType() != MVT::i32)
7023 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7024 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7030 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7031 LLVMContext *Context = DAG.getContext();
7032 DebugLoc dl = Op.getDebugLoc();
7033 EVT OpVT = Op.getValueType();
7035 // If this is a 256-bit vector result, first insert into a 128-bit
7036 // vector and then insert into the 256-bit vector.
7037 if (OpVT.getSizeInBits() > 128) {
7038 // Insert into a 128-bit vector.
7039 EVT VT128 = EVT::getVectorVT(*Context,
7040 OpVT.getVectorElementType(),
7041 OpVT.getVectorNumElements() / 2);
7043 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7045 // Insert the 128-bit vector.
7046 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7049 if (OpVT == MVT::v1i64 &&
7050 Op.getOperand(0).getValueType() == MVT::i64)
7051 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7053 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7054 assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7055 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7056 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7059 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7060 // a simple subregister reference or explicit instructions to grab
7061 // upper bits of a vector.
7063 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7064 if (Subtarget->hasAVX()) {
7065 DebugLoc dl = Op.getNode()->getDebugLoc();
7066 SDValue Vec = Op.getNode()->getOperand(0);
7067 SDValue Idx = Op.getNode()->getOperand(1);
7069 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7070 Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7071 isa<ConstantSDNode>(Idx)) {
7072 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7073 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7079 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7080 // simple superregister reference or explicit instructions to insert
7081 // the upper bits of a vector.
7083 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7084 if (Subtarget->hasAVX()) {
7085 DebugLoc dl = Op.getNode()->getDebugLoc();
7086 SDValue Vec = Op.getNode()->getOperand(0);
7087 SDValue SubVec = Op.getNode()->getOperand(1);
7088 SDValue Idx = Op.getNode()->getOperand(2);
7090 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7091 SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7092 isa<ConstantSDNode>(Idx)) {
7093 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7094 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7100 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7101 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7102 // one of the above mentioned nodes. It has to be wrapped because otherwise
7103 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7104 // be used to form addressing mode. These wrapped nodes will be selected
7107 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7108 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7110 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7112 unsigned char OpFlag = 0;
7113 unsigned WrapperKind = X86ISD::Wrapper;
7114 CodeModel::Model M = getTargetMachine().getCodeModel();
7116 if (Subtarget->isPICStyleRIPRel() &&
7117 (M == CodeModel::Small || M == CodeModel::Kernel))
7118 WrapperKind = X86ISD::WrapperRIP;
7119 else if (Subtarget->isPICStyleGOT())
7120 OpFlag = X86II::MO_GOTOFF;
7121 else if (Subtarget->isPICStyleStubPIC())
7122 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7124 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7126 CP->getOffset(), OpFlag);
7127 DebugLoc DL = CP->getDebugLoc();
7128 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7129 // With PIC, the address is actually $g + Offset.
7131 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7132 DAG.getNode(X86ISD::GlobalBaseReg,
7133 DebugLoc(), getPointerTy()),
7140 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7141 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7143 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7145 unsigned char OpFlag = 0;
7146 unsigned WrapperKind = X86ISD::Wrapper;
7147 CodeModel::Model M = getTargetMachine().getCodeModel();
7149 if (Subtarget->isPICStyleRIPRel() &&
7150 (M == CodeModel::Small || M == CodeModel::Kernel))
7151 WrapperKind = X86ISD::WrapperRIP;
7152 else if (Subtarget->isPICStyleGOT())
7153 OpFlag = X86II::MO_GOTOFF;
7154 else if (Subtarget->isPICStyleStubPIC())
7155 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7157 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7159 DebugLoc DL = JT->getDebugLoc();
7160 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7162 // With PIC, the address is actually $g + Offset.
7164 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7165 DAG.getNode(X86ISD::GlobalBaseReg,
7166 DebugLoc(), getPointerTy()),
7173 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7174 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7176 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7178 unsigned char OpFlag = 0;
7179 unsigned WrapperKind = X86ISD::Wrapper;
7180 CodeModel::Model M = getTargetMachine().getCodeModel();
7182 if (Subtarget->isPICStyleRIPRel() &&
7183 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7184 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7185 OpFlag = X86II::MO_GOTPCREL;
7186 WrapperKind = X86ISD::WrapperRIP;
7187 } else if (Subtarget->isPICStyleGOT()) {
7188 OpFlag = X86II::MO_GOT;
7189 } else if (Subtarget->isPICStyleStubPIC()) {
7190 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7191 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7192 OpFlag = X86II::MO_DARWIN_NONLAZY;
7195 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7197 DebugLoc DL = Op.getDebugLoc();
7198 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7201 // With PIC, the address is actually $g + Offset.
7202 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7203 !Subtarget->is64Bit()) {
7204 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7205 DAG.getNode(X86ISD::GlobalBaseReg,
7206 DebugLoc(), getPointerTy()),
7210 // For symbols that require a load from a stub to get the address, emit the
7212 if (isGlobalStubReference(OpFlag))
7213 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7214 MachinePointerInfo::getGOT(), false, false, false, 0);
7220 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7221 // Create the TargetBlockAddressAddress node.
7222 unsigned char OpFlags =
7223 Subtarget->ClassifyBlockAddressReference();
7224 CodeModel::Model M = getTargetMachine().getCodeModel();
7225 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7226 DebugLoc dl = Op.getDebugLoc();
7227 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7228 /*isTarget=*/true, OpFlags);
7230 if (Subtarget->isPICStyleRIPRel() &&
7231 (M == CodeModel::Small || M == CodeModel::Kernel))
7232 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7234 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7236 // With PIC, the address is actually $g + Offset.
7237 if (isGlobalRelativeToPICBase(OpFlags)) {
7238 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7239 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7247 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7249 SelectionDAG &DAG) const {
7250 // Create the TargetGlobalAddress node, folding in the constant
7251 // offset if it is legal.
7252 unsigned char OpFlags =
7253 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7254 CodeModel::Model M = getTargetMachine().getCodeModel();
7256 if (OpFlags == X86II::MO_NO_FLAG &&
7257 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7258 // A direct static reference to a global.
7259 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7262 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7265 if (Subtarget->isPICStyleRIPRel() &&
7266 (M == CodeModel::Small || M == CodeModel::Kernel))
7267 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7269 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7271 // With PIC, the address is actually $g + Offset.
7272 if (isGlobalRelativeToPICBase(OpFlags)) {
7273 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7274 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7278 // For globals that require a load from a stub to get the address, emit the
7280 if (isGlobalStubReference(OpFlags))
7281 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7282 MachinePointerInfo::getGOT(), false, false, false, 0);
7284 // If there was a non-zero offset that we didn't fold, create an explicit
7287 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7288 DAG.getConstant(Offset, getPointerTy()));
7294 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7295 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7296 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7297 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7301 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7302 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7303 unsigned char OperandFlags, bool LocalDynamic = false) {
7304 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7305 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7306 DebugLoc dl = GA->getDebugLoc();
7307 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7308 GA->getValueType(0),
7312 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7316 SDValue Ops[] = { Chain, TGA, *InFlag };
7317 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7319 SDValue Ops[] = { Chain, TGA };
7320 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7323 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7324 MFI->setAdjustsStack(true);
7326 SDValue Flag = Chain.getValue(1);
7327 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7330 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7332 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7335 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7336 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7337 DAG.getNode(X86ISD::GlobalBaseReg,
7338 DebugLoc(), PtrVT), InFlag);
7339 InFlag = Chain.getValue(1);
7341 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7344 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7346 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7348 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7349 X86::RAX, X86II::MO_TLSGD);
7352 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7356 DebugLoc dl = GA->getDebugLoc();
7358 // Get the start address of the TLS block for this module.
7359 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7360 .getInfo<X86MachineFunctionInfo>();
7361 MFI->incNumLocalDynamicTLSAccesses();
7365 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7366 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7369 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7370 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7371 InFlag = Chain.getValue(1);
7372 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7373 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7376 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7380 unsigned char OperandFlags = X86II::MO_DTPOFF;
7381 unsigned WrapperKind = X86ISD::Wrapper;
7382 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7383 GA->getValueType(0),
7384 GA->getOffset(), OperandFlags);
7385 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7387 // Add x@dtpoff with the base.
7388 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7391 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7392 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7393 const EVT PtrVT, TLSModel::Model model,
7394 bool is64Bit, bool isPIC) {
7395 DebugLoc dl = GA->getDebugLoc();
7397 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7398 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7399 is64Bit ? 257 : 256));
7401 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7402 DAG.getIntPtrConstant(0),
7403 MachinePointerInfo(Ptr),
7404 false, false, false, 0);
7406 unsigned char OperandFlags = 0;
7407 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7409 unsigned WrapperKind = X86ISD::Wrapper;
7410 if (model == TLSModel::LocalExec) {
7411 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7412 } else if (model == TLSModel::InitialExec) {
7414 OperandFlags = X86II::MO_GOTTPOFF;
7415 WrapperKind = X86ISD::WrapperRIP;
7417 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7420 llvm_unreachable("Unexpected model");
7423 // emit "addl x@ntpoff,%eax" (local exec)
7424 // or "addl x@indntpoff,%eax" (initial exec)
7425 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7426 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7427 GA->getValueType(0),
7428 GA->getOffset(), OperandFlags);
7429 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7431 if (model == TLSModel::InitialExec) {
7432 if (isPIC && !is64Bit) {
7433 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7434 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7438 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7439 MachinePointerInfo::getGOT(), false, false, false,
7443 // The address of the thread local variable is the add of the thread
7444 // pointer with the offset of the variable.
7445 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7449 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7451 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7452 const GlobalValue *GV = GA->getGlobal();
7454 if (Subtarget->isTargetELF()) {
7455 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7458 case TLSModel::GeneralDynamic:
7459 if (Subtarget->is64Bit())
7460 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7461 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7462 case TLSModel::LocalDynamic:
7463 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7464 Subtarget->is64Bit());
7465 case TLSModel::InitialExec:
7466 case TLSModel::LocalExec:
7467 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7468 Subtarget->is64Bit(),
7469 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7471 llvm_unreachable("Unknown TLS model.");
7474 if (Subtarget->isTargetDarwin()) {
7475 // Darwin only has one model of TLS. Lower to that.
7476 unsigned char OpFlag = 0;
7477 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7478 X86ISD::WrapperRIP : X86ISD::Wrapper;
7480 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7482 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7483 !Subtarget->is64Bit();
7485 OpFlag = X86II::MO_TLVP_PIC_BASE;
7487 OpFlag = X86II::MO_TLVP;
7488 DebugLoc DL = Op.getDebugLoc();
7489 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7490 GA->getValueType(0),
7491 GA->getOffset(), OpFlag);
7492 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7494 // With PIC32, the address is actually $g + Offset.
7496 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7497 DAG.getNode(X86ISD::GlobalBaseReg,
7498 DebugLoc(), getPointerTy()),
7501 // Lowering the machine isd will make sure everything is in the right
7503 SDValue Chain = DAG.getEntryNode();
7504 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7505 SDValue Args[] = { Chain, Offset };
7506 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7508 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7509 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7510 MFI->setAdjustsStack(true);
7512 // And our return value (tls address) is in the standard call return value
7514 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7515 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7519 if (Subtarget->isTargetWindows()) {
7520 // Just use the implicit TLS architecture
7521 // Need to generate someting similar to:
7522 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7524 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7525 // mov rcx, qword [rdx+rcx*8]
7526 // mov eax, .tls$:tlsvar
7527 // [rax+rcx] contains the address
7528 // Windows 64bit: gs:0x58
7529 // Windows 32bit: fs:__tls_array
7531 // If GV is an alias then use the aliasee for determining
7532 // thread-localness.
7533 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7534 GV = GA->resolveAliasedGlobal(false);
7535 DebugLoc dl = GA->getDebugLoc();
7536 SDValue Chain = DAG.getEntryNode();
7538 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7539 // %gs:0x58 (64-bit).
7540 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7541 ? Type::getInt8PtrTy(*DAG.getContext(),
7543 : Type::getInt32PtrTy(*DAG.getContext(),
7546 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7547 Subtarget->is64Bit()
7548 ? DAG.getIntPtrConstant(0x58)
7549 : DAG.getExternalSymbol("_tls_array",
7551 MachinePointerInfo(Ptr),
7552 false, false, false, 0);
7554 // Load the _tls_index variable
7555 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7556 if (Subtarget->is64Bit())
7557 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7558 IDX, MachinePointerInfo(), MVT::i32,
7561 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7562 false, false, false, 0);
7564 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7566 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7568 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7569 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7570 false, false, false, 0);
7572 // Get the offset of start of .tls section
7573 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7574 GA->getValueType(0),
7575 GA->getOffset(), X86II::MO_SECREL);
7576 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7578 // The address of the thread local variable is the add of the thread
7579 // pointer with the offset of the variable.
7580 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7583 llvm_unreachable("TLS not implemented for this target.");
7587 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7588 /// and take a 2 x i32 value to shift plus a shift amount.
7589 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7590 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7591 EVT VT = Op.getValueType();
7592 unsigned VTBits = VT.getSizeInBits();
7593 DebugLoc dl = Op.getDebugLoc();
7594 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7595 SDValue ShOpLo = Op.getOperand(0);
7596 SDValue ShOpHi = Op.getOperand(1);
7597 SDValue ShAmt = Op.getOperand(2);
7598 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7599 DAG.getConstant(VTBits - 1, MVT::i8))
7600 : DAG.getConstant(0, VT);
7603 if (Op.getOpcode() == ISD::SHL_PARTS) {
7604 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7605 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7607 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7608 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7611 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7612 DAG.getConstant(VTBits, MVT::i8));
7613 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7614 AndNode, DAG.getConstant(0, MVT::i8));
7617 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7618 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7619 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7621 if (Op.getOpcode() == ISD::SHL_PARTS) {
7622 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7623 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7625 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7626 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7629 SDValue Ops[2] = { Lo, Hi };
7630 return DAG.getMergeValues(Ops, 2, dl);
7633 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7634 SelectionDAG &DAG) const {
7635 EVT SrcVT = Op.getOperand(0).getValueType();
7637 if (SrcVT.isVector())
7640 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7641 "Unknown SINT_TO_FP to lower!");
7643 // These are really Legal; return the operand so the caller accepts it as
7645 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7647 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7648 Subtarget->is64Bit()) {
7652 DebugLoc dl = Op.getDebugLoc();
7653 unsigned Size = SrcVT.getSizeInBits()/8;
7654 MachineFunction &MF = DAG.getMachineFunction();
7655 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7656 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7657 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7659 MachinePointerInfo::getFixedStack(SSFI),
7661 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7664 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7666 SelectionDAG &DAG) const {
7668 DebugLoc DL = Op.getDebugLoc();
7670 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7672 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7674 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7676 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7678 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7679 MachineMemOperand *MMO;
7681 int SSFI = FI->getIndex();
7683 DAG.getMachineFunction()
7684 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7685 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7687 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7688 StackSlot = StackSlot.getOperand(1);
7690 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7691 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7693 Tys, Ops, array_lengthof(Ops),
7697 Chain = Result.getValue(1);
7698 SDValue InFlag = Result.getValue(2);
7700 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7701 // shouldn't be necessary except that RFP cannot be live across
7702 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7703 MachineFunction &MF = DAG.getMachineFunction();
7704 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7705 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7706 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7707 Tys = DAG.getVTList(MVT::Other);
7709 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7711 MachineMemOperand *MMO =
7712 DAG.getMachineFunction()
7713 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7714 MachineMemOperand::MOStore, SSFISize, SSFISize);
7716 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7717 Ops, array_lengthof(Ops),
7718 Op.getValueType(), MMO);
7719 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7720 MachinePointerInfo::getFixedStack(SSFI),
7721 false, false, false, 0);
7727 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7728 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7729 SelectionDAG &DAG) const {
7730 // This algorithm is not obvious. Here it is what we're trying to output:
7733 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7734 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7738 pshufd $0x4e, %xmm0, %xmm1
7743 DebugLoc dl = Op.getDebugLoc();
7744 LLVMContext *Context = DAG.getContext();
7746 // Build some magic constants.
7747 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7748 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7749 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7751 SmallVector<Constant*,2> CV1;
7753 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7755 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7756 Constant *C1 = ConstantVector::get(CV1);
7757 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7759 // Load the 64-bit value into an XMM register.
7760 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7762 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7763 MachinePointerInfo::getConstantPool(),
7764 false, false, false, 16);
7765 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7766 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7769 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7770 MachinePointerInfo::getConstantPool(),
7771 false, false, false, 16);
7772 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7773 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7776 if (Subtarget->hasSSE3()) {
7777 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7778 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7780 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7781 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7783 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7784 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7788 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7789 DAG.getIntPtrConstant(0));
7792 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7793 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7794 SelectionDAG &DAG) const {
7795 DebugLoc dl = Op.getDebugLoc();
7796 // FP constant to bias correct the final result.
7797 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7800 // Load the 32-bit value into an XMM register.
7801 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7804 // Zero out the upper parts of the register.
7805 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7807 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7808 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7809 DAG.getIntPtrConstant(0));
7811 // Or the load with the bias.
7812 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7813 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7814 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7816 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7817 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7818 MVT::v2f64, Bias)));
7819 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7820 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7821 DAG.getIntPtrConstant(0));
7823 // Subtract the bias.
7824 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7826 // Handle final rounding.
7827 EVT DestVT = Op.getValueType();
7829 if (DestVT.bitsLT(MVT::f64))
7830 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7831 DAG.getIntPtrConstant(0));
7832 if (DestVT.bitsGT(MVT::f64))
7833 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7835 // Handle final rounding.
7839 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7840 SelectionDAG &DAG) const {
7841 SDValue N0 = Op.getOperand(0);
7842 DebugLoc dl = Op.getDebugLoc();
7844 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7845 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7846 // the optimization here.
7847 if (DAG.SignBitIsZero(N0))
7848 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7850 EVT SrcVT = N0.getValueType();
7851 EVT DstVT = Op.getValueType();
7852 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7853 return LowerUINT_TO_FP_i64(Op, DAG);
7854 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7855 return LowerUINT_TO_FP_i32(Op, DAG);
7856 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7859 // Make a 64-bit buffer, and use it to build an FILD.
7860 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7861 if (SrcVT == MVT::i32) {
7862 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7863 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7864 getPointerTy(), StackSlot, WordOff);
7865 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7866 StackSlot, MachinePointerInfo(),
7868 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7869 OffsetSlot, MachinePointerInfo(),
7871 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7875 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7876 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7877 StackSlot, MachinePointerInfo(),
7879 // For i64 source, we need to add the appropriate power of 2 if the input
7880 // was negative. This is the same as the optimization in
7881 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7882 // we must be careful to do the computation in x87 extended precision, not
7883 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7884 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7885 MachineMemOperand *MMO =
7886 DAG.getMachineFunction()
7887 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7888 MachineMemOperand::MOLoad, 8, 8);
7890 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7891 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7892 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7895 APInt FF(32, 0x5F800000ULL);
7897 // Check whether the sign bit is set.
7898 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7899 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7902 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7903 SDValue FudgePtr = DAG.getConstantPool(
7904 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7907 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7908 SDValue Zero = DAG.getIntPtrConstant(0);
7909 SDValue Four = DAG.getIntPtrConstant(4);
7910 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7912 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7914 // Load the value out, extending it from f32 to f80.
7915 // FIXME: Avoid the extend by constructing the right constant pool?
7916 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7917 FudgePtr, MachinePointerInfo::getConstantPool(),
7918 MVT::f32, false, false, 4);
7919 // Extend everything to 80 bits to force it to be done on x87.
7920 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7921 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7924 std::pair<SDValue,SDValue> X86TargetLowering::
7925 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7926 DebugLoc DL = Op.getDebugLoc();
7928 EVT DstTy = Op.getValueType();
7930 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7931 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7935 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7936 DstTy.getSimpleVT() >= MVT::i16 &&
7937 "Unknown FP_TO_INT to lower!");
7939 // These are really Legal.
7940 if (DstTy == MVT::i32 &&
7941 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7942 return std::make_pair(SDValue(), SDValue());
7943 if (Subtarget->is64Bit() &&
7944 DstTy == MVT::i64 &&
7945 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7946 return std::make_pair(SDValue(), SDValue());
7948 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7949 // stack slot, or into the FTOL runtime function.
7950 MachineFunction &MF = DAG.getMachineFunction();
7951 unsigned MemSize = DstTy.getSizeInBits()/8;
7952 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7953 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7956 if (!IsSigned && isIntegerTypeFTOL(DstTy))
7957 Opc = X86ISD::WIN_FTOL;
7959 switch (DstTy.getSimpleVT().SimpleTy) {
7960 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7961 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7962 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7963 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7966 SDValue Chain = DAG.getEntryNode();
7967 SDValue Value = Op.getOperand(0);
7968 EVT TheVT = Op.getOperand(0).getValueType();
7969 // FIXME This causes a redundant load/store if the SSE-class value is already
7970 // in memory, such as if it is on the callstack.
7971 if (isScalarFPTypeInSSEReg(TheVT)) {
7972 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7973 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7974 MachinePointerInfo::getFixedStack(SSFI),
7976 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7978 Chain, StackSlot, DAG.getValueType(TheVT)
7981 MachineMemOperand *MMO =
7982 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7983 MachineMemOperand::MOLoad, MemSize, MemSize);
7984 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7986 Chain = Value.getValue(1);
7987 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7988 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7991 MachineMemOperand *MMO =
7992 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7993 MachineMemOperand::MOStore, MemSize, MemSize);
7995 if (Opc != X86ISD::WIN_FTOL) {
7996 // Build the FP_TO_INT*_IN_MEM
7997 SDValue Ops[] = { Chain, Value, StackSlot };
7998 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7999 Ops, 3, DstTy, MMO);
8000 return std::make_pair(FIST, StackSlot);
8002 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8003 DAG.getVTList(MVT::Other, MVT::Glue),
8005 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8006 MVT::i32, ftol.getValue(1));
8007 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8008 MVT::i32, eax.getValue(2));
8009 SDValue Ops[] = { eax, edx };
8010 SDValue pair = IsReplace
8011 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8012 : DAG.getMergeValues(Ops, 2, DL);
8013 return std::make_pair(pair, SDValue());
8017 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8018 SelectionDAG &DAG) const {
8019 if (Op.getValueType().isVector())
8022 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8023 /*IsSigned=*/ true, /*IsReplace=*/ false);
8024 SDValue FIST = Vals.first, StackSlot = Vals.second;
8025 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8026 if (FIST.getNode() == 0) return Op;
8028 if (StackSlot.getNode())
8030 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8031 FIST, StackSlot, MachinePointerInfo(),
8032 false, false, false, 0);
8034 // The node is the result.
8038 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8039 SelectionDAG &DAG) const {
8040 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8041 /*IsSigned=*/ false, /*IsReplace=*/ false);
8042 SDValue FIST = Vals.first, StackSlot = Vals.second;
8043 assert(FIST.getNode() && "Unexpected failure");
8045 if (StackSlot.getNode())
8047 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8048 FIST, StackSlot, MachinePointerInfo(),
8049 false, false, false, 0);
8051 // The node is the result.
8055 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8056 SelectionDAG &DAG) const {
8057 LLVMContext *Context = DAG.getContext();
8058 DebugLoc dl = Op.getDebugLoc();
8059 EVT VT = Op.getValueType();
8062 EltVT = VT.getVectorElementType();
8064 if (EltVT == MVT::f64) {
8065 C = ConstantVector::getSplat(2,
8066 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8068 C = ConstantVector::getSplat(4,
8069 ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8071 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8072 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8073 MachinePointerInfo::getConstantPool(),
8074 false, false, false, 16);
8075 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8078 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8079 LLVMContext *Context = DAG.getContext();
8080 DebugLoc dl = Op.getDebugLoc();
8081 EVT VT = Op.getValueType();
8083 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8084 if (VT.isVector()) {
8085 EltVT = VT.getVectorElementType();
8086 NumElts = VT.getVectorNumElements();
8089 if (EltVT == MVT::f64)
8090 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8092 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8093 C = ConstantVector::getSplat(NumElts, C);
8094 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8095 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8096 MachinePointerInfo::getConstantPool(),
8097 false, false, false, 16);
8098 if (VT.isVector()) {
8099 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8100 return DAG.getNode(ISD::BITCAST, dl, VT,
8101 DAG.getNode(ISD::XOR, dl, XORVT,
8102 DAG.getNode(ISD::BITCAST, dl, XORVT,
8104 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8107 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8110 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8111 LLVMContext *Context = DAG.getContext();
8112 SDValue Op0 = Op.getOperand(0);
8113 SDValue Op1 = Op.getOperand(1);
8114 DebugLoc dl = Op.getDebugLoc();
8115 EVT VT = Op.getValueType();
8116 EVT SrcVT = Op1.getValueType();
8118 // If second operand is smaller, extend it first.
8119 if (SrcVT.bitsLT(VT)) {
8120 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8123 // And if it is bigger, shrink it first.
8124 if (SrcVT.bitsGT(VT)) {
8125 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8129 // At this point the operands and the result should have the same
8130 // type, and that won't be f80 since that is not custom lowered.
8132 // First get the sign bit of second operand.
8133 SmallVector<Constant*,4> CV;
8134 if (SrcVT == MVT::f64) {
8135 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8136 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8138 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8139 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8140 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8141 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8143 Constant *C = ConstantVector::get(CV);
8144 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8145 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8146 MachinePointerInfo::getConstantPool(),
8147 false, false, false, 16);
8148 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8150 // Shift sign bit right or left if the two operands have different types.
8151 if (SrcVT.bitsGT(VT)) {
8152 // Op0 is MVT::f32, Op1 is MVT::f64.
8153 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8154 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8155 DAG.getConstant(32, MVT::i32));
8156 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8157 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8158 DAG.getIntPtrConstant(0));
8161 // Clear first operand sign bit.
8163 if (VT == MVT::f64) {
8164 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8165 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8167 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8168 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8169 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8170 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8172 C = ConstantVector::get(CV);
8173 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8174 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8175 MachinePointerInfo::getConstantPool(),
8176 false, false, false, 16);
8177 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8179 // Or the value with the sign bit.
8180 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8183 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8184 SDValue N0 = Op.getOperand(0);
8185 DebugLoc dl = Op.getDebugLoc();
8186 EVT VT = Op.getValueType();
8188 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8189 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8190 DAG.getConstant(1, VT));
8191 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8194 /// Emit nodes that will be selected as "test Op0,Op0", or something
8196 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8197 SelectionDAG &DAG) const {
8198 DebugLoc dl = Op.getDebugLoc();
8200 // CF and OF aren't always set the way we want. Determine which
8201 // of these we need.
8202 bool NeedCF = false;
8203 bool NeedOF = false;
8206 case X86::COND_A: case X86::COND_AE:
8207 case X86::COND_B: case X86::COND_BE:
8210 case X86::COND_G: case X86::COND_GE:
8211 case X86::COND_L: case X86::COND_LE:
8212 case X86::COND_O: case X86::COND_NO:
8217 // See if we can use the EFLAGS value from the operand instead of
8218 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8219 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8220 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8221 // Emit a CMP with 0, which is the TEST pattern.
8222 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8223 DAG.getConstant(0, Op.getValueType()));
8225 unsigned Opcode = 0;
8226 unsigned NumOperands = 0;
8227 switch (Op.getNode()->getOpcode()) {
8229 // Due to an isel shortcoming, be conservative if this add is likely to be
8230 // selected as part of a load-modify-store instruction. When the root node
8231 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8232 // uses of other nodes in the match, such as the ADD in this case. This
8233 // leads to the ADD being left around and reselected, with the result being
8234 // two adds in the output. Alas, even if none our users are stores, that
8235 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8236 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8237 // climbing the DAG back to the root, and it doesn't seem to be worth the
8239 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8240 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8241 if (UI->getOpcode() != ISD::CopyToReg &&
8242 UI->getOpcode() != ISD::SETCC &&
8243 UI->getOpcode() != ISD::STORE)
8246 if (ConstantSDNode *C =
8247 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8248 // An add of one will be selected as an INC.
8249 if (C->getAPIntValue() == 1) {
8250 Opcode = X86ISD::INC;
8255 // An add of negative one (subtract of one) will be selected as a DEC.
8256 if (C->getAPIntValue().isAllOnesValue()) {
8257 Opcode = X86ISD::DEC;
8263 // Otherwise use a regular EFLAGS-setting add.
8264 Opcode = X86ISD::ADD;
8268 // If the primary and result isn't used, don't bother using X86ISD::AND,
8269 // because a TEST instruction will be better.
8270 bool NonFlagUse = false;
8271 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8272 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8274 unsigned UOpNo = UI.getOperandNo();
8275 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8276 // Look pass truncate.
8277 UOpNo = User->use_begin().getOperandNo();
8278 User = *User->use_begin();
8281 if (User->getOpcode() != ISD::BRCOND &&
8282 User->getOpcode() != ISD::SETCC &&
8283 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8296 // Due to the ISEL shortcoming noted above, be conservative if this op is
8297 // likely to be selected as part of a load-modify-store instruction.
8298 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8299 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8300 if (UI->getOpcode() == ISD::STORE)
8303 // Otherwise use a regular EFLAGS-setting instruction.
8304 switch (Op.getNode()->getOpcode()) {
8305 default: llvm_unreachable("unexpected operator!");
8307 // If the only use of SUB is EFLAGS, use CMP instead.
8309 Opcode = X86ISD::CMP;
8311 Opcode = X86ISD::SUB;
8313 case ISD::OR: Opcode = X86ISD::OR; break;
8314 case ISD::XOR: Opcode = X86ISD::XOR; break;
8315 case ISD::AND: Opcode = X86ISD::AND; break;
8327 return SDValue(Op.getNode(), 1);
8334 // Emit a CMP with 0, which is the TEST pattern.
8335 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8336 DAG.getConstant(0, Op.getValueType()));
8338 if (Opcode == X86ISD::CMP) {
8339 SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8341 // We can't replace usage of SUB with CMP.
8342 // The SUB node will be removed later because there is no use of it.
8343 return SDValue(New.getNode(), 0);
8346 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8347 SmallVector<SDValue, 4> Ops;
8348 for (unsigned i = 0; i != NumOperands; ++i)
8349 Ops.push_back(Op.getOperand(i));
8351 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8352 DAG.ReplaceAllUsesWith(Op, New);
8353 return SDValue(New.getNode(), 1);
8356 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8358 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8359 SelectionDAG &DAG) const {
8360 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8361 if (C->getAPIntValue() == 0)
8362 return EmitTest(Op0, X86CC, DAG);
8364 DebugLoc dl = Op0.getDebugLoc();
8365 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8368 /// Convert a comparison if required by the subtarget.
8369 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8370 SelectionDAG &DAG) const {
8371 // If the subtarget does not support the FUCOMI instruction, floating-point
8372 // comparisons have to be converted.
8373 if (Subtarget->hasCMov() ||
8374 Cmp.getOpcode() != X86ISD::CMP ||
8375 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8376 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8379 // The instruction selector will select an FUCOM instruction instead of
8380 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8381 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8382 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8383 DebugLoc dl = Cmp.getDebugLoc();
8384 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8385 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8386 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8387 DAG.getConstant(8, MVT::i8));
8388 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8389 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8392 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8393 /// if it's possible.
8394 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8395 DebugLoc dl, SelectionDAG &DAG) const {
8396 SDValue Op0 = And.getOperand(0);
8397 SDValue Op1 = And.getOperand(1);
8398 if (Op0.getOpcode() == ISD::TRUNCATE)
8399 Op0 = Op0.getOperand(0);
8400 if (Op1.getOpcode() == ISD::TRUNCATE)
8401 Op1 = Op1.getOperand(0);
8404 if (Op1.getOpcode() == ISD::SHL)
8405 std::swap(Op0, Op1);
8406 if (Op0.getOpcode() == ISD::SHL) {
8407 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8408 if (And00C->getZExtValue() == 1) {
8409 // If we looked past a truncate, check that it's only truncating away
8411 unsigned BitWidth = Op0.getValueSizeInBits();
8412 unsigned AndBitWidth = And.getValueSizeInBits();
8413 if (BitWidth > AndBitWidth) {
8415 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8416 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8420 RHS = Op0.getOperand(1);
8422 } else if (Op1.getOpcode() == ISD::Constant) {
8423 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8424 uint64_t AndRHSVal = AndRHS->getZExtValue();
8425 SDValue AndLHS = Op0;
8427 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8428 LHS = AndLHS.getOperand(0);
8429 RHS = AndLHS.getOperand(1);
8432 // Use BT if the immediate can't be encoded in a TEST instruction.
8433 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8435 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8439 if (LHS.getNode()) {
8440 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8441 // instruction. Since the shift amount is in-range-or-undefined, we know
8442 // that doing a bittest on the i32 value is ok. We extend to i32 because
8443 // the encoding for the i16 version is larger than the i32 version.
8444 // Also promote i16 to i32 for performance / code size reason.
8445 if (LHS.getValueType() == MVT::i8 ||
8446 LHS.getValueType() == MVT::i16)
8447 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8449 // If the operand types disagree, extend the shift amount to match. Since
8450 // BT ignores high bits (like shifts) we can use anyextend.
8451 if (LHS.getValueType() != RHS.getValueType())
8452 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8454 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8455 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8456 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8457 DAG.getConstant(Cond, MVT::i8), BT);
8463 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8465 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8467 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8468 SDValue Op0 = Op.getOperand(0);
8469 SDValue Op1 = Op.getOperand(1);
8470 DebugLoc dl = Op.getDebugLoc();
8471 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8473 // Optimize to BT if possible.
8474 // Lower (X & (1 << N)) == 0 to BT(X, N).
8475 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8476 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8477 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8478 Op1.getOpcode() == ISD::Constant &&
8479 cast<ConstantSDNode>(Op1)->isNullValue() &&
8480 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8481 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8482 if (NewSetCC.getNode())
8486 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8488 if (Op1.getOpcode() == ISD::Constant &&
8489 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8490 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8491 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8493 // If the input is a setcc, then reuse the input setcc or use a new one with
8494 // the inverted condition.
8495 if (Op0.getOpcode() == X86ISD::SETCC) {
8496 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8497 bool Invert = (CC == ISD::SETNE) ^
8498 cast<ConstantSDNode>(Op1)->isNullValue();
8499 if (!Invert) return Op0;
8501 CCode = X86::GetOppositeBranchCondition(CCode);
8502 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8503 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8507 bool isFP = Op1.getValueType().isFloatingPoint();
8508 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8509 if (X86CC == X86::COND_INVALID)
8512 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8513 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8514 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8515 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8518 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8519 // ones, and then concatenate the result back.
8520 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8521 EVT VT = Op.getValueType();
8523 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8524 "Unsupported value type for operation");
8526 unsigned NumElems = VT.getVectorNumElements();
8527 DebugLoc dl = Op.getDebugLoc();
8528 SDValue CC = Op.getOperand(2);
8530 // Extract the LHS vectors
8531 SDValue LHS = Op.getOperand(0);
8532 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8533 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8535 // Extract the RHS vectors
8536 SDValue RHS = Op.getOperand(1);
8537 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8538 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8540 // Issue the operation on the smaller types and concatenate the result back
8541 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8542 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8543 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8544 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8545 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8549 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8551 SDValue Op0 = Op.getOperand(0);
8552 SDValue Op1 = Op.getOperand(1);
8553 SDValue CC = Op.getOperand(2);
8554 EVT VT = Op.getValueType();
8555 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8556 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8557 DebugLoc dl = Op.getDebugLoc();
8561 EVT EltVT = Op0.getValueType().getVectorElementType();
8562 assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8566 // SSE Condition code mapping:
8575 switch (SetCCOpcode) {
8578 case ISD::SETEQ: SSECC = 0; break;
8580 case ISD::SETGT: Swap = true; // Fallthrough
8582 case ISD::SETOLT: SSECC = 1; break;
8584 case ISD::SETGE: Swap = true; // Fallthrough
8586 case ISD::SETOLE: SSECC = 2; break;
8587 case ISD::SETUO: SSECC = 3; break;
8589 case ISD::SETNE: SSECC = 4; break;
8590 case ISD::SETULE: Swap = true;
8591 case ISD::SETUGE: SSECC = 5; break;
8592 case ISD::SETULT: Swap = true;
8593 case ISD::SETUGT: SSECC = 6; break;
8594 case ISD::SETO: SSECC = 7; break;
8597 std::swap(Op0, Op1);
8599 // In the two special cases we can't handle, emit two comparisons.
8601 if (SetCCOpcode == ISD::SETUEQ) {
8603 UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8604 DAG.getConstant(3, MVT::i8));
8605 EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8606 DAG.getConstant(0, MVT::i8));
8607 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8609 if (SetCCOpcode == ISD::SETONE) {
8611 ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8612 DAG.getConstant(7, MVT::i8));
8613 NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8614 DAG.getConstant(4, MVT::i8));
8615 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8617 llvm_unreachable("Illegal FP comparison");
8619 // Handle all other FP comparisons here.
8620 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8621 DAG.getConstant(SSECC, MVT::i8));
8624 // Break 256-bit integer vector compare into smaller ones.
8625 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8626 return Lower256IntVSETCC(Op, DAG);
8628 // We are handling one of the integer comparisons here. Since SSE only has
8629 // GT and EQ comparisons for integer, swapping operands and multiple
8630 // operations may be required for some comparisons.
8632 bool Swap = false, Invert = false, FlipSigns = false;
8634 switch (SetCCOpcode) {
8636 case ISD::SETNE: Invert = true;
8637 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8638 case ISD::SETLT: Swap = true;
8639 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8640 case ISD::SETGE: Swap = true;
8641 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8642 case ISD::SETULT: Swap = true;
8643 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8644 case ISD::SETUGE: Swap = true;
8645 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8648 std::swap(Op0, Op1);
8650 // Check that the operation in question is available (most are plain SSE2,
8651 // but PCMPGTQ and PCMPEQQ have different requirements).
8652 if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8654 if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8657 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8658 // bits of the inputs before performing those operations.
8660 EVT EltVT = VT.getVectorElementType();
8661 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8663 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8664 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8666 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8667 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8670 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8672 // If the logical-not of the result is required, perform that now.
8674 Result = DAG.getNOT(dl, Result, VT);
8679 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8680 static bool isX86LogicalCmp(SDValue Op) {
8681 unsigned Opc = Op.getNode()->getOpcode();
8682 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8683 Opc == X86ISD::SAHF)
8685 if (Op.getResNo() == 1 &&
8686 (Opc == X86ISD::ADD ||
8687 Opc == X86ISD::SUB ||
8688 Opc == X86ISD::ADC ||
8689 Opc == X86ISD::SBB ||
8690 Opc == X86ISD::SMUL ||
8691 Opc == X86ISD::UMUL ||
8692 Opc == X86ISD::INC ||
8693 Opc == X86ISD::DEC ||
8694 Opc == X86ISD::OR ||
8695 Opc == X86ISD::XOR ||
8696 Opc == X86ISD::AND))
8699 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8705 static bool isZero(SDValue V) {
8706 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8707 return C && C->isNullValue();
8710 static bool isAllOnes(SDValue V) {
8711 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8712 return C && C->isAllOnesValue();
8715 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8716 bool addTest = true;
8717 SDValue Cond = Op.getOperand(0);
8718 SDValue Op1 = Op.getOperand(1);
8719 SDValue Op2 = Op.getOperand(2);
8720 DebugLoc DL = Op.getDebugLoc();
8723 if (Cond.getOpcode() == ISD::SETCC) {
8724 SDValue NewCond = LowerSETCC(Cond, DAG);
8725 if (NewCond.getNode())
8729 // Handle the following cases related to max and min:
8730 // (a > b) ? (a-b) : 0
8731 // (a >= b) ? (a-b) : 0
8732 // (b < a) ? (a-b) : 0
8733 // (b <= a) ? (a-b) : 0
8734 // Comparison is removed to use EFLAGS from SUB.
8735 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8736 if (Cond.getOpcode() == X86ISD::SETCC &&
8737 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8738 (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8739 C->getAPIntValue() == 0) {
8740 SDValue Cmp = Cond.getOperand(1);
8741 unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8742 if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8743 DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8744 (CC == X86::COND_G || CC == X86::COND_GE ||
8745 CC == X86::COND_A || CC == X86::COND_AE)) ||
8746 (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8747 DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8748 (CC == X86::COND_L || CC == X86::COND_LE ||
8749 CC == X86::COND_B || CC == X86::COND_BE))) {
8751 if (Op1.getOpcode() == ISD::SUB) {
8752 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8753 SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8754 Op1.getOperand(0), Op1.getOperand(1));
8755 DAG.ReplaceAllUsesWith(Op1, New);
8759 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8760 unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8761 CC == X86::COND_L ||
8762 CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8763 SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8764 SDValue(Op1.getNode(), 1) };
8765 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8769 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8770 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8771 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8772 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8773 if (Cond.getOpcode() == X86ISD::SETCC &&
8774 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8775 isZero(Cond.getOperand(1).getOperand(1))) {
8776 SDValue Cmp = Cond.getOperand(1);
8778 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8780 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8781 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8782 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8784 SDValue CmpOp0 = Cmp.getOperand(0);
8785 // Apply further optimizations for special cases
8786 // (select (x != 0), -1, 0) -> neg & sbb
8787 // (select (x == 0), 0, -1) -> neg & sbb
8788 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8789 if (YC->isNullValue() &&
8790 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8791 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8792 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8793 DAG.getConstant(0, CmpOp0.getValueType()),
8795 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8796 DAG.getConstant(X86::COND_B, MVT::i8),
8797 SDValue(Neg.getNode(), 1));
8801 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8802 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8803 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8805 SDValue Res = // Res = 0 or -1.
8806 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8807 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8809 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8810 Res = DAG.getNOT(DL, Res, Res.getValueType());
8812 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8813 if (N2C == 0 || !N2C->isNullValue())
8814 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8819 // Look past (and (setcc_carry (cmp ...)), 1).
8820 if (Cond.getOpcode() == ISD::AND &&
8821 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8822 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8823 if (C && C->getAPIntValue() == 1)
8824 Cond = Cond.getOperand(0);
8827 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8828 // setting operand in place of the X86ISD::SETCC.
8829 unsigned CondOpcode = Cond.getOpcode();
8830 if (CondOpcode == X86ISD::SETCC ||
8831 CondOpcode == X86ISD::SETCC_CARRY) {
8832 CC = Cond.getOperand(0);
8834 SDValue Cmp = Cond.getOperand(1);
8835 unsigned Opc = Cmp.getOpcode();
8836 EVT VT = Op.getValueType();
8838 bool IllegalFPCMov = false;
8839 if (VT.isFloatingPoint() && !VT.isVector() &&
8840 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8841 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8843 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8844 Opc == X86ISD::BT) { // FIXME
8848 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8849 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8850 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8851 Cond.getOperand(0).getValueType() != MVT::i8)) {
8852 SDValue LHS = Cond.getOperand(0);
8853 SDValue RHS = Cond.getOperand(1);
8857 switch (CondOpcode) {
8858 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8859 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8860 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8861 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8862 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8863 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8864 default: llvm_unreachable("unexpected overflowing operator");
8866 if (CondOpcode == ISD::UMULO)
8867 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8870 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8872 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8874 if (CondOpcode == ISD::UMULO)
8875 Cond = X86Op.getValue(2);
8877 Cond = X86Op.getValue(1);
8879 CC = DAG.getConstant(X86Cond, MVT::i8);
8884 // Look pass the truncate.
8885 if (Cond.getOpcode() == ISD::TRUNCATE)
8886 Cond = Cond.getOperand(0);
8888 // We know the result of AND is compared against zero. Try to match
8890 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8891 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8892 if (NewSetCC.getNode()) {
8893 CC = NewSetCC.getOperand(0);
8894 Cond = NewSetCC.getOperand(1);
8901 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8902 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8905 // a < b ? -1 : 0 -> RES = ~setcc_carry
8906 // a < b ? 0 : -1 -> RES = setcc_carry
8907 // a >= b ? -1 : 0 -> RES = setcc_carry
8908 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8909 if (Cond.getOpcode() == X86ISD::CMP) {
8910 Cond = ConvertCmpIfNecessary(Cond, DAG);
8911 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8913 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8914 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8915 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8916 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8917 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8918 return DAG.getNOT(DL, Res, Res.getValueType());
8923 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8924 // condition is true.
8925 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8926 SDValue Ops[] = { Op2, Op1, CC, Cond };
8927 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8930 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8931 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8932 // from the AND / OR.
8933 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8934 Opc = Op.getOpcode();
8935 if (Opc != ISD::OR && Opc != ISD::AND)
8937 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8938 Op.getOperand(0).hasOneUse() &&
8939 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8940 Op.getOperand(1).hasOneUse());
8943 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8944 // 1 and that the SETCC node has a single use.
8945 static bool isXor1OfSetCC(SDValue Op) {
8946 if (Op.getOpcode() != ISD::XOR)
8948 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8949 if (N1C && N1C->getAPIntValue() == 1) {
8950 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8951 Op.getOperand(0).hasOneUse();
8956 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8957 bool addTest = true;
8958 SDValue Chain = Op.getOperand(0);
8959 SDValue Cond = Op.getOperand(1);
8960 SDValue Dest = Op.getOperand(2);
8961 DebugLoc dl = Op.getDebugLoc();
8963 bool Inverted = false;
8965 if (Cond.getOpcode() == ISD::SETCC) {
8966 // Check for setcc([su]{add,sub,mul}o == 0).
8967 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8968 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8969 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8970 Cond.getOperand(0).getResNo() == 1 &&
8971 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8972 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8973 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8974 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8975 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8976 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8978 Cond = Cond.getOperand(0);
8980 SDValue NewCond = LowerSETCC(Cond, DAG);
8981 if (NewCond.getNode())
8986 // FIXME: LowerXALUO doesn't handle these!!
8987 else if (Cond.getOpcode() == X86ISD::ADD ||
8988 Cond.getOpcode() == X86ISD::SUB ||
8989 Cond.getOpcode() == X86ISD::SMUL ||
8990 Cond.getOpcode() == X86ISD::UMUL)
8991 Cond = LowerXALUO(Cond, DAG);
8994 // Look pass (and (setcc_carry (cmp ...)), 1).
8995 if (Cond.getOpcode() == ISD::AND &&
8996 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8997 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8998 if (C && C->getAPIntValue() == 1)
8999 Cond = Cond.getOperand(0);
9002 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9003 // setting operand in place of the X86ISD::SETCC.
9004 unsigned CondOpcode = Cond.getOpcode();
9005 if (CondOpcode == X86ISD::SETCC ||
9006 CondOpcode == X86ISD::SETCC_CARRY) {
9007 CC = Cond.getOperand(0);
9009 SDValue Cmp = Cond.getOperand(1);
9010 unsigned Opc = Cmp.getOpcode();
9011 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9012 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9016 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9020 // These can only come from an arithmetic instruction with overflow,
9021 // e.g. SADDO, UADDO.
9022 Cond = Cond.getNode()->getOperand(1);
9028 CondOpcode = Cond.getOpcode();
9029 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9030 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9031 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9032 Cond.getOperand(0).getValueType() != MVT::i8)) {
9033 SDValue LHS = Cond.getOperand(0);
9034 SDValue RHS = Cond.getOperand(1);
9038 switch (CondOpcode) {
9039 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9040 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9041 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9042 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9043 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9044 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9045 default: llvm_unreachable("unexpected overflowing operator");
9048 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9049 if (CondOpcode == ISD::UMULO)
9050 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9053 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9055 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9057 if (CondOpcode == ISD::UMULO)
9058 Cond = X86Op.getValue(2);
9060 Cond = X86Op.getValue(1);
9062 CC = DAG.getConstant(X86Cond, MVT::i8);
9066 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9067 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9068 if (CondOpc == ISD::OR) {
9069 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9070 // two branches instead of an explicit OR instruction with a
9072 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9073 isX86LogicalCmp(Cmp)) {
9074 CC = Cond.getOperand(0).getOperand(0);
9075 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9076 Chain, Dest, CC, Cmp);
9077 CC = Cond.getOperand(1).getOperand(0);
9081 } else { // ISD::AND
9082 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9083 // two branches instead of an explicit AND instruction with a
9084 // separate test. However, we only do this if this block doesn't
9085 // have a fall-through edge, because this requires an explicit
9086 // jmp when the condition is false.
9087 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9088 isX86LogicalCmp(Cmp) &&
9089 Op.getNode()->hasOneUse()) {
9090 X86::CondCode CCode =
9091 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9092 CCode = X86::GetOppositeBranchCondition(CCode);
9093 CC = DAG.getConstant(CCode, MVT::i8);
9094 SDNode *User = *Op.getNode()->use_begin();
9095 // Look for an unconditional branch following this conditional branch.
9096 // We need this because we need to reverse the successors in order
9097 // to implement FCMP_OEQ.
9098 if (User->getOpcode() == ISD::BR) {
9099 SDValue FalseBB = User->getOperand(1);
9101 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9102 assert(NewBR == User);
9106 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9107 Chain, Dest, CC, Cmp);
9108 X86::CondCode CCode =
9109 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9110 CCode = X86::GetOppositeBranchCondition(CCode);
9111 CC = DAG.getConstant(CCode, MVT::i8);
9117 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9118 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9119 // It should be transformed during dag combiner except when the condition
9120 // is set by a arithmetics with overflow node.
9121 X86::CondCode CCode =
9122 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9123 CCode = X86::GetOppositeBranchCondition(CCode);
9124 CC = DAG.getConstant(CCode, MVT::i8);
9125 Cond = Cond.getOperand(0).getOperand(1);
9127 } else if (Cond.getOpcode() == ISD::SETCC &&
9128 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9129 // For FCMP_OEQ, we can emit
9130 // two branches instead of an explicit AND instruction with a
9131 // separate test. However, we only do this if this block doesn't
9132 // have a fall-through edge, because this requires an explicit
9133 // jmp when the condition is false.
9134 if (Op.getNode()->hasOneUse()) {
9135 SDNode *User = *Op.getNode()->use_begin();
9136 // Look for an unconditional branch following this conditional branch.
9137 // We need this because we need to reverse the successors in order
9138 // to implement FCMP_OEQ.
9139 if (User->getOpcode() == ISD::BR) {
9140 SDValue FalseBB = User->getOperand(1);
9142 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9143 assert(NewBR == User);
9147 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9148 Cond.getOperand(0), Cond.getOperand(1));
9149 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9150 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9151 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9152 Chain, Dest, CC, Cmp);
9153 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9158 } else if (Cond.getOpcode() == ISD::SETCC &&
9159 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9160 // For FCMP_UNE, we can emit
9161 // two branches instead of an explicit AND instruction with a
9162 // separate test. However, we only do this if this block doesn't
9163 // have a fall-through edge, because this requires an explicit
9164 // jmp when the condition is false.
9165 if (Op.getNode()->hasOneUse()) {
9166 SDNode *User = *Op.getNode()->use_begin();
9167 // Look for an unconditional branch following this conditional branch.
9168 // We need this because we need to reverse the successors in order
9169 // to implement FCMP_UNE.
9170 if (User->getOpcode() == ISD::BR) {
9171 SDValue FalseBB = User->getOperand(1);
9173 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9174 assert(NewBR == User);
9177 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9178 Cond.getOperand(0), Cond.getOperand(1));
9179 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9180 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9181 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9182 Chain, Dest, CC, Cmp);
9183 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9193 // Look pass the truncate.
9194 if (Cond.getOpcode() == ISD::TRUNCATE)
9195 Cond = Cond.getOperand(0);
9197 // We know the result of AND is compared against zero. Try to match
9199 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9200 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9201 if (NewSetCC.getNode()) {
9202 CC = NewSetCC.getOperand(0);
9203 Cond = NewSetCC.getOperand(1);
9210 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9211 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9213 Cond = ConvertCmpIfNecessary(Cond, DAG);
9214 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9215 Chain, Dest, CC, Cond);
9219 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9220 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9221 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9222 // that the guard pages used by the OS virtual memory manager are allocated in
9223 // correct sequence.
9225 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9226 SelectionDAG &DAG) const {
9227 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9228 getTargetMachine().Options.EnableSegmentedStacks) &&
9229 "This should be used only on Windows targets or when segmented stacks "
9231 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9232 DebugLoc dl = Op.getDebugLoc();
9235 SDValue Chain = Op.getOperand(0);
9236 SDValue Size = Op.getOperand(1);
9237 // FIXME: Ensure alignment here
9239 bool Is64Bit = Subtarget->is64Bit();
9240 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9242 if (getTargetMachine().Options.EnableSegmentedStacks) {
9243 MachineFunction &MF = DAG.getMachineFunction();
9244 MachineRegisterInfo &MRI = MF.getRegInfo();
9247 // The 64 bit implementation of segmented stacks needs to clobber both r10
9248 // r11. This makes it impossible to use it along with nested parameters.
9249 const Function *F = MF.getFunction();
9251 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9253 if (I->hasNestAttr())
9254 report_fatal_error("Cannot use segmented stacks with functions that "
9255 "have nested arguments.");
9258 const TargetRegisterClass *AddrRegClass =
9259 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9260 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9261 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9262 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9263 DAG.getRegister(Vreg, SPTy));
9264 SDValue Ops1[2] = { Value, Chain };
9265 return DAG.getMergeValues(Ops1, 2, dl);
9268 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9270 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9271 Flag = Chain.getValue(1);
9272 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9274 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9275 Flag = Chain.getValue(1);
9277 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9279 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9280 return DAG.getMergeValues(Ops1, 2, dl);
9284 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9285 MachineFunction &MF = DAG.getMachineFunction();
9286 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9288 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9289 DebugLoc DL = Op.getDebugLoc();
9291 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9292 // vastart just stores the address of the VarArgsFrameIndex slot into the
9293 // memory location argument.
9294 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9296 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9297 MachinePointerInfo(SV), false, false, 0);
9301 // gp_offset (0 - 6 * 8)
9302 // fp_offset (48 - 48 + 8 * 16)
9303 // overflow_arg_area (point to parameters coming in memory).
9305 SmallVector<SDValue, 8> MemOps;
9306 SDValue FIN = Op.getOperand(1);
9308 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9309 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9311 FIN, MachinePointerInfo(SV), false, false, 0);
9312 MemOps.push_back(Store);
9315 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9316 FIN, DAG.getIntPtrConstant(4));
9317 Store = DAG.getStore(Op.getOperand(0), DL,
9318 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9320 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9321 MemOps.push_back(Store);
9323 // Store ptr to overflow_arg_area
9324 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9325 FIN, DAG.getIntPtrConstant(4));
9326 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9328 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9329 MachinePointerInfo(SV, 8),
9331 MemOps.push_back(Store);
9333 // Store ptr to reg_save_area.
9334 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9335 FIN, DAG.getIntPtrConstant(8));
9336 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9338 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9339 MachinePointerInfo(SV, 16), false, false, 0);
9340 MemOps.push_back(Store);
9341 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9342 &MemOps[0], MemOps.size());
9345 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9346 assert(Subtarget->is64Bit() &&
9347 "LowerVAARG only handles 64-bit va_arg!");
9348 assert((Subtarget->isTargetLinux() ||
9349 Subtarget->isTargetDarwin()) &&
9350 "Unhandled target in LowerVAARG");
9351 assert(Op.getNode()->getNumOperands() == 4);
9352 SDValue Chain = Op.getOperand(0);
9353 SDValue SrcPtr = Op.getOperand(1);
9354 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9355 unsigned Align = Op.getConstantOperandVal(3);
9356 DebugLoc dl = Op.getDebugLoc();
9358 EVT ArgVT = Op.getNode()->getValueType(0);
9359 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9360 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9363 // Decide which area this value should be read from.
9364 // TODO: Implement the AMD64 ABI in its entirety. This simple
9365 // selection mechanism works only for the basic types.
9366 if (ArgVT == MVT::f80) {
9367 llvm_unreachable("va_arg for f80 not yet implemented");
9368 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9369 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9370 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9371 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9373 llvm_unreachable("Unhandled argument type in LowerVAARG");
9377 // Sanity Check: Make sure using fp_offset makes sense.
9378 assert(!getTargetMachine().Options.UseSoftFloat &&
9379 !(DAG.getMachineFunction()
9380 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9381 Subtarget->hasSSE1());
9384 // Insert VAARG_64 node into the DAG
9385 // VAARG_64 returns two values: Variable Argument Address, Chain
9386 SmallVector<SDValue, 11> InstOps;
9387 InstOps.push_back(Chain);
9388 InstOps.push_back(SrcPtr);
9389 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9390 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9391 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9392 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9393 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9394 VTs, &InstOps[0], InstOps.size(),
9396 MachinePointerInfo(SV),
9401 Chain = VAARG.getValue(1);
9403 // Load the next argument and return it
9404 return DAG.getLoad(ArgVT, dl,
9407 MachinePointerInfo(),
9408 false, false, false, 0);
9411 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9412 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9413 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9414 SDValue Chain = Op.getOperand(0);
9415 SDValue DstPtr = Op.getOperand(1);
9416 SDValue SrcPtr = Op.getOperand(2);
9417 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9418 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9419 DebugLoc DL = Op.getDebugLoc();
9421 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9422 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9424 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9427 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9428 // may or may not be a constant. Takes immediate version of shift as input.
9429 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9430 SDValue SrcOp, SDValue ShAmt,
9431 SelectionDAG &DAG) {
9432 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9434 if (isa<ConstantSDNode>(ShAmt)) {
9436 default: llvm_unreachable("Unknown target vector shift node");
9440 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9444 // Change opcode to non-immediate version
9446 default: llvm_unreachable("Unknown target vector shift node");
9447 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9448 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9449 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9452 // Need to build a vector containing shift amount
9453 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9456 ShOps[1] = DAG.getConstant(0, MVT::i32);
9457 ShOps[2] = DAG.getUNDEF(MVT::i32);
9458 ShOps[3] = DAG.getUNDEF(MVT::i32);
9459 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9460 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9461 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9465 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9466 DebugLoc dl = Op.getDebugLoc();
9467 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9469 default: return SDValue(); // Don't custom lower most intrinsics.
9470 // Comparison intrinsics.
9471 case Intrinsic::x86_sse_comieq_ss:
9472 case Intrinsic::x86_sse_comilt_ss:
9473 case Intrinsic::x86_sse_comile_ss:
9474 case Intrinsic::x86_sse_comigt_ss:
9475 case Intrinsic::x86_sse_comige_ss:
9476 case Intrinsic::x86_sse_comineq_ss:
9477 case Intrinsic::x86_sse_ucomieq_ss:
9478 case Intrinsic::x86_sse_ucomilt_ss:
9479 case Intrinsic::x86_sse_ucomile_ss:
9480 case Intrinsic::x86_sse_ucomigt_ss:
9481 case Intrinsic::x86_sse_ucomige_ss:
9482 case Intrinsic::x86_sse_ucomineq_ss:
9483 case Intrinsic::x86_sse2_comieq_sd:
9484 case Intrinsic::x86_sse2_comilt_sd:
9485 case Intrinsic::x86_sse2_comile_sd:
9486 case Intrinsic::x86_sse2_comigt_sd:
9487 case Intrinsic::x86_sse2_comige_sd:
9488 case Intrinsic::x86_sse2_comineq_sd:
9489 case Intrinsic::x86_sse2_ucomieq_sd:
9490 case Intrinsic::x86_sse2_ucomilt_sd:
9491 case Intrinsic::x86_sse2_ucomile_sd:
9492 case Intrinsic::x86_sse2_ucomigt_sd:
9493 case Intrinsic::x86_sse2_ucomige_sd:
9494 case Intrinsic::x86_sse2_ucomineq_sd: {
9496 ISD::CondCode CC = ISD::SETCC_INVALID;
9498 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9499 case Intrinsic::x86_sse_comieq_ss:
9500 case Intrinsic::x86_sse2_comieq_sd:
9504 case Intrinsic::x86_sse_comilt_ss:
9505 case Intrinsic::x86_sse2_comilt_sd:
9509 case Intrinsic::x86_sse_comile_ss:
9510 case Intrinsic::x86_sse2_comile_sd:
9514 case Intrinsic::x86_sse_comigt_ss:
9515 case Intrinsic::x86_sse2_comigt_sd:
9519 case Intrinsic::x86_sse_comige_ss:
9520 case Intrinsic::x86_sse2_comige_sd:
9524 case Intrinsic::x86_sse_comineq_ss:
9525 case Intrinsic::x86_sse2_comineq_sd:
9529 case Intrinsic::x86_sse_ucomieq_ss:
9530 case Intrinsic::x86_sse2_ucomieq_sd:
9531 Opc = X86ISD::UCOMI;
9534 case Intrinsic::x86_sse_ucomilt_ss:
9535 case Intrinsic::x86_sse2_ucomilt_sd:
9536 Opc = X86ISD::UCOMI;
9539 case Intrinsic::x86_sse_ucomile_ss:
9540 case Intrinsic::x86_sse2_ucomile_sd:
9541 Opc = X86ISD::UCOMI;
9544 case Intrinsic::x86_sse_ucomigt_ss:
9545 case Intrinsic::x86_sse2_ucomigt_sd:
9546 Opc = X86ISD::UCOMI;
9549 case Intrinsic::x86_sse_ucomige_ss:
9550 case Intrinsic::x86_sse2_ucomige_sd:
9551 Opc = X86ISD::UCOMI;
9554 case Intrinsic::x86_sse_ucomineq_ss:
9555 case Intrinsic::x86_sse2_ucomineq_sd:
9556 Opc = X86ISD::UCOMI;
9561 SDValue LHS = Op.getOperand(1);
9562 SDValue RHS = Op.getOperand(2);
9563 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9564 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9565 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9566 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9567 DAG.getConstant(X86CC, MVT::i8), Cond);
9568 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9570 // Arithmetic intrinsics.
9571 case Intrinsic::x86_sse2_pmulu_dq:
9572 case Intrinsic::x86_avx2_pmulu_dq:
9573 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9574 Op.getOperand(1), Op.getOperand(2));
9575 case Intrinsic::x86_sse3_hadd_ps:
9576 case Intrinsic::x86_sse3_hadd_pd:
9577 case Intrinsic::x86_avx_hadd_ps_256:
9578 case Intrinsic::x86_avx_hadd_pd_256:
9579 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9580 Op.getOperand(1), Op.getOperand(2));
9581 case Intrinsic::x86_sse3_hsub_ps:
9582 case Intrinsic::x86_sse3_hsub_pd:
9583 case Intrinsic::x86_avx_hsub_ps_256:
9584 case Intrinsic::x86_avx_hsub_pd_256:
9585 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9586 Op.getOperand(1), Op.getOperand(2));
9587 case Intrinsic::x86_ssse3_phadd_w_128:
9588 case Intrinsic::x86_ssse3_phadd_d_128:
9589 case Intrinsic::x86_avx2_phadd_w:
9590 case Intrinsic::x86_avx2_phadd_d:
9591 return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9592 Op.getOperand(1), Op.getOperand(2));
9593 case Intrinsic::x86_ssse3_phsub_w_128:
9594 case Intrinsic::x86_ssse3_phsub_d_128:
9595 case Intrinsic::x86_avx2_phsub_w:
9596 case Intrinsic::x86_avx2_phsub_d:
9597 return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9598 Op.getOperand(1), Op.getOperand(2));
9599 case Intrinsic::x86_avx2_psllv_d:
9600 case Intrinsic::x86_avx2_psllv_q:
9601 case Intrinsic::x86_avx2_psllv_d_256:
9602 case Intrinsic::x86_avx2_psllv_q_256:
9603 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9604 Op.getOperand(1), Op.getOperand(2));
9605 case Intrinsic::x86_avx2_psrlv_d:
9606 case Intrinsic::x86_avx2_psrlv_q:
9607 case Intrinsic::x86_avx2_psrlv_d_256:
9608 case Intrinsic::x86_avx2_psrlv_q_256:
9609 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9610 Op.getOperand(1), Op.getOperand(2));
9611 case Intrinsic::x86_avx2_psrav_d:
9612 case Intrinsic::x86_avx2_psrav_d_256:
9613 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9614 Op.getOperand(1), Op.getOperand(2));
9615 case Intrinsic::x86_ssse3_pshuf_b_128:
9616 case Intrinsic::x86_avx2_pshuf_b:
9617 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9618 Op.getOperand(1), Op.getOperand(2));
9619 case Intrinsic::x86_ssse3_psign_b_128:
9620 case Intrinsic::x86_ssse3_psign_w_128:
9621 case Intrinsic::x86_ssse3_psign_d_128:
9622 case Intrinsic::x86_avx2_psign_b:
9623 case Intrinsic::x86_avx2_psign_w:
9624 case Intrinsic::x86_avx2_psign_d:
9625 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9626 Op.getOperand(1), Op.getOperand(2));
9627 case Intrinsic::x86_sse41_insertps:
9628 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9629 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9630 case Intrinsic::x86_avx_vperm2f128_ps_256:
9631 case Intrinsic::x86_avx_vperm2f128_pd_256:
9632 case Intrinsic::x86_avx_vperm2f128_si_256:
9633 case Intrinsic::x86_avx2_vperm2i128:
9634 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9635 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9636 case Intrinsic::x86_avx2_permd:
9637 case Intrinsic::x86_avx2_permps:
9638 // Operands intentionally swapped. Mask is last operand to intrinsic,
9639 // but second operand for node/intruction.
9640 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9641 Op.getOperand(2), Op.getOperand(1));
9643 // ptest and testp intrinsics. The intrinsic these come from are designed to
9644 // return an integer value, not just an instruction so lower it to the ptest
9645 // or testp pattern and a setcc for the result.
9646 case Intrinsic::x86_sse41_ptestz:
9647 case Intrinsic::x86_sse41_ptestc:
9648 case Intrinsic::x86_sse41_ptestnzc:
9649 case Intrinsic::x86_avx_ptestz_256:
9650 case Intrinsic::x86_avx_ptestc_256:
9651 case Intrinsic::x86_avx_ptestnzc_256:
9652 case Intrinsic::x86_avx_vtestz_ps:
9653 case Intrinsic::x86_avx_vtestc_ps:
9654 case Intrinsic::x86_avx_vtestnzc_ps:
9655 case Intrinsic::x86_avx_vtestz_pd:
9656 case Intrinsic::x86_avx_vtestc_pd:
9657 case Intrinsic::x86_avx_vtestnzc_pd:
9658 case Intrinsic::x86_avx_vtestz_ps_256:
9659 case Intrinsic::x86_avx_vtestc_ps_256:
9660 case Intrinsic::x86_avx_vtestnzc_ps_256:
9661 case Intrinsic::x86_avx_vtestz_pd_256:
9662 case Intrinsic::x86_avx_vtestc_pd_256:
9663 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9664 bool IsTestPacked = false;
9667 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9668 case Intrinsic::x86_avx_vtestz_ps:
9669 case Intrinsic::x86_avx_vtestz_pd:
9670 case Intrinsic::x86_avx_vtestz_ps_256:
9671 case Intrinsic::x86_avx_vtestz_pd_256:
9672 IsTestPacked = true; // Fallthrough
9673 case Intrinsic::x86_sse41_ptestz:
9674 case Intrinsic::x86_avx_ptestz_256:
9676 X86CC = X86::COND_E;
9678 case Intrinsic::x86_avx_vtestc_ps:
9679 case Intrinsic::x86_avx_vtestc_pd:
9680 case Intrinsic::x86_avx_vtestc_ps_256:
9681 case Intrinsic::x86_avx_vtestc_pd_256:
9682 IsTestPacked = true; // Fallthrough
9683 case Intrinsic::x86_sse41_ptestc:
9684 case Intrinsic::x86_avx_ptestc_256:
9686 X86CC = X86::COND_B;
9688 case Intrinsic::x86_avx_vtestnzc_ps:
9689 case Intrinsic::x86_avx_vtestnzc_pd:
9690 case Intrinsic::x86_avx_vtestnzc_ps_256:
9691 case Intrinsic::x86_avx_vtestnzc_pd_256:
9692 IsTestPacked = true; // Fallthrough
9693 case Intrinsic::x86_sse41_ptestnzc:
9694 case Intrinsic::x86_avx_ptestnzc_256:
9696 X86CC = X86::COND_A;
9700 SDValue LHS = Op.getOperand(1);
9701 SDValue RHS = Op.getOperand(2);
9702 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9703 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9704 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9705 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9706 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9709 // SSE/AVX shift intrinsics
9710 case Intrinsic::x86_sse2_psll_w:
9711 case Intrinsic::x86_sse2_psll_d:
9712 case Intrinsic::x86_sse2_psll_q:
9713 case Intrinsic::x86_avx2_psll_w:
9714 case Intrinsic::x86_avx2_psll_d:
9715 case Intrinsic::x86_avx2_psll_q:
9716 return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9717 Op.getOperand(1), Op.getOperand(2));
9718 case Intrinsic::x86_sse2_psrl_w:
9719 case Intrinsic::x86_sse2_psrl_d:
9720 case Intrinsic::x86_sse2_psrl_q:
9721 case Intrinsic::x86_avx2_psrl_w:
9722 case Intrinsic::x86_avx2_psrl_d:
9723 case Intrinsic::x86_avx2_psrl_q:
9724 return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9725 Op.getOperand(1), Op.getOperand(2));
9726 case Intrinsic::x86_sse2_psra_w:
9727 case Intrinsic::x86_sse2_psra_d:
9728 case Intrinsic::x86_avx2_psra_w:
9729 case Intrinsic::x86_avx2_psra_d:
9730 return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9731 Op.getOperand(1), Op.getOperand(2));
9732 case Intrinsic::x86_sse2_pslli_w:
9733 case Intrinsic::x86_sse2_pslli_d:
9734 case Intrinsic::x86_sse2_pslli_q:
9735 case Intrinsic::x86_avx2_pslli_w:
9736 case Intrinsic::x86_avx2_pslli_d:
9737 case Intrinsic::x86_avx2_pslli_q:
9738 return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9739 Op.getOperand(1), Op.getOperand(2), DAG);
9740 case Intrinsic::x86_sse2_psrli_w:
9741 case Intrinsic::x86_sse2_psrli_d:
9742 case Intrinsic::x86_sse2_psrli_q:
9743 case Intrinsic::x86_avx2_psrli_w:
9744 case Intrinsic::x86_avx2_psrli_d:
9745 case Intrinsic::x86_avx2_psrli_q:
9746 return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9747 Op.getOperand(1), Op.getOperand(2), DAG);
9748 case Intrinsic::x86_sse2_psrai_w:
9749 case Intrinsic::x86_sse2_psrai_d:
9750 case Intrinsic::x86_avx2_psrai_w:
9751 case Intrinsic::x86_avx2_psrai_d:
9752 return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9753 Op.getOperand(1), Op.getOperand(2), DAG);
9754 // Fix vector shift instructions where the last operand is a non-immediate
9756 case Intrinsic::x86_mmx_pslli_w:
9757 case Intrinsic::x86_mmx_pslli_d:
9758 case Intrinsic::x86_mmx_pslli_q:
9759 case Intrinsic::x86_mmx_psrli_w:
9760 case Intrinsic::x86_mmx_psrli_d:
9761 case Intrinsic::x86_mmx_psrli_q:
9762 case Intrinsic::x86_mmx_psrai_w:
9763 case Intrinsic::x86_mmx_psrai_d: {
9764 SDValue ShAmt = Op.getOperand(2);
9765 if (isa<ConstantSDNode>(ShAmt))
9768 unsigned NewIntNo = 0;
9770 case Intrinsic::x86_mmx_pslli_w:
9771 NewIntNo = Intrinsic::x86_mmx_psll_w;
9773 case Intrinsic::x86_mmx_pslli_d:
9774 NewIntNo = Intrinsic::x86_mmx_psll_d;
9776 case Intrinsic::x86_mmx_pslli_q:
9777 NewIntNo = Intrinsic::x86_mmx_psll_q;
9779 case Intrinsic::x86_mmx_psrli_w:
9780 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9782 case Intrinsic::x86_mmx_psrli_d:
9783 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9785 case Intrinsic::x86_mmx_psrli_q:
9786 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9788 case Intrinsic::x86_mmx_psrai_w:
9789 NewIntNo = Intrinsic::x86_mmx_psra_w;
9791 case Intrinsic::x86_mmx_psrai_d:
9792 NewIntNo = Intrinsic::x86_mmx_psra_d;
9794 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9797 // The vector shift intrinsics with scalars uses 32b shift amounts but
9798 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9800 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9801 DAG.getConstant(0, MVT::i32));
9802 // FIXME this must be lowered to get rid of the invalid type.
9804 EVT VT = Op.getValueType();
9805 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9806 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9807 DAG.getConstant(NewIntNo, MVT::i32),
9808 Op.getOperand(1), ShAmt);
9813 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9814 SelectionDAG &DAG) const {
9815 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9816 MFI->setReturnAddressIsTaken(true);
9818 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9819 DebugLoc dl = Op.getDebugLoc();
9822 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9824 DAG.getConstant(TD->getPointerSize(),
9825 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9826 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9827 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9829 MachinePointerInfo(), false, false, false, 0);
9832 // Just load the return address.
9833 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9834 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9835 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9838 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9839 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9840 MFI->setFrameAddressIsTaken(true);
9842 EVT VT = Op.getValueType();
9843 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9844 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9845 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9846 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9848 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9849 MachinePointerInfo(),
9850 false, false, false, 0);
9854 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9855 SelectionDAG &DAG) const {
9856 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9859 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9860 SDValue Chain = Op.getOperand(0);
9861 SDValue Offset = Op.getOperand(1);
9862 SDValue Handler = Op.getOperand(2);
9863 DebugLoc dl = Op.getDebugLoc();
9865 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9866 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9868 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9870 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9871 DAG.getIntPtrConstant(TD->getPointerSize()));
9872 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9873 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9875 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9877 return DAG.getNode(X86ISD::EH_RETURN, dl,
9879 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9882 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9883 SelectionDAG &DAG) const {
9884 return Op.getOperand(0);
9887 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9888 SelectionDAG &DAG) const {
9889 SDValue Root = Op.getOperand(0);
9890 SDValue Trmp = Op.getOperand(1); // trampoline
9891 SDValue FPtr = Op.getOperand(2); // nested function
9892 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9893 DebugLoc dl = Op.getDebugLoc();
9895 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9897 if (Subtarget->is64Bit()) {
9898 SDValue OutChains[6];
9900 // Large code-model.
9901 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9902 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9904 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9905 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9907 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9909 // Load the pointer to the nested function into R11.
9910 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9911 SDValue Addr = Trmp;
9912 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9913 Addr, MachinePointerInfo(TrmpAddr),
9916 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9917 DAG.getConstant(2, MVT::i64));
9918 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9919 MachinePointerInfo(TrmpAddr, 2),
9922 // Load the 'nest' parameter value into R10.
9923 // R10 is specified in X86CallingConv.td
9924 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9925 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9926 DAG.getConstant(10, MVT::i64));
9927 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9928 Addr, MachinePointerInfo(TrmpAddr, 10),
9931 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9932 DAG.getConstant(12, MVT::i64));
9933 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9934 MachinePointerInfo(TrmpAddr, 12),
9937 // Jump to the nested function.
9938 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9939 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9940 DAG.getConstant(20, MVT::i64));
9941 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9942 Addr, MachinePointerInfo(TrmpAddr, 20),
9945 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9946 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9947 DAG.getConstant(22, MVT::i64));
9948 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9949 MachinePointerInfo(TrmpAddr, 22),
9952 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9954 const Function *Func =
9955 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9956 CallingConv::ID CC = Func->getCallingConv();
9961 llvm_unreachable("Unsupported calling convention");
9962 case CallingConv::C:
9963 case CallingConv::X86_StdCall: {
9964 // Pass 'nest' parameter in ECX.
9965 // Must be kept in sync with X86CallingConv.td
9968 // Check that ECX wasn't needed by an 'inreg' parameter.
9969 FunctionType *FTy = Func->getFunctionType();
9970 const AttrListPtr &Attrs = Func->getAttributes();
9972 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9973 unsigned InRegCount = 0;
9976 for (FunctionType::param_iterator I = FTy->param_begin(),
9977 E = FTy->param_end(); I != E; ++I, ++Idx)
9978 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9979 // FIXME: should only count parameters that are lowered to integers.
9980 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9982 if (InRegCount > 2) {
9983 report_fatal_error("Nest register in use - reduce number of inreg"
9989 case CallingConv::X86_FastCall:
9990 case CallingConv::X86_ThisCall:
9991 case CallingConv::Fast:
9992 // Pass 'nest' parameter in EAX.
9993 // Must be kept in sync with X86CallingConv.td
9998 SDValue OutChains[4];
10001 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10002 DAG.getConstant(10, MVT::i32));
10003 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10005 // This is storing the opcode for MOV32ri.
10006 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10007 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10008 OutChains[0] = DAG.getStore(Root, dl,
10009 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10010 Trmp, MachinePointerInfo(TrmpAddr),
10013 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10014 DAG.getConstant(1, MVT::i32));
10015 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10016 MachinePointerInfo(TrmpAddr, 1),
10019 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10020 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10021 DAG.getConstant(5, MVT::i32));
10022 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10023 MachinePointerInfo(TrmpAddr, 5),
10026 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10027 DAG.getConstant(6, MVT::i32));
10028 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10029 MachinePointerInfo(TrmpAddr, 6),
10032 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10036 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10037 SelectionDAG &DAG) const {
10039 The rounding mode is in bits 11:10 of FPSR, and has the following
10041 00 Round to nearest
10046 FLT_ROUNDS, on the other hand, expects the following:
10053 To perform the conversion, we do:
10054 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10057 MachineFunction &MF = DAG.getMachineFunction();
10058 const TargetMachine &TM = MF.getTarget();
10059 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10060 unsigned StackAlignment = TFI.getStackAlignment();
10061 EVT VT = Op.getValueType();
10062 DebugLoc DL = Op.getDebugLoc();
10064 // Save FP Control Word to stack slot
10065 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10066 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10069 MachineMemOperand *MMO =
10070 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10071 MachineMemOperand::MOStore, 2, 2);
10073 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10074 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10075 DAG.getVTList(MVT::Other),
10076 Ops, 2, MVT::i16, MMO);
10078 // Load FP Control Word from stack slot
10079 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10080 MachinePointerInfo(), false, false, false, 0);
10082 // Transform as necessary
10084 DAG.getNode(ISD::SRL, DL, MVT::i16,
10085 DAG.getNode(ISD::AND, DL, MVT::i16,
10086 CWD, DAG.getConstant(0x800, MVT::i16)),
10087 DAG.getConstant(11, MVT::i8));
10089 DAG.getNode(ISD::SRL, DL, MVT::i16,
10090 DAG.getNode(ISD::AND, DL, MVT::i16,
10091 CWD, DAG.getConstant(0x400, MVT::i16)),
10092 DAG.getConstant(9, MVT::i8));
10095 DAG.getNode(ISD::AND, DL, MVT::i16,
10096 DAG.getNode(ISD::ADD, DL, MVT::i16,
10097 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10098 DAG.getConstant(1, MVT::i16)),
10099 DAG.getConstant(3, MVT::i16));
10102 return DAG.getNode((VT.getSizeInBits() < 16 ?
10103 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10106 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10107 EVT VT = Op.getValueType();
10109 unsigned NumBits = VT.getSizeInBits();
10110 DebugLoc dl = Op.getDebugLoc();
10112 Op = Op.getOperand(0);
10113 if (VT == MVT::i8) {
10114 // Zero extend to i32 since there is not an i8 bsr.
10116 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10119 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10120 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10121 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10123 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10126 DAG.getConstant(NumBits+NumBits-1, OpVT),
10127 DAG.getConstant(X86::COND_E, MVT::i8),
10130 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10132 // Finally xor with NumBits-1.
10133 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10136 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10140 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10141 SelectionDAG &DAG) const {
10142 EVT VT = Op.getValueType();
10144 unsigned NumBits = VT.getSizeInBits();
10145 DebugLoc dl = Op.getDebugLoc();
10147 Op = Op.getOperand(0);
10148 if (VT == MVT::i8) {
10149 // Zero extend to i32 since there is not an i8 bsr.
10151 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10154 // Issue a bsr (scan bits in reverse).
10155 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10156 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10158 // And xor with NumBits-1.
10159 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10162 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10166 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10167 EVT VT = Op.getValueType();
10168 unsigned NumBits = VT.getSizeInBits();
10169 DebugLoc dl = Op.getDebugLoc();
10170 Op = Op.getOperand(0);
10172 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10173 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10174 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10176 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10179 DAG.getConstant(NumBits, VT),
10180 DAG.getConstant(X86::COND_E, MVT::i8),
10183 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10186 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10187 // ones, and then concatenate the result back.
10188 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10189 EVT VT = Op.getValueType();
10191 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10192 "Unsupported value type for operation");
10194 unsigned NumElems = VT.getVectorNumElements();
10195 DebugLoc dl = Op.getDebugLoc();
10197 // Extract the LHS vectors
10198 SDValue LHS = Op.getOperand(0);
10199 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10200 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10202 // Extract the RHS vectors
10203 SDValue RHS = Op.getOperand(1);
10204 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10205 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10207 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10208 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10210 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10211 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10212 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10215 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10216 assert(Op.getValueType().getSizeInBits() == 256 &&
10217 Op.getValueType().isInteger() &&
10218 "Only handle AVX 256-bit vector integer operation");
10219 return Lower256IntArith(Op, DAG);
10222 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10223 assert(Op.getValueType().getSizeInBits() == 256 &&
10224 Op.getValueType().isInteger() &&
10225 "Only handle AVX 256-bit vector integer operation");
10226 return Lower256IntArith(Op, DAG);
10229 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10230 EVT VT = Op.getValueType();
10232 // Decompose 256-bit ops into smaller 128-bit ops.
10233 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10234 return Lower256IntArith(Op, DAG);
10236 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10237 "Only know how to lower V2I64/V4I64 multiply");
10239 DebugLoc dl = Op.getDebugLoc();
10241 // Ahi = psrlqi(a, 32);
10242 // Bhi = psrlqi(b, 32);
10244 // AloBlo = pmuludq(a, b);
10245 // AloBhi = pmuludq(a, Bhi);
10246 // AhiBlo = pmuludq(Ahi, b);
10248 // AloBhi = psllqi(AloBhi, 32);
10249 // AhiBlo = psllqi(AhiBlo, 32);
10250 // return AloBlo + AloBhi + AhiBlo;
10252 SDValue A = Op.getOperand(0);
10253 SDValue B = Op.getOperand(1);
10255 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10257 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10258 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10260 // Bit cast to 32-bit vectors for MULUDQ
10261 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10262 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10263 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10264 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10265 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10267 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10268 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10269 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10271 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10272 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10274 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10275 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10278 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10280 EVT VT = Op.getValueType();
10281 DebugLoc dl = Op.getDebugLoc();
10282 SDValue R = Op.getOperand(0);
10283 SDValue Amt = Op.getOperand(1);
10284 LLVMContext *Context = DAG.getContext();
10286 if (!Subtarget->hasSSE2())
10289 // Optimize shl/srl/sra with constant shift amount.
10290 if (isSplatVector(Amt.getNode())) {
10291 SDValue SclrAmt = Amt->getOperand(0);
10292 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10293 uint64_t ShiftAmt = C->getZExtValue();
10295 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10296 (Subtarget->hasAVX2() &&
10297 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10298 if (Op.getOpcode() == ISD::SHL)
10299 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10300 DAG.getConstant(ShiftAmt, MVT::i32));
10301 if (Op.getOpcode() == ISD::SRL)
10302 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10303 DAG.getConstant(ShiftAmt, MVT::i32));
10304 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10305 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10306 DAG.getConstant(ShiftAmt, MVT::i32));
10309 if (VT == MVT::v16i8) {
10310 if (Op.getOpcode() == ISD::SHL) {
10311 // Make a large shift.
10312 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10313 DAG.getConstant(ShiftAmt, MVT::i32));
10314 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10315 // Zero out the rightmost bits.
10316 SmallVector<SDValue, 16> V(16,
10317 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10319 return DAG.getNode(ISD::AND, dl, VT, SHL,
10320 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10322 if (Op.getOpcode() == ISD::SRL) {
10323 // Make a large shift.
10324 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10325 DAG.getConstant(ShiftAmt, MVT::i32));
10326 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10327 // Zero out the leftmost bits.
10328 SmallVector<SDValue, 16> V(16,
10329 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10331 return DAG.getNode(ISD::AND, dl, VT, SRL,
10332 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10334 if (Op.getOpcode() == ISD::SRA) {
10335 if (ShiftAmt == 7) {
10336 // R s>> 7 === R s< 0
10337 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10338 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10341 // R s>> a === ((R u>> a) ^ m) - m
10342 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10343 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10345 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10346 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10347 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10350 llvm_unreachable("Unknown shift opcode.");
10353 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10354 if (Op.getOpcode() == ISD::SHL) {
10355 // Make a large shift.
10356 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10357 DAG.getConstant(ShiftAmt, MVT::i32));
10358 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10359 // Zero out the rightmost bits.
10360 SmallVector<SDValue, 32> V(32,
10361 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10363 return DAG.getNode(ISD::AND, dl, VT, SHL,
10364 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10366 if (Op.getOpcode() == ISD::SRL) {
10367 // Make a large shift.
10368 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10369 DAG.getConstant(ShiftAmt, MVT::i32));
10370 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10371 // Zero out the leftmost bits.
10372 SmallVector<SDValue, 32> V(32,
10373 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10375 return DAG.getNode(ISD::AND, dl, VT, SRL,
10376 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10378 if (Op.getOpcode() == ISD::SRA) {
10379 if (ShiftAmt == 7) {
10380 // R s>> 7 === R s< 0
10381 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10382 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10385 // R s>> a === ((R u>> a) ^ m) - m
10386 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10387 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10389 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10390 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10391 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10394 llvm_unreachable("Unknown shift opcode.");
10399 // Lower SHL with variable shift amount.
10400 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10401 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10402 DAG.getConstant(23, MVT::i32));
10404 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10405 Constant *C = ConstantDataVector::get(*Context, CV);
10406 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10407 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10408 MachinePointerInfo::getConstantPool(),
10409 false, false, false, 16);
10411 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10412 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10413 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10414 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10416 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10417 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10420 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10421 DAG.getConstant(5, MVT::i32));
10422 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10424 // Turn 'a' into a mask suitable for VSELECT
10425 SDValue VSelM = DAG.getConstant(0x80, VT);
10426 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10427 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10429 SDValue CM1 = DAG.getConstant(0x0f, VT);
10430 SDValue CM2 = DAG.getConstant(0x3f, VT);
10432 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10433 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10434 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10435 DAG.getConstant(4, MVT::i32), DAG);
10436 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10437 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10440 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10441 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10442 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10444 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10445 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10446 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10447 DAG.getConstant(2, MVT::i32), DAG);
10448 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10449 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10452 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10453 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10454 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10456 // return VSELECT(r, r+r, a);
10457 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10458 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10462 // Decompose 256-bit shifts into smaller 128-bit shifts.
10463 if (VT.getSizeInBits() == 256) {
10464 unsigned NumElems = VT.getVectorNumElements();
10465 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10466 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10468 // Extract the two vectors
10469 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10470 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10472 // Recreate the shift amount vectors
10473 SDValue Amt1, Amt2;
10474 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10475 // Constant shift amount
10476 SmallVector<SDValue, 4> Amt1Csts;
10477 SmallVector<SDValue, 4> Amt2Csts;
10478 for (unsigned i = 0; i != NumElems/2; ++i)
10479 Amt1Csts.push_back(Amt->getOperand(i));
10480 for (unsigned i = NumElems/2; i != NumElems; ++i)
10481 Amt2Csts.push_back(Amt->getOperand(i));
10483 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10484 &Amt1Csts[0], NumElems/2);
10485 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10486 &Amt2Csts[0], NumElems/2);
10488 // Variable shift amount
10489 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10490 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10493 // Issue new vector shifts for the smaller types
10494 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10495 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10497 // Concatenate the result back
10498 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10504 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10505 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10506 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10507 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10508 // has only one use.
10509 SDNode *N = Op.getNode();
10510 SDValue LHS = N->getOperand(0);
10511 SDValue RHS = N->getOperand(1);
10512 unsigned BaseOp = 0;
10514 DebugLoc DL = Op.getDebugLoc();
10515 switch (Op.getOpcode()) {
10516 default: llvm_unreachable("Unknown ovf instruction!");
10518 // A subtract of one will be selected as a INC. Note that INC doesn't
10519 // set CF, so we can't do this for UADDO.
10520 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10522 BaseOp = X86ISD::INC;
10523 Cond = X86::COND_O;
10526 BaseOp = X86ISD::ADD;
10527 Cond = X86::COND_O;
10530 BaseOp = X86ISD::ADD;
10531 Cond = X86::COND_B;
10534 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10535 // set CF, so we can't do this for USUBO.
10536 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10538 BaseOp = X86ISD::DEC;
10539 Cond = X86::COND_O;
10542 BaseOp = X86ISD::SUB;
10543 Cond = X86::COND_O;
10546 BaseOp = X86ISD::SUB;
10547 Cond = X86::COND_B;
10550 BaseOp = X86ISD::SMUL;
10551 Cond = X86::COND_O;
10553 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10554 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10556 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10559 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10560 DAG.getConstant(X86::COND_O, MVT::i32),
10561 SDValue(Sum.getNode(), 2));
10563 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10567 // Also sets EFLAGS.
10568 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10569 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10572 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10573 DAG.getConstant(Cond, MVT::i32),
10574 SDValue(Sum.getNode(), 1));
10576 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10579 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10580 SelectionDAG &DAG) const {
10581 DebugLoc dl = Op.getDebugLoc();
10582 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10583 EVT VT = Op.getValueType();
10585 if (!Subtarget->hasSSE2() || !VT.isVector())
10588 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10589 ExtraVT.getScalarType().getSizeInBits();
10590 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10592 switch (VT.getSimpleVT().SimpleTy) {
10593 default: return SDValue();
10596 if (!Subtarget->hasAVX())
10598 if (!Subtarget->hasAVX2()) {
10599 // needs to be split
10600 unsigned NumElems = VT.getVectorNumElements();
10602 // Extract the LHS vectors
10603 SDValue LHS = Op.getOperand(0);
10604 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10605 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10607 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10608 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10610 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10611 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10612 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10614 SDValue Extra = DAG.getValueType(ExtraVT);
10616 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10617 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10619 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10624 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10625 Op.getOperand(0), ShAmt, DAG);
10626 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10632 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10633 DebugLoc dl = Op.getDebugLoc();
10635 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10636 // There isn't any reason to disable it if the target processor supports it.
10637 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10638 SDValue Chain = Op.getOperand(0);
10639 SDValue Zero = DAG.getConstant(0, MVT::i32);
10641 DAG.getRegister(X86::ESP, MVT::i32), // Base
10642 DAG.getTargetConstant(1, MVT::i8), // Scale
10643 DAG.getRegister(0, MVT::i32), // Index
10644 DAG.getTargetConstant(0, MVT::i32), // Disp
10645 DAG.getRegister(0, MVT::i32), // Segment.
10650 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10651 array_lengthof(Ops));
10652 return SDValue(Res, 0);
10655 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10657 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10659 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10660 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10661 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10662 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10664 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10665 if (!Op1 && !Op2 && !Op3 && Op4)
10666 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10668 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10669 if (Op1 && !Op2 && !Op3 && !Op4)
10670 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10672 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10674 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10677 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10678 SelectionDAG &DAG) const {
10679 DebugLoc dl = Op.getDebugLoc();
10680 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10681 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10682 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10683 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10685 // The only fence that needs an instruction is a sequentially-consistent
10686 // cross-thread fence.
10687 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10688 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10689 // no-sse2). There isn't any reason to disable it if the target processor
10691 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10692 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10694 SDValue Chain = Op.getOperand(0);
10695 SDValue Zero = DAG.getConstant(0, MVT::i32);
10697 DAG.getRegister(X86::ESP, MVT::i32), // Base
10698 DAG.getTargetConstant(1, MVT::i8), // Scale
10699 DAG.getRegister(0, MVT::i32), // Index
10700 DAG.getTargetConstant(0, MVT::i32), // Disp
10701 DAG.getRegister(0, MVT::i32), // Segment.
10706 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10707 array_lengthof(Ops));
10708 return SDValue(Res, 0);
10711 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10712 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10716 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10717 EVT T = Op.getValueType();
10718 DebugLoc DL = Op.getDebugLoc();
10721 switch(T.getSimpleVT().SimpleTy) {
10722 default: llvm_unreachable("Invalid value type!");
10723 case MVT::i8: Reg = X86::AL; size = 1; break;
10724 case MVT::i16: Reg = X86::AX; size = 2; break;
10725 case MVT::i32: Reg = X86::EAX; size = 4; break;
10727 assert(Subtarget->is64Bit() && "Node not type legal!");
10728 Reg = X86::RAX; size = 8;
10731 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10732 Op.getOperand(2), SDValue());
10733 SDValue Ops[] = { cpIn.getValue(0),
10736 DAG.getTargetConstant(size, MVT::i8),
10737 cpIn.getValue(1) };
10738 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10739 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10740 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10743 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10747 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10748 SelectionDAG &DAG) const {
10749 assert(Subtarget->is64Bit() && "Result not type legalized?");
10750 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10751 SDValue TheChain = Op.getOperand(0);
10752 DebugLoc dl = Op.getDebugLoc();
10753 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10754 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10755 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10757 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10758 DAG.getConstant(32, MVT::i8));
10760 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10763 return DAG.getMergeValues(Ops, 2, dl);
10766 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10767 SelectionDAG &DAG) const {
10768 EVT SrcVT = Op.getOperand(0).getValueType();
10769 EVT DstVT = Op.getValueType();
10770 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10771 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10772 assert((DstVT == MVT::i64 ||
10773 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10774 "Unexpected custom BITCAST");
10775 // i64 <=> MMX conversions are Legal.
10776 if (SrcVT==MVT::i64 && DstVT.isVector())
10778 if (DstVT==MVT::i64 && SrcVT.isVector())
10780 // MMX <=> MMX conversions are Legal.
10781 if (SrcVT.isVector() && DstVT.isVector())
10783 // All other conversions need to be expanded.
10787 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10788 SDNode *Node = Op.getNode();
10789 DebugLoc dl = Node->getDebugLoc();
10790 EVT T = Node->getValueType(0);
10791 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10792 DAG.getConstant(0, T), Node->getOperand(2));
10793 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10794 cast<AtomicSDNode>(Node)->getMemoryVT(),
10795 Node->getOperand(0),
10796 Node->getOperand(1), negOp,
10797 cast<AtomicSDNode>(Node)->getSrcValue(),
10798 cast<AtomicSDNode>(Node)->getAlignment(),
10799 cast<AtomicSDNode>(Node)->getOrdering(),
10800 cast<AtomicSDNode>(Node)->getSynchScope());
10803 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10804 SDNode *Node = Op.getNode();
10805 DebugLoc dl = Node->getDebugLoc();
10806 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10808 // Convert seq_cst store -> xchg
10809 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10810 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10811 // (The only way to get a 16-byte store is cmpxchg16b)
10812 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10813 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10814 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10815 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10816 cast<AtomicSDNode>(Node)->getMemoryVT(),
10817 Node->getOperand(0),
10818 Node->getOperand(1), Node->getOperand(2),
10819 cast<AtomicSDNode>(Node)->getMemOperand(),
10820 cast<AtomicSDNode>(Node)->getOrdering(),
10821 cast<AtomicSDNode>(Node)->getSynchScope());
10822 return Swap.getValue(1);
10824 // Other atomic stores have a simple pattern.
10828 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10829 EVT VT = Op.getNode()->getValueType(0);
10831 // Let legalize expand this if it isn't a legal type yet.
10832 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10835 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10838 bool ExtraOp = false;
10839 switch (Op.getOpcode()) {
10840 default: llvm_unreachable("Invalid code");
10841 case ISD::ADDC: Opc = X86ISD::ADD; break;
10842 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10843 case ISD::SUBC: Opc = X86ISD::SUB; break;
10844 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10848 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10850 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10851 Op.getOperand(1), Op.getOperand(2));
10854 /// LowerOperation - Provide custom lowering hooks for some operations.
10856 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10857 switch (Op.getOpcode()) {
10858 default: llvm_unreachable("Should not custom lower this!");
10859 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10860 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10861 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10862 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10863 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10864 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10865 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10866 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10867 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10868 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10869 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10870 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10871 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10872 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10873 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10874 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10875 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10876 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10877 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10878 case ISD::SHL_PARTS:
10879 case ISD::SRA_PARTS:
10880 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10881 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10882 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10883 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10884 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10885 case ISD::FABS: return LowerFABS(Op, DAG);
10886 case ISD::FNEG: return LowerFNEG(Op, DAG);
10887 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10888 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10889 case ISD::SETCC: return LowerSETCC(Op, DAG);
10890 case ISD::SELECT: return LowerSELECT(Op, DAG);
10891 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10892 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10893 case ISD::VASTART: return LowerVASTART(Op, DAG);
10894 case ISD::VAARG: return LowerVAARG(Op, DAG);
10895 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10896 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10897 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10898 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10899 case ISD::FRAME_TO_ARGS_OFFSET:
10900 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10901 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10902 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10903 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10904 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10905 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10906 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10907 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10908 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10909 case ISD::MUL: return LowerMUL(Op, DAG);
10912 case ISD::SHL: return LowerShift(Op, DAG);
10918 case ISD::UMULO: return LowerXALUO(Op, DAG);
10919 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10920 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10924 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10925 case ISD::ADD: return LowerADD(Op, DAG);
10926 case ISD::SUB: return LowerSUB(Op, DAG);
10930 static void ReplaceATOMIC_LOAD(SDNode *Node,
10931 SmallVectorImpl<SDValue> &Results,
10932 SelectionDAG &DAG) {
10933 DebugLoc dl = Node->getDebugLoc();
10934 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10936 // Convert wide load -> cmpxchg8b/cmpxchg16b
10937 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10938 // (The only way to get a 16-byte load is cmpxchg16b)
10939 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10940 SDValue Zero = DAG.getConstant(0, VT);
10941 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10942 Node->getOperand(0),
10943 Node->getOperand(1), Zero, Zero,
10944 cast<AtomicSDNode>(Node)->getMemOperand(),
10945 cast<AtomicSDNode>(Node)->getOrdering(),
10946 cast<AtomicSDNode>(Node)->getSynchScope());
10947 Results.push_back(Swap.getValue(0));
10948 Results.push_back(Swap.getValue(1));
10951 void X86TargetLowering::
10952 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10953 SelectionDAG &DAG, unsigned NewOp) const {
10954 DebugLoc dl = Node->getDebugLoc();
10955 assert (Node->getValueType(0) == MVT::i64 &&
10956 "Only know how to expand i64 atomics");
10958 SDValue Chain = Node->getOperand(0);
10959 SDValue In1 = Node->getOperand(1);
10960 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10961 Node->getOperand(2), DAG.getIntPtrConstant(0));
10962 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10963 Node->getOperand(2), DAG.getIntPtrConstant(1));
10964 SDValue Ops[] = { Chain, In1, In2L, In2H };
10965 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10967 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10968 cast<MemSDNode>(Node)->getMemOperand());
10969 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10970 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10971 Results.push_back(Result.getValue(2));
10974 /// ReplaceNodeResults - Replace a node with an illegal result type
10975 /// with a new node built out of custom code.
10976 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10977 SmallVectorImpl<SDValue>&Results,
10978 SelectionDAG &DAG) const {
10979 DebugLoc dl = N->getDebugLoc();
10980 switch (N->getOpcode()) {
10982 llvm_unreachable("Do not know how to custom type legalize this operation!");
10983 case ISD::SIGN_EXTEND_INREG:
10988 // We don't want to expand or promote these.
10990 case ISD::FP_TO_SINT:
10991 case ISD::FP_TO_UINT: {
10992 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10994 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
10997 std::pair<SDValue,SDValue> Vals =
10998 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
10999 SDValue FIST = Vals.first, StackSlot = Vals.second;
11000 if (FIST.getNode() != 0) {
11001 EVT VT = N->getValueType(0);
11002 // Return a load from the stack slot.
11003 if (StackSlot.getNode() != 0)
11004 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11005 MachinePointerInfo(),
11006 false, false, false, 0));
11008 Results.push_back(FIST);
11012 case ISD::READCYCLECOUNTER: {
11013 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11014 SDValue TheChain = N->getOperand(0);
11015 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11016 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11018 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11020 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11021 SDValue Ops[] = { eax, edx };
11022 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11023 Results.push_back(edx.getValue(1));
11026 case ISD::ATOMIC_CMP_SWAP: {
11027 EVT T = N->getValueType(0);
11028 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11029 bool Regs64bit = T == MVT::i128;
11030 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11031 SDValue cpInL, cpInH;
11032 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11033 DAG.getConstant(0, HalfT));
11034 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11035 DAG.getConstant(1, HalfT));
11036 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11037 Regs64bit ? X86::RAX : X86::EAX,
11039 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11040 Regs64bit ? X86::RDX : X86::EDX,
11041 cpInH, cpInL.getValue(1));
11042 SDValue swapInL, swapInH;
11043 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11044 DAG.getConstant(0, HalfT));
11045 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11046 DAG.getConstant(1, HalfT));
11047 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11048 Regs64bit ? X86::RBX : X86::EBX,
11049 swapInL, cpInH.getValue(1));
11050 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11051 Regs64bit ? X86::RCX : X86::ECX,
11052 swapInH, swapInL.getValue(1));
11053 SDValue Ops[] = { swapInH.getValue(0),
11055 swapInH.getValue(1) };
11056 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11057 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11058 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11059 X86ISD::LCMPXCHG8_DAG;
11060 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11062 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11063 Regs64bit ? X86::RAX : X86::EAX,
11064 HalfT, Result.getValue(1));
11065 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11066 Regs64bit ? X86::RDX : X86::EDX,
11067 HalfT, cpOutL.getValue(2));
11068 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11069 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11070 Results.push_back(cpOutH.getValue(1));
11073 case ISD::ATOMIC_LOAD_ADD:
11074 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11076 case ISD::ATOMIC_LOAD_AND:
11077 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11079 case ISD::ATOMIC_LOAD_NAND:
11080 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11082 case ISD::ATOMIC_LOAD_OR:
11083 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11085 case ISD::ATOMIC_LOAD_SUB:
11086 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11088 case ISD::ATOMIC_LOAD_XOR:
11089 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11091 case ISD::ATOMIC_SWAP:
11092 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11094 case ISD::ATOMIC_LOAD:
11095 ReplaceATOMIC_LOAD(N, Results, DAG);
11099 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11101 default: return NULL;
11102 case X86ISD::BSF: return "X86ISD::BSF";
11103 case X86ISD::BSR: return "X86ISD::BSR";
11104 case X86ISD::SHLD: return "X86ISD::SHLD";
11105 case X86ISD::SHRD: return "X86ISD::SHRD";
11106 case X86ISD::FAND: return "X86ISD::FAND";
11107 case X86ISD::FOR: return "X86ISD::FOR";
11108 case X86ISD::FXOR: return "X86ISD::FXOR";
11109 case X86ISD::FSRL: return "X86ISD::FSRL";
11110 case X86ISD::FILD: return "X86ISD::FILD";
11111 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11112 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11113 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11114 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11115 case X86ISD::FLD: return "X86ISD::FLD";
11116 case X86ISD::FST: return "X86ISD::FST";
11117 case X86ISD::CALL: return "X86ISD::CALL";
11118 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11119 case X86ISD::BT: return "X86ISD::BT";
11120 case X86ISD::CMP: return "X86ISD::CMP";
11121 case X86ISD::COMI: return "X86ISD::COMI";
11122 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11123 case X86ISD::SETCC: return "X86ISD::SETCC";
11124 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11125 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11126 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11127 case X86ISD::CMOV: return "X86ISD::CMOV";
11128 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11129 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11130 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11131 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11132 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11133 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11134 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11135 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11136 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11137 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11138 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11139 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11140 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11141 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11142 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11143 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11144 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11145 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11146 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11147 case X86ISD::HADD: return "X86ISD::HADD";
11148 case X86ISD::HSUB: return "X86ISD::HSUB";
11149 case X86ISD::FHADD: return "X86ISD::FHADD";
11150 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11151 case X86ISD::FMAX: return "X86ISD::FMAX";
11152 case X86ISD::FMIN: return "X86ISD::FMIN";
11153 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11154 case X86ISD::FRCP: return "X86ISD::FRCP";
11155 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11156 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11157 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11158 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11159 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11160 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11161 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11162 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11163 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11164 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11165 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11166 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11167 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11168 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11169 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11170 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11171 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11172 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11173 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11174 case X86ISD::VSHL: return "X86ISD::VSHL";
11175 case X86ISD::VSRL: return "X86ISD::VSRL";
11176 case X86ISD::VSRA: return "X86ISD::VSRA";
11177 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11178 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11179 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11180 case X86ISD::CMPP: return "X86ISD::CMPP";
11181 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11182 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11183 case X86ISD::ADD: return "X86ISD::ADD";
11184 case X86ISD::SUB: return "X86ISD::SUB";
11185 case X86ISD::ADC: return "X86ISD::ADC";
11186 case X86ISD::SBB: return "X86ISD::SBB";
11187 case X86ISD::SMUL: return "X86ISD::SMUL";
11188 case X86ISD::UMUL: return "X86ISD::UMUL";
11189 case X86ISD::INC: return "X86ISD::INC";
11190 case X86ISD::DEC: return "X86ISD::DEC";
11191 case X86ISD::OR: return "X86ISD::OR";
11192 case X86ISD::XOR: return "X86ISD::XOR";
11193 case X86ISD::AND: return "X86ISD::AND";
11194 case X86ISD::ANDN: return "X86ISD::ANDN";
11195 case X86ISD::BLSI: return "X86ISD::BLSI";
11196 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11197 case X86ISD::BLSR: return "X86ISD::BLSR";
11198 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11199 case X86ISD::PTEST: return "X86ISD::PTEST";
11200 case X86ISD::TESTP: return "X86ISD::TESTP";
11201 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11202 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11203 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11204 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11205 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11206 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11207 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11208 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11209 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11210 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11211 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11212 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11213 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11214 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11215 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11216 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11217 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11218 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11219 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11220 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11221 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11222 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11223 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11224 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11225 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11226 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11227 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11228 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11229 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11230 case X86ISD::SAHF: return "X86ISD::SAHF";
11234 // isLegalAddressingMode - Return true if the addressing mode represented
11235 // by AM is legal for this target, for a load/store of the specified type.
11236 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11238 // X86 supports extremely general addressing modes.
11239 CodeModel::Model M = getTargetMachine().getCodeModel();
11240 Reloc::Model R = getTargetMachine().getRelocationModel();
11242 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11243 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11248 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11250 // If a reference to this global requires an extra load, we can't fold it.
11251 if (isGlobalStubReference(GVFlags))
11254 // If BaseGV requires a register for the PIC base, we cannot also have a
11255 // BaseReg specified.
11256 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11259 // If lower 4G is not available, then we must use rip-relative addressing.
11260 if ((M != CodeModel::Small || R != Reloc::Static) &&
11261 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11265 switch (AM.Scale) {
11271 // These scales always work.
11276 // These scales are formed with basereg+scalereg. Only accept if there is
11281 default: // Other stuff never works.
11289 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11290 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11292 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11293 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11294 if (NumBits1 <= NumBits2)
11299 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11300 if (!VT1.isInteger() || !VT2.isInteger())
11302 unsigned NumBits1 = VT1.getSizeInBits();
11303 unsigned NumBits2 = VT2.getSizeInBits();
11304 if (NumBits1 <= NumBits2)
11309 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11310 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11311 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11314 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11315 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11316 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11319 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11320 // i16 instructions are longer (0x66 prefix) and potentially slower.
11321 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11324 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11325 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11326 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11327 /// are assumed to be legal.
11329 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11331 // Very little shuffling can be done for 64-bit vectors right now.
11332 if (VT.getSizeInBits() == 64)
11335 // FIXME: pshufb, blends, shifts.
11336 return (VT.getVectorNumElements() == 2 ||
11337 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11338 isMOVLMask(M, VT) ||
11339 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11340 isPSHUFDMask(M, VT) ||
11341 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11342 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11343 isPALIGNRMask(M, VT, Subtarget) ||
11344 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11345 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11346 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11347 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11351 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11353 unsigned NumElts = VT.getVectorNumElements();
11354 // FIXME: This collection of masks seems suspect.
11357 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11358 return (isMOVLMask(Mask, VT) ||
11359 isCommutedMOVLMask(Mask, VT, true) ||
11360 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11361 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11366 //===----------------------------------------------------------------------===//
11367 // X86 Scheduler Hooks
11368 //===----------------------------------------------------------------------===//
11370 // private utility function
11371 MachineBasicBlock *
11372 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11373 MachineBasicBlock *MBB,
11380 const TargetRegisterClass *RC,
11381 bool Invert) const {
11382 // For the atomic bitwise operator, we generate
11385 // ld t1 = [bitinstr.addr]
11386 // op t2 = t1, [bitinstr.val]
11387 // not t3 = t2 (if Invert)
11389 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11391 // fallthrough -->nextMBB
11392 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11393 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11394 MachineFunction::iterator MBBIter = MBB;
11397 /// First build the CFG
11398 MachineFunction *F = MBB->getParent();
11399 MachineBasicBlock *thisMBB = MBB;
11400 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11401 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11402 F->insert(MBBIter, newMBB);
11403 F->insert(MBBIter, nextMBB);
11405 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11406 nextMBB->splice(nextMBB->begin(), thisMBB,
11407 llvm::next(MachineBasicBlock::iterator(bInstr)),
11409 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11411 // Update thisMBB to fall through to newMBB
11412 thisMBB->addSuccessor(newMBB);
11414 // newMBB jumps to itself and fall through to nextMBB
11415 newMBB->addSuccessor(nextMBB);
11416 newMBB->addSuccessor(newMBB);
11418 // Insert instructions into newMBB based on incoming instruction
11419 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11420 "unexpected number of operands");
11421 DebugLoc dl = bInstr->getDebugLoc();
11422 MachineOperand& destOper = bInstr->getOperand(0);
11423 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11424 int numArgs = bInstr->getNumOperands() - 1;
11425 for (int i=0; i < numArgs; ++i)
11426 argOpers[i] = &bInstr->getOperand(i+1);
11428 // x86 address has 4 operands: base, index, scale, and displacement
11429 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11430 int valArgIndx = lastAddrIndx + 1;
11432 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11433 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11434 for (int i=0; i <= lastAddrIndx; ++i)
11435 (*MIB).addOperand(*argOpers[i]);
11437 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11438 assert((argOpers[valArgIndx]->isReg() ||
11439 argOpers[valArgIndx]->isImm()) &&
11440 "invalid operand");
11441 if (argOpers[valArgIndx]->isReg())
11442 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11444 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11446 (*MIB).addOperand(*argOpers[valArgIndx]);
11448 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11450 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11455 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11458 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11459 for (int i=0; i <= lastAddrIndx; ++i)
11460 (*MIB).addOperand(*argOpers[i]);
11462 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11463 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11464 bInstr->memoperands_end());
11466 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11467 MIB.addReg(EAXreg);
11470 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11472 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11476 // private utility function: 64 bit atomics on 32 bit host.
11477 MachineBasicBlock *
11478 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11479 MachineBasicBlock *MBB,
11484 bool Invert) const {
11485 // For the atomic bitwise operator, we generate
11486 // thisMBB (instructions are in pairs, except cmpxchg8b)
11487 // ld t1,t2 = [bitinstr.addr]
11489 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11490 // op t5, t6 <- out1, out2, [bitinstr.val]
11491 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11492 // neg t7, t8 < t5, t6 (if Invert)
11493 // mov ECX, EBX <- t5, t6
11494 // mov EAX, EDX <- t1, t2
11495 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11496 // mov t3, t4 <- EAX, EDX
11498 // result in out1, out2
11499 // fallthrough -->nextMBB
11501 const TargetRegisterClass *RC = &X86::GR32RegClass;
11502 const unsigned LoadOpc = X86::MOV32rm;
11503 const unsigned NotOpc = X86::NOT32r;
11504 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11505 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11506 MachineFunction::iterator MBBIter = MBB;
11509 /// First build the CFG
11510 MachineFunction *F = MBB->getParent();
11511 MachineBasicBlock *thisMBB = MBB;
11512 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11513 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11514 F->insert(MBBIter, newMBB);
11515 F->insert(MBBIter, nextMBB);
11517 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11518 nextMBB->splice(nextMBB->begin(), thisMBB,
11519 llvm::next(MachineBasicBlock::iterator(bInstr)),
11521 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11523 // Update thisMBB to fall through to newMBB
11524 thisMBB->addSuccessor(newMBB);
11526 // newMBB jumps to itself and fall through to nextMBB
11527 newMBB->addSuccessor(nextMBB);
11528 newMBB->addSuccessor(newMBB);
11530 DebugLoc dl = bInstr->getDebugLoc();
11531 // Insert instructions into newMBB based on incoming instruction
11532 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11533 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11534 "unexpected number of operands");
11535 MachineOperand& dest1Oper = bInstr->getOperand(0);
11536 MachineOperand& dest2Oper = bInstr->getOperand(1);
11537 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11538 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11539 argOpers[i] = &bInstr->getOperand(i+2);
11541 // We use some of the operands multiple times, so conservatively just
11542 // clear any kill flags that might be present.
11543 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11544 argOpers[i]->setIsKill(false);
11547 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11548 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11550 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11551 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11552 for (int i=0; i <= lastAddrIndx; ++i)
11553 (*MIB).addOperand(*argOpers[i]);
11554 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11555 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11556 // add 4 to displacement.
11557 for (int i=0; i <= lastAddrIndx-2; ++i)
11558 (*MIB).addOperand(*argOpers[i]);
11559 MachineOperand newOp3 = *(argOpers[3]);
11560 if (newOp3.isImm())
11561 newOp3.setImm(newOp3.getImm()+4);
11563 newOp3.setOffset(newOp3.getOffset()+4);
11564 (*MIB).addOperand(newOp3);
11565 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11567 // t3/4 are defined later, at the bottom of the loop
11568 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11569 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11570 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11571 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11572 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11573 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11575 // The subsequent operations should be using the destination registers of
11576 // the PHI instructions.
11577 t1 = dest1Oper.getReg();
11578 t2 = dest2Oper.getReg();
11580 int valArgIndx = lastAddrIndx + 1;
11581 assert((argOpers[valArgIndx]->isReg() ||
11582 argOpers[valArgIndx]->isImm()) &&
11583 "invalid operand");
11584 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11585 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11586 if (argOpers[valArgIndx]->isReg())
11587 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11589 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11590 if (regOpcL != X86::MOV32rr)
11592 (*MIB).addOperand(*argOpers[valArgIndx]);
11593 assert(argOpers[valArgIndx + 1]->isReg() ==
11594 argOpers[valArgIndx]->isReg());
11595 assert(argOpers[valArgIndx + 1]->isImm() ==
11596 argOpers[valArgIndx]->isImm());
11597 if (argOpers[valArgIndx + 1]->isReg())
11598 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11600 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11601 if (regOpcH != X86::MOV32rr)
11603 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11607 t7 = F->getRegInfo().createVirtualRegister(RC);
11608 t8 = F->getRegInfo().createVirtualRegister(RC);
11609 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11610 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11616 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11618 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11621 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11623 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11626 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11627 for (int i=0; i <= lastAddrIndx; ++i)
11628 (*MIB).addOperand(*argOpers[i]);
11630 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11631 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11632 bInstr->memoperands_end());
11634 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11635 MIB.addReg(X86::EAX);
11636 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11637 MIB.addReg(X86::EDX);
11640 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11642 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11646 // private utility function
11647 MachineBasicBlock *
11648 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11649 MachineBasicBlock *MBB,
11650 unsigned cmovOpc) const {
11651 // For the atomic min/max operator, we generate
11654 // ld t1 = [min/max.addr]
11655 // mov t2 = [min/max.val]
11657 // cmov[cond] t2 = t1
11659 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11661 // fallthrough -->nextMBB
11663 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11664 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11665 MachineFunction::iterator MBBIter = MBB;
11668 /// First build the CFG
11669 MachineFunction *F = MBB->getParent();
11670 MachineBasicBlock *thisMBB = MBB;
11671 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11672 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11673 F->insert(MBBIter, newMBB);
11674 F->insert(MBBIter, nextMBB);
11676 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11677 nextMBB->splice(nextMBB->begin(), thisMBB,
11678 llvm::next(MachineBasicBlock::iterator(mInstr)),
11680 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11682 // Update thisMBB to fall through to newMBB
11683 thisMBB->addSuccessor(newMBB);
11685 // newMBB jumps to newMBB and fall through to nextMBB
11686 newMBB->addSuccessor(nextMBB);
11687 newMBB->addSuccessor(newMBB);
11689 DebugLoc dl = mInstr->getDebugLoc();
11690 // Insert instructions into newMBB based on incoming instruction
11691 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11692 "unexpected number of operands");
11693 MachineOperand& destOper = mInstr->getOperand(0);
11694 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11695 int numArgs = mInstr->getNumOperands() - 1;
11696 for (int i=0; i < numArgs; ++i)
11697 argOpers[i] = &mInstr->getOperand(i+1);
11699 // x86 address has 4 operands: base, index, scale, and displacement
11700 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11701 int valArgIndx = lastAddrIndx + 1;
11703 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11704 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11705 for (int i=0; i <= lastAddrIndx; ++i)
11706 (*MIB).addOperand(*argOpers[i]);
11708 // We only support register and immediate values
11709 assert((argOpers[valArgIndx]->isReg() ||
11710 argOpers[valArgIndx]->isImm()) &&
11711 "invalid operand");
11713 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11714 if (argOpers[valArgIndx]->isReg())
11715 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11717 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11718 (*MIB).addOperand(*argOpers[valArgIndx]);
11720 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11723 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11728 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11729 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11733 // Cmp and exchange if none has modified the memory location
11734 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11735 for (int i=0; i <= lastAddrIndx; ++i)
11736 (*MIB).addOperand(*argOpers[i]);
11738 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11739 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11740 mInstr->memoperands_end());
11742 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11743 MIB.addReg(X86::EAX);
11746 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11748 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11752 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11753 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11754 // in the .td file.
11755 MachineBasicBlock *
11756 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11757 unsigned numArgs, bool memArg) const {
11758 assert(Subtarget->hasSSE42() &&
11759 "Target must have SSE4.2 or AVX features enabled");
11761 DebugLoc dl = MI->getDebugLoc();
11762 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11764 if (!Subtarget->hasAVX()) {
11766 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11768 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11771 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11773 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11776 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11777 for (unsigned i = 0; i < numArgs; ++i) {
11778 MachineOperand &Op = MI->getOperand(i+1);
11779 if (!(Op.isReg() && Op.isImplicit()))
11780 MIB.addOperand(Op);
11782 BuildMI(*BB, MI, dl,
11783 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11784 MI->getOperand(0).getReg())
11785 .addReg(X86::XMM0);
11787 MI->eraseFromParent();
11791 MachineBasicBlock *
11792 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11793 DebugLoc dl = MI->getDebugLoc();
11794 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11796 // Address into RAX/EAX, other two args into ECX, EDX.
11797 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11798 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11799 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11800 for (int i = 0; i < X86::AddrNumOperands; ++i)
11801 MIB.addOperand(MI->getOperand(i));
11803 unsigned ValOps = X86::AddrNumOperands;
11804 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11805 .addReg(MI->getOperand(ValOps).getReg());
11806 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11807 .addReg(MI->getOperand(ValOps+1).getReg());
11809 // The instruction doesn't actually take any operands though.
11810 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11812 MI->eraseFromParent(); // The pseudo is gone now.
11816 MachineBasicBlock *
11817 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11818 DebugLoc dl = MI->getDebugLoc();
11819 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11821 // First arg in ECX, the second in EAX.
11822 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11823 .addReg(MI->getOperand(0).getReg());
11824 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11825 .addReg(MI->getOperand(1).getReg());
11827 // The instruction doesn't actually take any operands though.
11828 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11830 MI->eraseFromParent(); // The pseudo is gone now.
11834 MachineBasicBlock *
11835 X86TargetLowering::EmitVAARG64WithCustomInserter(
11837 MachineBasicBlock *MBB) const {
11838 // Emit va_arg instruction on X86-64.
11840 // Operands to this pseudo-instruction:
11841 // 0 ) Output : destination address (reg)
11842 // 1-5) Input : va_list address (addr, i64mem)
11843 // 6 ) ArgSize : Size (in bytes) of vararg type
11844 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11845 // 8 ) Align : Alignment of type
11846 // 9 ) EFLAGS (implicit-def)
11848 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11849 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11851 unsigned DestReg = MI->getOperand(0).getReg();
11852 MachineOperand &Base = MI->getOperand(1);
11853 MachineOperand &Scale = MI->getOperand(2);
11854 MachineOperand &Index = MI->getOperand(3);
11855 MachineOperand &Disp = MI->getOperand(4);
11856 MachineOperand &Segment = MI->getOperand(5);
11857 unsigned ArgSize = MI->getOperand(6).getImm();
11858 unsigned ArgMode = MI->getOperand(7).getImm();
11859 unsigned Align = MI->getOperand(8).getImm();
11861 // Memory Reference
11862 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11863 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11864 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11866 // Machine Information
11867 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11868 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11869 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11870 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11871 DebugLoc DL = MI->getDebugLoc();
11873 // struct va_list {
11876 // i64 overflow_area (address)
11877 // i64 reg_save_area (address)
11879 // sizeof(va_list) = 24
11880 // alignment(va_list) = 8
11882 unsigned TotalNumIntRegs = 6;
11883 unsigned TotalNumXMMRegs = 8;
11884 bool UseGPOffset = (ArgMode == 1);
11885 bool UseFPOffset = (ArgMode == 2);
11886 unsigned MaxOffset = TotalNumIntRegs * 8 +
11887 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11889 /* Align ArgSize to a multiple of 8 */
11890 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11891 bool NeedsAlign = (Align > 8);
11893 MachineBasicBlock *thisMBB = MBB;
11894 MachineBasicBlock *overflowMBB;
11895 MachineBasicBlock *offsetMBB;
11896 MachineBasicBlock *endMBB;
11898 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11899 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11900 unsigned OffsetReg = 0;
11902 if (!UseGPOffset && !UseFPOffset) {
11903 // If we only pull from the overflow region, we don't create a branch.
11904 // We don't need to alter control flow.
11905 OffsetDestReg = 0; // unused
11906 OverflowDestReg = DestReg;
11909 overflowMBB = thisMBB;
11912 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11913 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11914 // If not, pull from overflow_area. (branch to overflowMBB)
11919 // offsetMBB overflowMBB
11924 // Registers for the PHI in endMBB
11925 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11926 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11928 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11929 MachineFunction *MF = MBB->getParent();
11930 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11931 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11932 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11934 MachineFunction::iterator MBBIter = MBB;
11937 // Insert the new basic blocks
11938 MF->insert(MBBIter, offsetMBB);
11939 MF->insert(MBBIter, overflowMBB);
11940 MF->insert(MBBIter, endMBB);
11942 // Transfer the remainder of MBB and its successor edges to endMBB.
11943 endMBB->splice(endMBB->begin(), thisMBB,
11944 llvm::next(MachineBasicBlock::iterator(MI)),
11946 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11948 // Make offsetMBB and overflowMBB successors of thisMBB
11949 thisMBB->addSuccessor(offsetMBB);
11950 thisMBB->addSuccessor(overflowMBB);
11952 // endMBB is a successor of both offsetMBB and overflowMBB
11953 offsetMBB->addSuccessor(endMBB);
11954 overflowMBB->addSuccessor(endMBB);
11956 // Load the offset value into a register
11957 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11958 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11962 .addDisp(Disp, UseFPOffset ? 4 : 0)
11963 .addOperand(Segment)
11964 .setMemRefs(MMOBegin, MMOEnd);
11966 // Check if there is enough room left to pull this argument.
11967 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11969 .addImm(MaxOffset + 8 - ArgSizeA8);
11971 // Branch to "overflowMBB" if offset >= max
11972 // Fall through to "offsetMBB" otherwise
11973 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11974 .addMBB(overflowMBB);
11977 // In offsetMBB, emit code to use the reg_save_area.
11979 assert(OffsetReg != 0);
11981 // Read the reg_save_area address.
11982 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11983 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11988 .addOperand(Segment)
11989 .setMemRefs(MMOBegin, MMOEnd);
11991 // Zero-extend the offset
11992 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11993 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11996 .addImm(X86::sub_32bit);
11998 // Add the offset to the reg_save_area to get the final address.
11999 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12000 .addReg(OffsetReg64)
12001 .addReg(RegSaveReg);
12003 // Compute the offset for the next argument
12004 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12005 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12007 .addImm(UseFPOffset ? 16 : 8);
12009 // Store it back into the va_list.
12010 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12014 .addDisp(Disp, UseFPOffset ? 4 : 0)
12015 .addOperand(Segment)
12016 .addReg(NextOffsetReg)
12017 .setMemRefs(MMOBegin, MMOEnd);
12020 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12025 // Emit code to use overflow area
12028 // Load the overflow_area address into a register.
12029 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12030 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12035 .addOperand(Segment)
12036 .setMemRefs(MMOBegin, MMOEnd);
12038 // If we need to align it, do so. Otherwise, just copy the address
12039 // to OverflowDestReg.
12041 // Align the overflow address
12042 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12043 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12045 // aligned_addr = (addr + (align-1)) & ~(align-1)
12046 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12047 .addReg(OverflowAddrReg)
12050 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12052 .addImm(~(uint64_t)(Align-1));
12054 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12055 .addReg(OverflowAddrReg);
12058 // Compute the next overflow address after this argument.
12059 // (the overflow address should be kept 8-byte aligned)
12060 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12061 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12062 .addReg(OverflowDestReg)
12063 .addImm(ArgSizeA8);
12065 // Store the new overflow address.
12066 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12071 .addOperand(Segment)
12072 .addReg(NextAddrReg)
12073 .setMemRefs(MMOBegin, MMOEnd);
12075 // If we branched, emit the PHI to the front of endMBB.
12077 BuildMI(*endMBB, endMBB->begin(), DL,
12078 TII->get(X86::PHI), DestReg)
12079 .addReg(OffsetDestReg).addMBB(offsetMBB)
12080 .addReg(OverflowDestReg).addMBB(overflowMBB);
12083 // Erase the pseudo instruction
12084 MI->eraseFromParent();
12089 MachineBasicBlock *
12090 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12092 MachineBasicBlock *MBB) const {
12093 // Emit code to save XMM registers to the stack. The ABI says that the
12094 // number of registers to save is given in %al, so it's theoretically
12095 // possible to do an indirect jump trick to avoid saving all of them,
12096 // however this code takes a simpler approach and just executes all
12097 // of the stores if %al is non-zero. It's less code, and it's probably
12098 // easier on the hardware branch predictor, and stores aren't all that
12099 // expensive anyway.
12101 // Create the new basic blocks. One block contains all the XMM stores,
12102 // and one block is the final destination regardless of whether any
12103 // stores were performed.
12104 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12105 MachineFunction *F = MBB->getParent();
12106 MachineFunction::iterator MBBIter = MBB;
12108 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12109 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12110 F->insert(MBBIter, XMMSaveMBB);
12111 F->insert(MBBIter, EndMBB);
12113 // Transfer the remainder of MBB and its successor edges to EndMBB.
12114 EndMBB->splice(EndMBB->begin(), MBB,
12115 llvm::next(MachineBasicBlock::iterator(MI)),
12117 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12119 // The original block will now fall through to the XMM save block.
12120 MBB->addSuccessor(XMMSaveMBB);
12121 // The XMMSaveMBB will fall through to the end block.
12122 XMMSaveMBB->addSuccessor(EndMBB);
12124 // Now add the instructions.
12125 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12126 DebugLoc DL = MI->getDebugLoc();
12128 unsigned CountReg = MI->getOperand(0).getReg();
12129 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12130 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12132 if (!Subtarget->isTargetWin64()) {
12133 // If %al is 0, branch around the XMM save block.
12134 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12135 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12136 MBB->addSuccessor(EndMBB);
12139 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12140 // In the XMM save block, save all the XMM argument registers.
12141 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12142 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12143 MachineMemOperand *MMO =
12144 F->getMachineMemOperand(
12145 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12146 MachineMemOperand::MOStore,
12147 /*Size=*/16, /*Align=*/16);
12148 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12149 .addFrameIndex(RegSaveFrameIndex)
12150 .addImm(/*Scale=*/1)
12151 .addReg(/*IndexReg=*/0)
12152 .addImm(/*Disp=*/Offset)
12153 .addReg(/*Segment=*/0)
12154 .addReg(MI->getOperand(i).getReg())
12155 .addMemOperand(MMO);
12158 MI->eraseFromParent(); // The pseudo instruction is gone now.
12163 // The EFLAGS operand of SelectItr might be missing a kill marker
12164 // because there were multiple uses of EFLAGS, and ISel didn't know
12165 // which to mark. Figure out whether SelectItr should have had a
12166 // kill marker, and set it if it should. Returns the correct kill
12168 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12169 MachineBasicBlock* BB,
12170 const TargetRegisterInfo* TRI) {
12171 // Scan forward through BB for a use/def of EFLAGS.
12172 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12173 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12174 const MachineInstr& mi = *miI;
12175 if (mi.readsRegister(X86::EFLAGS))
12177 if (mi.definesRegister(X86::EFLAGS))
12178 break; // Should have kill-flag - update below.
12181 // If we hit the end of the block, check whether EFLAGS is live into a
12183 if (miI == BB->end()) {
12184 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12185 sEnd = BB->succ_end();
12186 sItr != sEnd; ++sItr) {
12187 MachineBasicBlock* succ = *sItr;
12188 if (succ->isLiveIn(X86::EFLAGS))
12193 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12194 // out. SelectMI should have a kill flag on EFLAGS.
12195 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12199 MachineBasicBlock *
12200 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12201 MachineBasicBlock *BB) const {
12202 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12203 DebugLoc DL = MI->getDebugLoc();
12205 // To "insert" a SELECT_CC instruction, we actually have to insert the
12206 // diamond control-flow pattern. The incoming instruction knows the
12207 // destination vreg to set, the condition code register to branch on, the
12208 // true/false values to select between, and a branch opcode to use.
12209 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12210 MachineFunction::iterator It = BB;
12216 // cmpTY ccX, r1, r2
12218 // fallthrough --> copy0MBB
12219 MachineBasicBlock *thisMBB = BB;
12220 MachineFunction *F = BB->getParent();
12221 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12222 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12223 F->insert(It, copy0MBB);
12224 F->insert(It, sinkMBB);
12226 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12227 // live into the sink and copy blocks.
12228 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12229 if (!MI->killsRegister(X86::EFLAGS) &&
12230 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12231 copy0MBB->addLiveIn(X86::EFLAGS);
12232 sinkMBB->addLiveIn(X86::EFLAGS);
12235 // Transfer the remainder of BB and its successor edges to sinkMBB.
12236 sinkMBB->splice(sinkMBB->begin(), BB,
12237 llvm::next(MachineBasicBlock::iterator(MI)),
12239 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12241 // Add the true and fallthrough blocks as its successors.
12242 BB->addSuccessor(copy0MBB);
12243 BB->addSuccessor(sinkMBB);
12245 // Create the conditional branch instruction.
12247 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12248 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12251 // %FalseValue = ...
12252 // # fallthrough to sinkMBB
12253 copy0MBB->addSuccessor(sinkMBB);
12256 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12258 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12259 TII->get(X86::PHI), MI->getOperand(0).getReg())
12260 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12261 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12263 MI->eraseFromParent(); // The pseudo instruction is gone now.
12267 MachineBasicBlock *
12268 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12269 bool Is64Bit) const {
12270 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12271 DebugLoc DL = MI->getDebugLoc();
12272 MachineFunction *MF = BB->getParent();
12273 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12275 assert(getTargetMachine().Options.EnableSegmentedStacks);
12277 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12278 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12281 // ... [Till the alloca]
12282 // If stacklet is not large enough, jump to mallocMBB
12285 // Allocate by subtracting from RSP
12286 // Jump to continueMBB
12289 // Allocate by call to runtime
12293 // [rest of original BB]
12296 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12297 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12298 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12300 MachineRegisterInfo &MRI = MF->getRegInfo();
12301 const TargetRegisterClass *AddrRegClass =
12302 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12304 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12305 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12306 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12307 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12308 sizeVReg = MI->getOperand(1).getReg(),
12309 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12311 MachineFunction::iterator MBBIter = BB;
12314 MF->insert(MBBIter, bumpMBB);
12315 MF->insert(MBBIter, mallocMBB);
12316 MF->insert(MBBIter, continueMBB);
12318 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12319 (MachineBasicBlock::iterator(MI)), BB->end());
12320 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12322 // Add code to the main basic block to check if the stack limit has been hit,
12323 // and if so, jump to mallocMBB otherwise to bumpMBB.
12324 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12325 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12326 .addReg(tmpSPVReg).addReg(sizeVReg);
12327 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12328 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12329 .addReg(SPLimitVReg);
12330 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12332 // bumpMBB simply decreases the stack pointer, since we know the current
12333 // stacklet has enough space.
12334 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12335 .addReg(SPLimitVReg);
12336 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12337 .addReg(SPLimitVReg);
12338 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12340 // Calls into a routine in libgcc to allocate more space from the heap.
12341 const uint32_t *RegMask =
12342 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12344 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12346 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12347 .addExternalSymbol("__morestack_allocate_stack_space")
12348 .addRegMask(RegMask)
12349 .addReg(X86::RDI, RegState::Implicit)
12350 .addReg(X86::RAX, RegState::ImplicitDefine);
12352 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12354 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12355 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12356 .addExternalSymbol("__morestack_allocate_stack_space")
12357 .addRegMask(RegMask)
12358 .addReg(X86::EAX, RegState::ImplicitDefine);
12362 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12365 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12366 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12367 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12369 // Set up the CFG correctly.
12370 BB->addSuccessor(bumpMBB);
12371 BB->addSuccessor(mallocMBB);
12372 mallocMBB->addSuccessor(continueMBB);
12373 bumpMBB->addSuccessor(continueMBB);
12375 // Take care of the PHI nodes.
12376 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12377 MI->getOperand(0).getReg())
12378 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12379 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12381 // Delete the original pseudo instruction.
12382 MI->eraseFromParent();
12385 return continueMBB;
12388 MachineBasicBlock *
12389 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12390 MachineBasicBlock *BB) const {
12391 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12392 DebugLoc DL = MI->getDebugLoc();
12394 assert(!Subtarget->isTargetEnvMacho());
12396 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12397 // non-trivial part is impdef of ESP.
12399 if (Subtarget->isTargetWin64()) {
12400 if (Subtarget->isTargetCygMing()) {
12401 // ___chkstk(Mingw64):
12402 // Clobbers R10, R11, RAX and EFLAGS.
12404 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12405 .addExternalSymbol("___chkstk")
12406 .addReg(X86::RAX, RegState::Implicit)
12407 .addReg(X86::RSP, RegState::Implicit)
12408 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12409 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12410 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12412 // __chkstk(MSVCRT): does not update stack pointer.
12413 // Clobbers R10, R11 and EFLAGS.
12414 // FIXME: RAX(allocated size) might be reused and not killed.
12415 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12416 .addExternalSymbol("__chkstk")
12417 .addReg(X86::RAX, RegState::Implicit)
12418 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12419 // RAX has the offset to subtracted from RSP.
12420 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12425 const char *StackProbeSymbol =
12426 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12428 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12429 .addExternalSymbol(StackProbeSymbol)
12430 .addReg(X86::EAX, RegState::Implicit)
12431 .addReg(X86::ESP, RegState::Implicit)
12432 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12433 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12434 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12437 MI->eraseFromParent(); // The pseudo instruction is gone now.
12441 MachineBasicBlock *
12442 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12443 MachineBasicBlock *BB) const {
12444 // This is pretty easy. We're taking the value that we received from
12445 // our load from the relocation, sticking it in either RDI (x86-64)
12446 // or EAX and doing an indirect call. The return value will then
12447 // be in the normal return register.
12448 const X86InstrInfo *TII
12449 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12450 DebugLoc DL = MI->getDebugLoc();
12451 MachineFunction *F = BB->getParent();
12453 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12454 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12456 // Get a register mask for the lowered call.
12457 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12458 // proper register mask.
12459 const uint32_t *RegMask =
12460 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12461 if (Subtarget->is64Bit()) {
12462 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12463 TII->get(X86::MOV64rm), X86::RDI)
12465 .addImm(0).addReg(0)
12466 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12467 MI->getOperand(3).getTargetFlags())
12469 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12470 addDirectMem(MIB, X86::RDI);
12471 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12472 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12473 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12474 TII->get(X86::MOV32rm), X86::EAX)
12476 .addImm(0).addReg(0)
12477 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12478 MI->getOperand(3).getTargetFlags())
12480 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12481 addDirectMem(MIB, X86::EAX);
12482 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12484 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12485 TII->get(X86::MOV32rm), X86::EAX)
12486 .addReg(TII->getGlobalBaseReg(F))
12487 .addImm(0).addReg(0)
12488 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12489 MI->getOperand(3).getTargetFlags())
12491 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12492 addDirectMem(MIB, X86::EAX);
12493 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12496 MI->eraseFromParent(); // The pseudo instruction is gone now.
12500 MachineBasicBlock *
12501 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12502 MachineBasicBlock *BB) const {
12503 switch (MI->getOpcode()) {
12504 default: llvm_unreachable("Unexpected instr type to insert");
12505 case X86::TAILJMPd64:
12506 case X86::TAILJMPr64:
12507 case X86::TAILJMPm64:
12508 llvm_unreachable("TAILJMP64 would not be touched here.");
12509 case X86::TCRETURNdi64:
12510 case X86::TCRETURNri64:
12511 case X86::TCRETURNmi64:
12513 case X86::WIN_ALLOCA:
12514 return EmitLoweredWinAlloca(MI, BB);
12515 case X86::SEG_ALLOCA_32:
12516 return EmitLoweredSegAlloca(MI, BB, false);
12517 case X86::SEG_ALLOCA_64:
12518 return EmitLoweredSegAlloca(MI, BB, true);
12519 case X86::TLSCall_32:
12520 case X86::TLSCall_64:
12521 return EmitLoweredTLSCall(MI, BB);
12522 case X86::CMOV_GR8:
12523 case X86::CMOV_FR32:
12524 case X86::CMOV_FR64:
12525 case X86::CMOV_V4F32:
12526 case X86::CMOV_V2F64:
12527 case X86::CMOV_V2I64:
12528 case X86::CMOV_V8F32:
12529 case X86::CMOV_V4F64:
12530 case X86::CMOV_V4I64:
12531 case X86::CMOV_GR16:
12532 case X86::CMOV_GR32:
12533 case X86::CMOV_RFP32:
12534 case X86::CMOV_RFP64:
12535 case X86::CMOV_RFP80:
12536 return EmitLoweredSelect(MI, BB);
12538 case X86::FP32_TO_INT16_IN_MEM:
12539 case X86::FP32_TO_INT32_IN_MEM:
12540 case X86::FP32_TO_INT64_IN_MEM:
12541 case X86::FP64_TO_INT16_IN_MEM:
12542 case X86::FP64_TO_INT32_IN_MEM:
12543 case X86::FP64_TO_INT64_IN_MEM:
12544 case X86::FP80_TO_INT16_IN_MEM:
12545 case X86::FP80_TO_INT32_IN_MEM:
12546 case X86::FP80_TO_INT64_IN_MEM: {
12547 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12548 DebugLoc DL = MI->getDebugLoc();
12550 // Change the floating point control register to use "round towards zero"
12551 // mode when truncating to an integer value.
12552 MachineFunction *F = BB->getParent();
12553 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12554 addFrameReference(BuildMI(*BB, MI, DL,
12555 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12557 // Load the old value of the high byte of the control word...
12559 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12560 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12563 // Set the high part to be round to zero...
12564 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12567 // Reload the modified control word now...
12568 addFrameReference(BuildMI(*BB, MI, DL,
12569 TII->get(X86::FLDCW16m)), CWFrameIdx);
12571 // Restore the memory image of control word to original value
12572 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12575 // Get the X86 opcode to use.
12577 switch (MI->getOpcode()) {
12578 default: llvm_unreachable("illegal opcode!");
12579 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12580 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12581 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12582 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12583 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12584 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12585 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12586 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12587 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12591 MachineOperand &Op = MI->getOperand(0);
12593 AM.BaseType = X86AddressMode::RegBase;
12594 AM.Base.Reg = Op.getReg();
12596 AM.BaseType = X86AddressMode::FrameIndexBase;
12597 AM.Base.FrameIndex = Op.getIndex();
12599 Op = MI->getOperand(1);
12601 AM.Scale = Op.getImm();
12602 Op = MI->getOperand(2);
12604 AM.IndexReg = Op.getImm();
12605 Op = MI->getOperand(3);
12606 if (Op.isGlobal()) {
12607 AM.GV = Op.getGlobal();
12609 AM.Disp = Op.getImm();
12611 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12612 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12614 // Reload the original control word now.
12615 addFrameReference(BuildMI(*BB, MI, DL,
12616 TII->get(X86::FLDCW16m)), CWFrameIdx);
12618 MI->eraseFromParent(); // The pseudo instruction is gone now.
12621 // String/text processing lowering.
12622 case X86::PCMPISTRM128REG:
12623 case X86::VPCMPISTRM128REG:
12624 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12625 case X86::PCMPISTRM128MEM:
12626 case X86::VPCMPISTRM128MEM:
12627 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12628 case X86::PCMPESTRM128REG:
12629 case X86::VPCMPESTRM128REG:
12630 return EmitPCMP(MI, BB, 5, false /* in mem */);
12631 case X86::PCMPESTRM128MEM:
12632 case X86::VPCMPESTRM128MEM:
12633 return EmitPCMP(MI, BB, 5, true /* in mem */);
12635 // Thread synchronization.
12637 return EmitMonitor(MI, BB);
12639 return EmitMwait(MI, BB);
12641 // Atomic Lowering.
12642 case X86::ATOMAND32:
12643 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12644 X86::AND32ri, X86::MOV32rm,
12646 X86::NOT32r, X86::EAX,
12647 &X86::GR32RegClass);
12648 case X86::ATOMOR32:
12649 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12650 X86::OR32ri, X86::MOV32rm,
12652 X86::NOT32r, X86::EAX,
12653 &X86::GR32RegClass);
12654 case X86::ATOMXOR32:
12655 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12656 X86::XOR32ri, X86::MOV32rm,
12658 X86::NOT32r, X86::EAX,
12659 &X86::GR32RegClass);
12660 case X86::ATOMNAND32:
12661 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12662 X86::AND32ri, X86::MOV32rm,
12664 X86::NOT32r, X86::EAX,
12665 &X86::GR32RegClass, true);
12666 case X86::ATOMMIN32:
12667 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12668 case X86::ATOMMAX32:
12669 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12670 case X86::ATOMUMIN32:
12671 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12672 case X86::ATOMUMAX32:
12673 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12675 case X86::ATOMAND16:
12676 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12677 X86::AND16ri, X86::MOV16rm,
12679 X86::NOT16r, X86::AX,
12680 &X86::GR16RegClass);
12681 case X86::ATOMOR16:
12682 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12683 X86::OR16ri, X86::MOV16rm,
12685 X86::NOT16r, X86::AX,
12686 &X86::GR16RegClass);
12687 case X86::ATOMXOR16:
12688 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12689 X86::XOR16ri, X86::MOV16rm,
12691 X86::NOT16r, X86::AX,
12692 &X86::GR16RegClass);
12693 case X86::ATOMNAND16:
12694 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12695 X86::AND16ri, X86::MOV16rm,
12697 X86::NOT16r, X86::AX,
12698 &X86::GR16RegClass, true);
12699 case X86::ATOMMIN16:
12700 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12701 case X86::ATOMMAX16:
12702 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12703 case X86::ATOMUMIN16:
12704 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12705 case X86::ATOMUMAX16:
12706 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12708 case X86::ATOMAND8:
12709 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12710 X86::AND8ri, X86::MOV8rm,
12712 X86::NOT8r, X86::AL,
12713 &X86::GR8RegClass);
12715 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12716 X86::OR8ri, X86::MOV8rm,
12718 X86::NOT8r, X86::AL,
12719 &X86::GR8RegClass);
12720 case X86::ATOMXOR8:
12721 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12722 X86::XOR8ri, X86::MOV8rm,
12724 X86::NOT8r, X86::AL,
12725 &X86::GR8RegClass);
12726 case X86::ATOMNAND8:
12727 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12728 X86::AND8ri, X86::MOV8rm,
12730 X86::NOT8r, X86::AL,
12731 &X86::GR8RegClass, true);
12732 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12733 // This group is for 64-bit host.
12734 case X86::ATOMAND64:
12735 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12736 X86::AND64ri32, X86::MOV64rm,
12738 X86::NOT64r, X86::RAX,
12739 &X86::GR64RegClass);
12740 case X86::ATOMOR64:
12741 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12742 X86::OR64ri32, X86::MOV64rm,
12744 X86::NOT64r, X86::RAX,
12745 &X86::GR64RegClass);
12746 case X86::ATOMXOR64:
12747 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12748 X86::XOR64ri32, X86::MOV64rm,
12750 X86::NOT64r, X86::RAX,
12751 &X86::GR64RegClass);
12752 case X86::ATOMNAND64:
12753 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12754 X86::AND64ri32, X86::MOV64rm,
12756 X86::NOT64r, X86::RAX,
12757 &X86::GR64RegClass, true);
12758 case X86::ATOMMIN64:
12759 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12760 case X86::ATOMMAX64:
12761 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12762 case X86::ATOMUMIN64:
12763 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12764 case X86::ATOMUMAX64:
12765 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12767 // This group does 64-bit operations on a 32-bit host.
12768 case X86::ATOMAND6432:
12769 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12770 X86::AND32rr, X86::AND32rr,
12771 X86::AND32ri, X86::AND32ri,
12773 case X86::ATOMOR6432:
12774 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12775 X86::OR32rr, X86::OR32rr,
12776 X86::OR32ri, X86::OR32ri,
12778 case X86::ATOMXOR6432:
12779 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12780 X86::XOR32rr, X86::XOR32rr,
12781 X86::XOR32ri, X86::XOR32ri,
12783 case X86::ATOMNAND6432:
12784 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12785 X86::AND32rr, X86::AND32rr,
12786 X86::AND32ri, X86::AND32ri,
12788 case X86::ATOMADD6432:
12789 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12790 X86::ADD32rr, X86::ADC32rr,
12791 X86::ADD32ri, X86::ADC32ri,
12793 case X86::ATOMSUB6432:
12794 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12795 X86::SUB32rr, X86::SBB32rr,
12796 X86::SUB32ri, X86::SBB32ri,
12798 case X86::ATOMSWAP6432:
12799 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12800 X86::MOV32rr, X86::MOV32rr,
12801 X86::MOV32ri, X86::MOV32ri,
12803 case X86::VASTART_SAVE_XMM_REGS:
12804 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12806 case X86::VAARG_64:
12807 return EmitVAARG64WithCustomInserter(MI, BB);
12811 //===----------------------------------------------------------------------===//
12812 // X86 Optimization Hooks
12813 //===----------------------------------------------------------------------===//
12815 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12818 const SelectionDAG &DAG,
12819 unsigned Depth) const {
12820 unsigned BitWidth = KnownZero.getBitWidth();
12821 unsigned Opc = Op.getOpcode();
12822 assert((Opc >= ISD::BUILTIN_OP_END ||
12823 Opc == ISD::INTRINSIC_WO_CHAIN ||
12824 Opc == ISD::INTRINSIC_W_CHAIN ||
12825 Opc == ISD::INTRINSIC_VOID) &&
12826 "Should use MaskedValueIsZero if you don't know whether Op"
12827 " is a target node!");
12829 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
12843 // These nodes' second result is a boolean.
12844 if (Op.getResNo() == 0)
12847 case X86ISD::SETCC:
12848 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12850 case ISD::INTRINSIC_WO_CHAIN: {
12851 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12852 unsigned NumLoBits = 0;
12855 case Intrinsic::x86_sse_movmsk_ps:
12856 case Intrinsic::x86_avx_movmsk_ps_256:
12857 case Intrinsic::x86_sse2_movmsk_pd:
12858 case Intrinsic::x86_avx_movmsk_pd_256:
12859 case Intrinsic::x86_mmx_pmovmskb:
12860 case Intrinsic::x86_sse2_pmovmskb_128:
12861 case Intrinsic::x86_avx2_pmovmskb: {
12862 // High bits of movmskp{s|d}, pmovmskb are known zero.
12864 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12865 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12866 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12867 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12868 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12869 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12870 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12871 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
12873 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12882 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12883 unsigned Depth) const {
12884 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12885 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12886 return Op.getValueType().getScalarType().getSizeInBits();
12892 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12893 /// node is a GlobalAddress + offset.
12894 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12895 const GlobalValue* &GA,
12896 int64_t &Offset) const {
12897 if (N->getOpcode() == X86ISD::Wrapper) {
12898 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12899 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12900 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12904 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12907 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12908 /// same as extracting the high 128-bit part of 256-bit vector and then
12909 /// inserting the result into the low part of a new 256-bit vector
12910 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12911 EVT VT = SVOp->getValueType(0);
12912 unsigned NumElems = VT.getVectorNumElements();
12914 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12915 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
12916 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12917 SVOp->getMaskElt(j) >= 0)
12923 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12924 /// same as extracting the low 128-bit part of 256-bit vector and then
12925 /// inserting the result into the high part of a new 256-bit vector
12926 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12927 EVT VT = SVOp->getValueType(0);
12928 unsigned NumElems = VT.getVectorNumElements();
12930 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12931 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
12932 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12933 SVOp->getMaskElt(j) >= 0)
12939 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12940 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12941 TargetLowering::DAGCombinerInfo &DCI,
12942 const X86Subtarget* Subtarget) {
12943 DebugLoc dl = N->getDebugLoc();
12944 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12945 SDValue V1 = SVOp->getOperand(0);
12946 SDValue V2 = SVOp->getOperand(1);
12947 EVT VT = SVOp->getValueType(0);
12948 unsigned NumElems = VT.getVectorNumElements();
12950 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12951 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12955 // V UNDEF BUILD_VECTOR UNDEF
12957 // CONCAT_VECTOR CONCAT_VECTOR
12960 // RESULT: V + zero extended
12962 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12963 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12964 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12967 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12970 // To match the shuffle mask, the first half of the mask should
12971 // be exactly the first vector, and all the rest a splat with the
12972 // first element of the second one.
12973 for (unsigned i = 0; i != NumElems/2; ++i)
12974 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12975 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12978 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
12979 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
12980 if (Ld->hasNUsesOfValue(1, 0)) {
12981 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
12982 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
12984 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
12986 Ld->getPointerInfo(),
12987 Ld->getAlignment(),
12988 false/*isVolatile*/, true/*ReadMem*/,
12989 false/*WriteMem*/);
12990 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
12994 // Emit a zeroed vector and insert the desired subvector on its
12996 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12997 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
12998 return DCI.CombineTo(N, InsV);
13001 //===--------------------------------------------------------------------===//
13002 // Combine some shuffles into subvector extracts and inserts:
13005 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13006 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13007 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13008 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13009 return DCI.CombineTo(N, InsV);
13012 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13013 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13014 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13015 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13016 return DCI.CombineTo(N, InsV);
13022 /// PerformShuffleCombine - Performs several different shuffle combines.
13023 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13024 TargetLowering::DAGCombinerInfo &DCI,
13025 const X86Subtarget *Subtarget) {
13026 DebugLoc dl = N->getDebugLoc();
13027 EVT VT = N->getValueType(0);
13029 // Don't create instructions with illegal types after legalize types has run.
13030 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13031 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13034 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13035 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13036 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13037 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13039 // Only handle 128 wide vector from here on.
13040 if (VT.getSizeInBits() != 128)
13043 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13044 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13045 // consecutive, non-overlapping, and in the right order.
13046 SmallVector<SDValue, 16> Elts;
13047 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13048 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13050 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13054 /// DCI, PerformTruncateCombine - Converts truncate operation to
13055 /// a sequence of vector shuffle operations.
13056 /// It is possible when we truncate 256-bit vector to 128-bit vector
13058 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13059 DAGCombinerInfo &DCI) const {
13060 if (!DCI.isBeforeLegalizeOps())
13063 if (!Subtarget->hasAVX())
13066 EVT VT = N->getValueType(0);
13067 SDValue Op = N->getOperand(0);
13068 EVT OpVT = Op.getValueType();
13069 DebugLoc dl = N->getDebugLoc();
13071 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13073 if (Subtarget->hasAVX2()) {
13074 // AVX2: v4i64 -> v4i32
13077 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13079 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13080 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13083 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13084 DAG.getIntPtrConstant(0));
13087 // AVX: v4i64 -> v4i32
13088 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13089 DAG.getIntPtrConstant(0));
13091 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13092 DAG.getIntPtrConstant(2));
13094 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13095 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13098 static const int ShufMask1[] = {0, 2, 0, 0};
13100 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13101 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13104 static const int ShufMask2[] = {0, 1, 4, 5};
13106 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13109 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13111 if (Subtarget->hasAVX2()) {
13112 // AVX2: v8i32 -> v8i16
13114 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13117 SmallVector<SDValue,32> pshufbMask;
13118 for (unsigned i = 0; i < 2; ++i) {
13119 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13120 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13121 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13122 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13123 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13124 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13125 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13126 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13127 for (unsigned j = 0; j < 8; ++j)
13128 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13130 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13131 &pshufbMask[0], 32);
13132 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13134 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13136 static const int ShufMask[] = {0, 2, -1, -1};
13137 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13140 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13141 DAG.getIntPtrConstant(0));
13143 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13146 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13147 DAG.getIntPtrConstant(0));
13149 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13150 DAG.getIntPtrConstant(4));
13152 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13153 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13156 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13157 -1, -1, -1, -1, -1, -1, -1, -1};
13159 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13161 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13164 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13165 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13168 static const int ShufMask2[] = {0, 1, 4, 5};
13170 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13171 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13177 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13178 /// specific shuffle of a load can be folded into a single element load.
13179 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13180 /// shuffles have been customed lowered so we need to handle those here.
13181 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13182 TargetLowering::DAGCombinerInfo &DCI) {
13183 if (DCI.isBeforeLegalizeOps())
13186 SDValue InVec = N->getOperand(0);
13187 SDValue EltNo = N->getOperand(1);
13189 if (!isa<ConstantSDNode>(EltNo))
13192 EVT VT = InVec.getValueType();
13194 bool HasShuffleIntoBitcast = false;
13195 if (InVec.getOpcode() == ISD::BITCAST) {
13196 // Don't duplicate a load with other uses.
13197 if (!InVec.hasOneUse())
13199 EVT BCVT = InVec.getOperand(0).getValueType();
13200 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13202 InVec = InVec.getOperand(0);
13203 HasShuffleIntoBitcast = true;
13206 if (!isTargetShuffle(InVec.getOpcode()))
13209 // Don't duplicate a load with other uses.
13210 if (!InVec.hasOneUse())
13213 SmallVector<int, 16> ShuffleMask;
13215 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13219 // Select the input vector, guarding against out of range extract vector.
13220 unsigned NumElems = VT.getVectorNumElements();
13221 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13222 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13223 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13224 : InVec.getOperand(1);
13226 // If inputs to shuffle are the same for both ops, then allow 2 uses
13227 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13229 if (LdNode.getOpcode() == ISD::BITCAST) {
13230 // Don't duplicate a load with other uses.
13231 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13234 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13235 LdNode = LdNode.getOperand(0);
13238 if (!ISD::isNormalLoad(LdNode.getNode()))
13241 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13243 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13246 if (HasShuffleIntoBitcast) {
13247 // If there's a bitcast before the shuffle, check if the load type and
13248 // alignment is valid.
13249 unsigned Align = LN0->getAlignment();
13250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13251 unsigned NewAlign = TLI.getTargetData()->
13252 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13254 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13258 // All checks match so transform back to vector_shuffle so that DAG combiner
13259 // can finish the job
13260 DebugLoc dl = N->getDebugLoc();
13262 // Create shuffle node taking into account the case that its a unary shuffle
13263 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13264 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13265 InVec.getOperand(0), Shuffle,
13267 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13268 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13272 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13273 /// generation and convert it from being a bunch of shuffles and extracts
13274 /// to a simple store and scalar loads to extract the elements.
13275 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13276 TargetLowering::DAGCombinerInfo &DCI) {
13277 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13278 if (NewOp.getNode())
13281 SDValue InputVector = N->getOperand(0);
13283 // Only operate on vectors of 4 elements, where the alternative shuffling
13284 // gets to be more expensive.
13285 if (InputVector.getValueType() != MVT::v4i32)
13288 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13289 // single use which is a sign-extend or zero-extend, and all elements are
13291 SmallVector<SDNode *, 4> Uses;
13292 unsigned ExtractedElements = 0;
13293 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13294 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13295 if (UI.getUse().getResNo() != InputVector.getResNo())
13298 SDNode *Extract = *UI;
13299 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13302 if (Extract->getValueType(0) != MVT::i32)
13304 if (!Extract->hasOneUse())
13306 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13307 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13309 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13312 // Record which element was extracted.
13313 ExtractedElements |=
13314 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13316 Uses.push_back(Extract);
13319 // If not all the elements were used, this may not be worthwhile.
13320 if (ExtractedElements != 15)
13323 // Ok, we've now decided to do the transformation.
13324 DebugLoc dl = InputVector.getDebugLoc();
13326 // Store the value to a temporary stack slot.
13327 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13328 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13329 MachinePointerInfo(), false, false, 0);
13331 // Replace each use (extract) with a load of the appropriate element.
13332 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13333 UE = Uses.end(); UI != UE; ++UI) {
13334 SDNode *Extract = *UI;
13336 // cOMpute the element's address.
13337 SDValue Idx = Extract->getOperand(1);
13339 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13340 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13341 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13342 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13344 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13345 StackPtr, OffsetVal);
13347 // Load the scalar.
13348 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13349 ScalarAddr, MachinePointerInfo(),
13350 false, false, false, 0);
13352 // Replace the exact with the load.
13353 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13356 // The replacement was made in place; don't return anything.
13360 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13362 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13363 TargetLowering::DAGCombinerInfo &DCI,
13364 const X86Subtarget *Subtarget) {
13365 DebugLoc DL = N->getDebugLoc();
13366 SDValue Cond = N->getOperand(0);
13367 // Get the LHS/RHS of the select.
13368 SDValue LHS = N->getOperand(1);
13369 SDValue RHS = N->getOperand(2);
13370 EVT VT = LHS.getValueType();
13372 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13373 // instructions match the semantics of the common C idiom x<y?x:y but not
13374 // x<=y?x:y, because of how they handle negative zero (which can be
13375 // ignored in unsafe-math mode).
13376 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13377 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13378 (Subtarget->hasSSE2() ||
13379 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13380 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13382 unsigned Opcode = 0;
13383 // Check for x CC y ? x : y.
13384 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13385 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13389 // Converting this to a min would handle NaNs incorrectly, and swapping
13390 // the operands would cause it to handle comparisons between positive
13391 // and negative zero incorrectly.
13392 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13393 if (!DAG.getTarget().Options.UnsafeFPMath &&
13394 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13396 std::swap(LHS, RHS);
13398 Opcode = X86ISD::FMIN;
13401 // Converting this to a min would handle comparisons between positive
13402 // and negative zero incorrectly.
13403 if (!DAG.getTarget().Options.UnsafeFPMath &&
13404 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13406 Opcode = X86ISD::FMIN;
13409 // Converting this to a min would handle both negative zeros and NaNs
13410 // incorrectly, but we can swap the operands to fix both.
13411 std::swap(LHS, RHS);
13415 Opcode = X86ISD::FMIN;
13419 // Converting this to a max would handle comparisons between positive
13420 // and negative zero incorrectly.
13421 if (!DAG.getTarget().Options.UnsafeFPMath &&
13422 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13424 Opcode = X86ISD::FMAX;
13427 // Converting this to a max would handle NaNs incorrectly, and swapping
13428 // the operands would cause it to handle comparisons between positive
13429 // and negative zero incorrectly.
13430 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13431 if (!DAG.getTarget().Options.UnsafeFPMath &&
13432 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13434 std::swap(LHS, RHS);
13436 Opcode = X86ISD::FMAX;
13439 // Converting this to a max would handle both negative zeros and NaNs
13440 // incorrectly, but we can swap the operands to fix both.
13441 std::swap(LHS, RHS);
13445 Opcode = X86ISD::FMAX;
13448 // Check for x CC y ? y : x -- a min/max with reversed arms.
13449 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13450 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13454 // Converting this to a min would handle comparisons between positive
13455 // and negative zero incorrectly, and swapping the operands would
13456 // cause it to handle NaNs incorrectly.
13457 if (!DAG.getTarget().Options.UnsafeFPMath &&
13458 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13459 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13461 std::swap(LHS, RHS);
13463 Opcode = X86ISD::FMIN;
13466 // Converting this to a min would handle NaNs incorrectly.
13467 if (!DAG.getTarget().Options.UnsafeFPMath &&
13468 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13470 Opcode = X86ISD::FMIN;
13473 // Converting this to a min would handle both negative zeros and NaNs
13474 // incorrectly, but we can swap the operands to fix both.
13475 std::swap(LHS, RHS);
13479 Opcode = X86ISD::FMIN;
13483 // Converting this to a max would handle NaNs incorrectly.
13484 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13486 Opcode = X86ISD::FMAX;
13489 // Converting this to a max would handle comparisons between positive
13490 // and negative zero incorrectly, and swapping the operands would
13491 // cause it to handle NaNs incorrectly.
13492 if (!DAG.getTarget().Options.UnsafeFPMath &&
13493 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13494 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13496 std::swap(LHS, RHS);
13498 Opcode = X86ISD::FMAX;
13501 // Converting this to a max would handle both negative zeros and NaNs
13502 // incorrectly, but we can swap the operands to fix both.
13503 std::swap(LHS, RHS);
13507 Opcode = X86ISD::FMAX;
13513 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13516 // If this is a select between two integer constants, try to do some
13518 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13519 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13520 // Don't do this for crazy integer types.
13521 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13522 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13523 // so that TrueC (the true value) is larger than FalseC.
13524 bool NeedsCondInvert = false;
13526 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13527 // Efficiently invertible.
13528 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13529 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13530 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13531 NeedsCondInvert = true;
13532 std::swap(TrueC, FalseC);
13535 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13536 if (FalseC->getAPIntValue() == 0 &&
13537 TrueC->getAPIntValue().isPowerOf2()) {
13538 if (NeedsCondInvert) // Invert the condition if needed.
13539 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13540 DAG.getConstant(1, Cond.getValueType()));
13542 // Zero extend the condition if needed.
13543 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13545 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13546 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13547 DAG.getConstant(ShAmt, MVT::i8));
13550 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13551 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13552 if (NeedsCondInvert) // Invert the condition if needed.
13553 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13554 DAG.getConstant(1, Cond.getValueType()));
13556 // Zero extend the condition if needed.
13557 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13558 FalseC->getValueType(0), Cond);
13559 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13560 SDValue(FalseC, 0));
13563 // Optimize cases that will turn into an LEA instruction. This requires
13564 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13565 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13566 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13567 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13569 bool isFastMultiplier = false;
13571 switch ((unsigned char)Diff) {
13573 case 1: // result = add base, cond
13574 case 2: // result = lea base( , cond*2)
13575 case 3: // result = lea base(cond, cond*2)
13576 case 4: // result = lea base( , cond*4)
13577 case 5: // result = lea base(cond, cond*4)
13578 case 8: // result = lea base( , cond*8)
13579 case 9: // result = lea base(cond, cond*8)
13580 isFastMultiplier = true;
13585 if (isFastMultiplier) {
13586 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13587 if (NeedsCondInvert) // Invert the condition if needed.
13588 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13589 DAG.getConstant(1, Cond.getValueType()));
13591 // Zero extend the condition if needed.
13592 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13594 // Scale the condition by the difference.
13596 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13597 DAG.getConstant(Diff, Cond.getValueType()));
13599 // Add the base if non-zero.
13600 if (FalseC->getAPIntValue() != 0)
13601 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13602 SDValue(FalseC, 0));
13609 // Canonicalize max and min:
13610 // (x > y) ? x : y -> (x >= y) ? x : y
13611 // (x < y) ? x : y -> (x <= y) ? x : y
13612 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13613 // the need for an extra compare
13614 // against zero. e.g.
13615 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13617 // testl %edi, %edi
13619 // cmovgl %edi, %eax
13623 // cmovsl %eax, %edi
13624 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13625 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13626 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13627 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13632 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13633 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13634 Cond.getOperand(0), Cond.getOperand(1), NewCC);
13635 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13640 // If we know that this node is legal then we know that it is going to be
13641 // matched by one of the SSE/AVX BLEND instructions. These instructions only
13642 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13643 // to simplify previous instructions.
13644 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13645 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13646 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13647 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13649 // Don't optimize vector selects that map to mask-registers.
13653 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13654 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13656 APInt KnownZero, KnownOne;
13657 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13658 DCI.isBeforeLegalizeOps());
13659 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13660 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13661 DCI.CommitTargetLoweringOpt(TLO);
13667 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13668 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13669 TargetLowering::DAGCombinerInfo &DCI) {
13670 DebugLoc DL = N->getDebugLoc();
13672 // If the flag operand isn't dead, don't touch this CMOV.
13673 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13676 SDValue FalseOp = N->getOperand(0);
13677 SDValue TrueOp = N->getOperand(1);
13678 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13679 SDValue Cond = N->getOperand(3);
13680 if (CC == X86::COND_E || CC == X86::COND_NE) {
13681 switch (Cond.getOpcode()) {
13685 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13686 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13687 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13691 // If this is a select between two integer constants, try to do some
13692 // optimizations. Note that the operands are ordered the opposite of SELECT
13694 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13695 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13696 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13697 // larger than FalseC (the false value).
13698 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13699 CC = X86::GetOppositeBranchCondition(CC);
13700 std::swap(TrueC, FalseC);
13703 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13704 // This is efficient for any integer data type (including i8/i16) and
13706 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13707 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13708 DAG.getConstant(CC, MVT::i8), Cond);
13710 // Zero extend the condition if needed.
13711 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13713 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13714 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13715 DAG.getConstant(ShAmt, MVT::i8));
13716 if (N->getNumValues() == 2) // Dead flag value?
13717 return DCI.CombineTo(N, Cond, SDValue());
13721 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13722 // for any integer data type, including i8/i16.
13723 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13724 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13725 DAG.getConstant(CC, MVT::i8), Cond);
13727 // Zero extend the condition if needed.
13728 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13729 FalseC->getValueType(0), Cond);
13730 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13731 SDValue(FalseC, 0));
13733 if (N->getNumValues() == 2) // Dead flag value?
13734 return DCI.CombineTo(N, Cond, SDValue());
13738 // Optimize cases that will turn into an LEA instruction. This requires
13739 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13740 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13741 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13742 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13744 bool isFastMultiplier = false;
13746 switch ((unsigned char)Diff) {
13748 case 1: // result = add base, cond
13749 case 2: // result = lea base( , cond*2)
13750 case 3: // result = lea base(cond, cond*2)
13751 case 4: // result = lea base( , cond*4)
13752 case 5: // result = lea base(cond, cond*4)
13753 case 8: // result = lea base( , cond*8)
13754 case 9: // result = lea base(cond, cond*8)
13755 isFastMultiplier = true;
13760 if (isFastMultiplier) {
13761 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13762 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13763 DAG.getConstant(CC, MVT::i8), Cond);
13764 // Zero extend the condition if needed.
13765 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13767 // Scale the condition by the difference.
13769 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13770 DAG.getConstant(Diff, Cond.getValueType()));
13772 // Add the base if non-zero.
13773 if (FalseC->getAPIntValue() != 0)
13774 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13775 SDValue(FalseC, 0));
13776 if (N->getNumValues() == 2) // Dead flag value?
13777 return DCI.CombineTo(N, Cond, SDValue());
13787 /// PerformMulCombine - Optimize a single multiply with constant into two
13788 /// in order to implement it with two cheaper instructions, e.g.
13789 /// LEA + SHL, LEA + LEA.
13790 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13791 TargetLowering::DAGCombinerInfo &DCI) {
13792 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13795 EVT VT = N->getValueType(0);
13796 if (VT != MVT::i64)
13799 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13802 uint64_t MulAmt = C->getZExtValue();
13803 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13806 uint64_t MulAmt1 = 0;
13807 uint64_t MulAmt2 = 0;
13808 if ((MulAmt % 9) == 0) {
13810 MulAmt2 = MulAmt / 9;
13811 } else if ((MulAmt % 5) == 0) {
13813 MulAmt2 = MulAmt / 5;
13814 } else if ((MulAmt % 3) == 0) {
13816 MulAmt2 = MulAmt / 3;
13819 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13820 DebugLoc DL = N->getDebugLoc();
13822 if (isPowerOf2_64(MulAmt2) &&
13823 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13824 // If second multiplifer is pow2, issue it first. We want the multiply by
13825 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13827 std::swap(MulAmt1, MulAmt2);
13830 if (isPowerOf2_64(MulAmt1))
13831 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13832 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13834 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13835 DAG.getConstant(MulAmt1, VT));
13837 if (isPowerOf2_64(MulAmt2))
13838 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13839 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13841 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13842 DAG.getConstant(MulAmt2, VT));
13844 // Do not add new nodes to DAG combiner worklist.
13845 DCI.CombineTo(N, NewMul, false);
13850 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13851 SDValue N0 = N->getOperand(0);
13852 SDValue N1 = N->getOperand(1);
13853 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13854 EVT VT = N0.getValueType();
13856 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13857 // since the result of setcc_c is all zero's or all ones.
13858 if (VT.isInteger() && !VT.isVector() &&
13859 N1C && N0.getOpcode() == ISD::AND &&
13860 N0.getOperand(1).getOpcode() == ISD::Constant) {
13861 SDValue N00 = N0.getOperand(0);
13862 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13863 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13864 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13865 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13866 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13867 APInt ShAmt = N1C->getAPIntValue();
13868 Mask = Mask.shl(ShAmt);
13870 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13871 N00, DAG.getConstant(Mask, VT));
13876 // Hardware support for vector shifts is sparse which makes us scalarize the
13877 // vector operations in many cases. Also, on sandybridge ADD is faster than
13879 // (shl V, 1) -> add V,V
13880 if (isSplatVector(N1.getNode())) {
13881 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13882 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13883 // We shift all of the values by one. In many cases we do not have
13884 // hardware support for this operation. This is better expressed as an ADD
13886 if (N1C && (1 == N1C->getZExtValue())) {
13887 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13894 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13896 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13897 TargetLowering::DAGCombinerInfo &DCI,
13898 const X86Subtarget *Subtarget) {
13899 EVT VT = N->getValueType(0);
13900 if (N->getOpcode() == ISD::SHL) {
13901 SDValue V = PerformSHLCombine(N, DAG);
13902 if (V.getNode()) return V;
13905 // On X86 with SSE2 support, we can transform this to a vector shift if
13906 // all elements are shifted by the same amount. We can't do this in legalize
13907 // because the a constant vector is typically transformed to a constant pool
13908 // so we have no knowledge of the shift amount.
13909 if (!Subtarget->hasSSE2())
13912 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13913 (!Subtarget->hasAVX2() ||
13914 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13917 SDValue ShAmtOp = N->getOperand(1);
13918 EVT EltVT = VT.getVectorElementType();
13919 DebugLoc DL = N->getDebugLoc();
13920 SDValue BaseShAmt = SDValue();
13921 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13922 unsigned NumElts = VT.getVectorNumElements();
13924 for (; i != NumElts; ++i) {
13925 SDValue Arg = ShAmtOp.getOperand(i);
13926 if (Arg.getOpcode() == ISD::UNDEF) continue;
13930 // Handle the case where the build_vector is all undef
13931 // FIXME: Should DAG allow this?
13935 for (; i != NumElts; ++i) {
13936 SDValue Arg = ShAmtOp.getOperand(i);
13937 if (Arg.getOpcode() == ISD::UNDEF) continue;
13938 if (Arg != BaseShAmt) {
13942 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13943 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13944 SDValue InVec = ShAmtOp.getOperand(0);
13945 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13946 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13948 for (; i != NumElts; ++i) {
13949 SDValue Arg = InVec.getOperand(i);
13950 if (Arg.getOpcode() == ISD::UNDEF) continue;
13954 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13955 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13956 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13957 if (C->getZExtValue() == SplatIdx)
13958 BaseShAmt = InVec.getOperand(1);
13961 if (BaseShAmt.getNode() == 0) {
13962 // Don't create instructions with illegal types after legalize
13964 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
13965 !DCI.isBeforeLegalize())
13968 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13969 DAG.getIntPtrConstant(0));
13974 // The shift amount is an i32.
13975 if (EltVT.bitsGT(MVT::i32))
13976 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13977 else if (EltVT.bitsLT(MVT::i32))
13978 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13980 // The shift amount is identical so we can do a vector shift.
13981 SDValue ValOp = N->getOperand(0);
13982 switch (N->getOpcode()) {
13984 llvm_unreachable("Unknown shift opcode!");
13986 switch (VT.getSimpleVT().SimpleTy) {
13987 default: return SDValue();
13994 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
13997 switch (VT.getSimpleVT().SimpleTy) {
13998 default: return SDValue();
14003 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14006 switch (VT.getSimpleVT().SimpleTy) {
14007 default: return SDValue();
14014 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14020 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14021 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14022 // and friends. Likewise for OR -> CMPNEQSS.
14023 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14024 TargetLowering::DAGCombinerInfo &DCI,
14025 const X86Subtarget *Subtarget) {
14028 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14029 // we're requiring SSE2 for both.
14030 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14031 SDValue N0 = N->getOperand(0);
14032 SDValue N1 = N->getOperand(1);
14033 SDValue CMP0 = N0->getOperand(1);
14034 SDValue CMP1 = N1->getOperand(1);
14035 DebugLoc DL = N->getDebugLoc();
14037 // The SETCCs should both refer to the same CMP.
14038 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14041 SDValue CMP00 = CMP0->getOperand(0);
14042 SDValue CMP01 = CMP0->getOperand(1);
14043 EVT VT = CMP00.getValueType();
14045 if (VT == MVT::f32 || VT == MVT::f64) {
14046 bool ExpectingFlags = false;
14047 // Check for any users that want flags:
14048 for (SDNode::use_iterator UI = N->use_begin(),
14050 !ExpectingFlags && UI != UE; ++UI)
14051 switch (UI->getOpcode()) {
14056 ExpectingFlags = true;
14058 case ISD::CopyToReg:
14059 case ISD::SIGN_EXTEND:
14060 case ISD::ZERO_EXTEND:
14061 case ISD::ANY_EXTEND:
14065 if (!ExpectingFlags) {
14066 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14067 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14069 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14070 X86::CondCode tmp = cc0;
14075 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14076 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14077 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14078 X86ISD::NodeType NTOperator = is64BitFP ?
14079 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14080 // FIXME: need symbolic constants for these magic numbers.
14081 // See X86ATTInstPrinter.cpp:printSSECC().
14082 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14083 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14084 DAG.getConstant(x86cc, MVT::i8));
14085 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14087 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14088 DAG.getConstant(1, MVT::i32));
14089 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14090 return OneBitOfTruth;
14098 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14099 /// so it can be folded inside ANDNP.
14100 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14101 EVT VT = N->getValueType(0);
14103 // Match direct AllOnes for 128 and 256-bit vectors
14104 if (ISD::isBuildVectorAllOnes(N))
14107 // Look through a bit convert.
14108 if (N->getOpcode() == ISD::BITCAST)
14109 N = N->getOperand(0).getNode();
14111 // Sometimes the operand may come from a insert_subvector building a 256-bit
14113 if (VT.getSizeInBits() == 256 &&
14114 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14115 SDValue V1 = N->getOperand(0);
14116 SDValue V2 = N->getOperand(1);
14118 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14119 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14120 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14121 ISD::isBuildVectorAllOnes(V2.getNode()))
14128 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14129 TargetLowering::DAGCombinerInfo &DCI,
14130 const X86Subtarget *Subtarget) {
14131 if (DCI.isBeforeLegalizeOps())
14134 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14138 EVT VT = N->getValueType(0);
14140 // Create ANDN, BLSI, and BLSR instructions
14141 // BLSI is X & (-X)
14142 // BLSR is X & (X-1)
14143 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14144 SDValue N0 = N->getOperand(0);
14145 SDValue N1 = N->getOperand(1);
14146 DebugLoc DL = N->getDebugLoc();
14148 // Check LHS for not
14149 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14150 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14151 // Check RHS for not
14152 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14153 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14155 // Check LHS for neg
14156 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14157 isZero(N0.getOperand(0)))
14158 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14160 // Check RHS for neg
14161 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14162 isZero(N1.getOperand(0)))
14163 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14165 // Check LHS for X-1
14166 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14167 isAllOnes(N0.getOperand(1)))
14168 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14170 // Check RHS for X-1
14171 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14172 isAllOnes(N1.getOperand(1)))
14173 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14178 // Want to form ANDNP nodes:
14179 // 1) In the hopes of then easily combining them with OR and AND nodes
14180 // to form PBLEND/PSIGN.
14181 // 2) To match ANDN packed intrinsics
14182 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14185 SDValue N0 = N->getOperand(0);
14186 SDValue N1 = N->getOperand(1);
14187 DebugLoc DL = N->getDebugLoc();
14189 // Check LHS for vnot
14190 if (N0.getOpcode() == ISD::XOR &&
14191 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14192 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14193 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14195 // Check RHS for vnot
14196 if (N1.getOpcode() == ISD::XOR &&
14197 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14198 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14199 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14204 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14205 TargetLowering::DAGCombinerInfo &DCI,
14206 const X86Subtarget *Subtarget) {
14207 if (DCI.isBeforeLegalizeOps())
14210 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14214 EVT VT = N->getValueType(0);
14216 SDValue N0 = N->getOperand(0);
14217 SDValue N1 = N->getOperand(1);
14219 // look for psign/blend
14220 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14221 if (!Subtarget->hasSSSE3() ||
14222 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14225 // Canonicalize pandn to RHS
14226 if (N0.getOpcode() == X86ISD::ANDNP)
14228 // or (and (m, y), (pandn m, x))
14229 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14230 SDValue Mask = N1.getOperand(0);
14231 SDValue X = N1.getOperand(1);
14233 if (N0.getOperand(0) == Mask)
14234 Y = N0.getOperand(1);
14235 if (N0.getOperand(1) == Mask)
14236 Y = N0.getOperand(0);
14238 // Check to see if the mask appeared in both the AND and ANDNP and
14242 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14243 // Look through mask bitcast.
14244 if (Mask.getOpcode() == ISD::BITCAST)
14245 Mask = Mask.getOperand(0);
14246 if (X.getOpcode() == ISD::BITCAST)
14247 X = X.getOperand(0);
14248 if (Y.getOpcode() == ISD::BITCAST)
14249 Y = Y.getOperand(0);
14251 EVT MaskVT = Mask.getValueType();
14253 // Validate that the Mask operand is a vector sra node.
14254 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14255 // there is no psrai.b
14256 if (Mask.getOpcode() != X86ISD::VSRAI)
14259 // Check that the SRA is all signbits.
14260 SDValue SraC = Mask.getOperand(1);
14261 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14262 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14263 if ((SraAmt + 1) != EltBits)
14266 DebugLoc DL = N->getDebugLoc();
14268 // Now we know we at least have a plendvb with the mask val. See if
14269 // we can form a psignb/w/d.
14270 // psign = x.type == y.type == mask.type && y = sub(0, x);
14271 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14272 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14273 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14274 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14275 "Unsupported VT for PSIGN");
14276 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14277 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14279 // PBLENDVB only available on SSE 4.1
14280 if (!Subtarget->hasSSE41())
14283 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14285 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14286 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14287 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14288 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14289 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14293 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14296 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14297 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14299 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14301 if (!N0.hasOneUse() || !N1.hasOneUse())
14304 SDValue ShAmt0 = N0.getOperand(1);
14305 if (ShAmt0.getValueType() != MVT::i8)
14307 SDValue ShAmt1 = N1.getOperand(1);
14308 if (ShAmt1.getValueType() != MVT::i8)
14310 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14311 ShAmt0 = ShAmt0.getOperand(0);
14312 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14313 ShAmt1 = ShAmt1.getOperand(0);
14315 DebugLoc DL = N->getDebugLoc();
14316 unsigned Opc = X86ISD::SHLD;
14317 SDValue Op0 = N0.getOperand(0);
14318 SDValue Op1 = N1.getOperand(0);
14319 if (ShAmt0.getOpcode() == ISD::SUB) {
14320 Opc = X86ISD::SHRD;
14321 std::swap(Op0, Op1);
14322 std::swap(ShAmt0, ShAmt1);
14325 unsigned Bits = VT.getSizeInBits();
14326 if (ShAmt1.getOpcode() == ISD::SUB) {
14327 SDValue Sum = ShAmt1.getOperand(0);
14328 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14329 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14330 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14331 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14332 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14333 return DAG.getNode(Opc, DL, VT,
14335 DAG.getNode(ISD::TRUNCATE, DL,
14338 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14339 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14341 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14342 return DAG.getNode(Opc, DL, VT,
14343 N0.getOperand(0), N1.getOperand(0),
14344 DAG.getNode(ISD::TRUNCATE, DL,
14351 // Generate NEG and CMOV for integer abs.
14352 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14353 EVT VT = N->getValueType(0);
14355 // Since X86 does not have CMOV for 8-bit integer, we don't convert
14356 // 8-bit integer abs to NEG and CMOV.
14357 if (VT.isInteger() && VT.getSizeInBits() == 8)
14360 SDValue N0 = N->getOperand(0);
14361 SDValue N1 = N->getOperand(1);
14362 DebugLoc DL = N->getDebugLoc();
14364 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14365 // and change it to SUB and CMOV.
14366 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14367 N0.getOpcode() == ISD::ADD &&
14368 N0.getOperand(1) == N1 &&
14369 N1.getOpcode() == ISD::SRA &&
14370 N1.getOperand(0) == N0.getOperand(0))
14371 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14372 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14373 // Generate SUB & CMOV.
14374 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14375 DAG.getConstant(0, VT), N0.getOperand(0));
14377 SDValue Ops[] = { N0.getOperand(0), Neg,
14378 DAG.getConstant(X86::COND_GE, MVT::i8),
14379 SDValue(Neg.getNode(), 1) };
14380 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14381 Ops, array_lengthof(Ops));
14386 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14387 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14388 TargetLowering::DAGCombinerInfo &DCI,
14389 const X86Subtarget *Subtarget) {
14390 if (DCI.isBeforeLegalizeOps())
14393 if (Subtarget->hasCMov()) {
14394 SDValue RV = performIntegerAbsCombine(N, DAG);
14399 // Try forming BMI if it is available.
14400 if (!Subtarget->hasBMI())
14403 EVT VT = N->getValueType(0);
14405 if (VT != MVT::i32 && VT != MVT::i64)
14408 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14410 // Create BLSMSK instructions by finding X ^ (X-1)
14411 SDValue N0 = N->getOperand(0);
14412 SDValue N1 = N->getOperand(1);
14413 DebugLoc DL = N->getDebugLoc();
14415 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14416 isAllOnes(N0.getOperand(1)))
14417 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14419 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14420 isAllOnes(N1.getOperand(1)))
14421 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14426 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14427 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14428 const X86Subtarget *Subtarget) {
14429 LoadSDNode *Ld = cast<LoadSDNode>(N);
14430 EVT RegVT = Ld->getValueType(0);
14431 EVT MemVT = Ld->getMemoryVT();
14432 DebugLoc dl = Ld->getDebugLoc();
14433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14435 ISD::LoadExtType Ext = Ld->getExtensionType();
14437 // If this is a vector EXT Load then attempt to optimize it using a
14438 // shuffle. We need SSE4 for the shuffles.
14439 // TODO: It is possible to support ZExt by zeroing the undef values
14440 // during the shuffle phase or after the shuffle.
14441 if (RegVT.isVector() && RegVT.isInteger() &&
14442 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14443 assert(MemVT != RegVT && "Cannot extend to the same type");
14444 assert(MemVT.isVector() && "Must load a vector from memory");
14446 unsigned NumElems = RegVT.getVectorNumElements();
14447 unsigned RegSz = RegVT.getSizeInBits();
14448 unsigned MemSz = MemVT.getSizeInBits();
14449 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14450 // All sizes must be a power of two
14451 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14453 // Attempt to load the original value using a single load op.
14454 // Find a scalar type which is equal to the loaded word size.
14455 MVT SclrLoadTy = MVT::i8;
14456 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14457 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14458 MVT Tp = (MVT::SimpleValueType)tp;
14459 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
14465 // Proceed if a load word is found.
14466 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14468 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14469 RegSz/SclrLoadTy.getSizeInBits());
14471 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14472 RegSz/MemVT.getScalarType().getSizeInBits());
14473 // Can't shuffle using an illegal type.
14474 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14476 // Perform a single load.
14477 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14479 Ld->getPointerInfo(), Ld->isVolatile(),
14480 Ld->isNonTemporal(), Ld->isInvariant(),
14481 Ld->getAlignment());
14483 // Insert the word loaded into a vector.
14484 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14485 LoadUnitVecVT, ScalarLoad);
14487 // Bitcast the loaded value to a vector of the original element type, in
14488 // the size of the target vector type.
14489 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14491 unsigned SizeRatio = RegSz/MemSz;
14493 // Redistribute the loaded elements into the different locations.
14494 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14495 for (unsigned i = 0; i != NumElems; ++i)
14496 ShuffleVec[i*SizeRatio] = i;
14498 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14499 DAG.getUNDEF(WideVecVT),
14502 // Bitcast to the requested type.
14503 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14504 // Replace the original load with the new sequence
14505 // and return the new chain.
14506 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14507 return SDValue(ScalarLoad.getNode(), 1);
14513 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14514 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14515 const X86Subtarget *Subtarget) {
14516 StoreSDNode *St = cast<StoreSDNode>(N);
14517 EVT VT = St->getValue().getValueType();
14518 EVT StVT = St->getMemoryVT();
14519 DebugLoc dl = St->getDebugLoc();
14520 SDValue StoredVal = St->getOperand(1);
14521 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14523 // If we are saving a concatenation of two XMM registers, perform two stores.
14524 // On Sandy Bridge, 256-bit memory operations are executed by two
14525 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14526 // memory operation.
14527 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14528 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14529 StoredVal.getNumOperands() == 2) {
14530 SDValue Value0 = StoredVal.getOperand(0);
14531 SDValue Value1 = StoredVal.getOperand(1);
14533 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14534 SDValue Ptr0 = St->getBasePtr();
14535 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14537 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14538 St->getPointerInfo(), St->isVolatile(),
14539 St->isNonTemporal(), St->getAlignment());
14540 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14541 St->getPointerInfo(), St->isVolatile(),
14542 St->isNonTemporal(), St->getAlignment());
14543 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14546 // Optimize trunc store (of multiple scalars) to shuffle and store.
14547 // First, pack all of the elements in one place. Next, store to memory
14548 // in fewer chunks.
14549 if (St->isTruncatingStore() && VT.isVector()) {
14550 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14551 unsigned NumElems = VT.getVectorNumElements();
14552 assert(StVT != VT && "Cannot truncate to the same type");
14553 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14554 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14556 // From, To sizes and ElemCount must be pow of two
14557 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14558 // We are going to use the original vector elt for storing.
14559 // Accumulated smaller vector elements must be a multiple of the store size.
14560 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14562 unsigned SizeRatio = FromSz / ToSz;
14564 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14566 // Create a type on which we perform the shuffle
14567 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14568 StVT.getScalarType(), NumElems*SizeRatio);
14570 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14572 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14573 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14574 for (unsigned i = 0; i != NumElems; ++i)
14575 ShuffleVec[i] = i * SizeRatio;
14577 // Can't shuffle using an illegal type
14578 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14580 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14581 DAG.getUNDEF(WideVecVT),
14583 // At this point all of the data is stored at the bottom of the
14584 // register. We now need to save it to mem.
14586 // Find the largest store unit
14587 MVT StoreType = MVT::i8;
14588 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14589 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14590 MVT Tp = (MVT::SimpleValueType)tp;
14591 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14595 // Bitcast the original vector into a vector of store-size units
14596 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14597 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14598 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14599 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14600 SmallVector<SDValue, 8> Chains;
14601 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14602 TLI.getPointerTy());
14603 SDValue Ptr = St->getBasePtr();
14605 // Perform one or more big stores into memory.
14606 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14607 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14608 StoreType, ShuffWide,
14609 DAG.getIntPtrConstant(i));
14610 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14611 St->getPointerInfo(), St->isVolatile(),
14612 St->isNonTemporal(), St->getAlignment());
14613 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14614 Chains.push_back(Ch);
14617 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14622 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14623 // the FP state in cases where an emms may be missing.
14624 // A preferable solution to the general problem is to figure out the right
14625 // places to insert EMMS. This qualifies as a quick hack.
14627 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14628 if (VT.getSizeInBits() != 64)
14631 const Function *F = DAG.getMachineFunction().getFunction();
14632 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14633 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14634 && Subtarget->hasSSE2();
14635 if ((VT.isVector() ||
14636 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14637 isa<LoadSDNode>(St->getValue()) &&
14638 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14639 St->getChain().hasOneUse() && !St->isVolatile()) {
14640 SDNode* LdVal = St->getValue().getNode();
14641 LoadSDNode *Ld = 0;
14642 int TokenFactorIndex = -1;
14643 SmallVector<SDValue, 8> Ops;
14644 SDNode* ChainVal = St->getChain().getNode();
14645 // Must be a store of a load. We currently handle two cases: the load
14646 // is a direct child, and it's under an intervening TokenFactor. It is
14647 // possible to dig deeper under nested TokenFactors.
14648 if (ChainVal == LdVal)
14649 Ld = cast<LoadSDNode>(St->getChain());
14650 else if (St->getValue().hasOneUse() &&
14651 ChainVal->getOpcode() == ISD::TokenFactor) {
14652 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14653 if (ChainVal->getOperand(i).getNode() == LdVal) {
14654 TokenFactorIndex = i;
14655 Ld = cast<LoadSDNode>(St->getValue());
14657 Ops.push_back(ChainVal->getOperand(i));
14661 if (!Ld || !ISD::isNormalLoad(Ld))
14664 // If this is not the MMX case, i.e. we are just turning i64 load/store
14665 // into f64 load/store, avoid the transformation if there are multiple
14666 // uses of the loaded value.
14667 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14670 DebugLoc LdDL = Ld->getDebugLoc();
14671 DebugLoc StDL = N->getDebugLoc();
14672 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14673 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14675 if (Subtarget->is64Bit() || F64IsLegal) {
14676 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14677 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14678 Ld->getPointerInfo(), Ld->isVolatile(),
14679 Ld->isNonTemporal(), Ld->isInvariant(),
14680 Ld->getAlignment());
14681 SDValue NewChain = NewLd.getValue(1);
14682 if (TokenFactorIndex != -1) {
14683 Ops.push_back(NewChain);
14684 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14687 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14688 St->getPointerInfo(),
14689 St->isVolatile(), St->isNonTemporal(),
14690 St->getAlignment());
14693 // Otherwise, lower to two pairs of 32-bit loads / stores.
14694 SDValue LoAddr = Ld->getBasePtr();
14695 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14696 DAG.getConstant(4, MVT::i32));
14698 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14699 Ld->getPointerInfo(),
14700 Ld->isVolatile(), Ld->isNonTemporal(),
14701 Ld->isInvariant(), Ld->getAlignment());
14702 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14703 Ld->getPointerInfo().getWithOffset(4),
14704 Ld->isVolatile(), Ld->isNonTemporal(),
14706 MinAlign(Ld->getAlignment(), 4));
14708 SDValue NewChain = LoLd.getValue(1);
14709 if (TokenFactorIndex != -1) {
14710 Ops.push_back(LoLd);
14711 Ops.push_back(HiLd);
14712 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14716 LoAddr = St->getBasePtr();
14717 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14718 DAG.getConstant(4, MVT::i32));
14720 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14721 St->getPointerInfo(),
14722 St->isVolatile(), St->isNonTemporal(),
14723 St->getAlignment());
14724 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14725 St->getPointerInfo().getWithOffset(4),
14727 St->isNonTemporal(),
14728 MinAlign(St->getAlignment(), 4));
14729 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14734 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14735 /// and return the operands for the horizontal operation in LHS and RHS. A
14736 /// horizontal operation performs the binary operation on successive elements
14737 /// of its first operand, then on successive elements of its second operand,
14738 /// returning the resulting values in a vector. For example, if
14739 /// A = < float a0, float a1, float a2, float a3 >
14741 /// B = < float b0, float b1, float b2, float b3 >
14742 /// then the result of doing a horizontal operation on A and B is
14743 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14744 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14745 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14746 /// set to A, RHS to B, and the routine returns 'true'.
14747 /// Note that the binary operation should have the property that if one of the
14748 /// operands is UNDEF then the result is UNDEF.
14749 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14750 // Look for the following pattern: if
14751 // A = < float a0, float a1, float a2, float a3 >
14752 // B = < float b0, float b1, float b2, float b3 >
14754 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14755 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14756 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14757 // which is A horizontal-op B.
14759 // At least one of the operands should be a vector shuffle.
14760 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14761 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14764 EVT VT = LHS.getValueType();
14766 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14767 "Unsupported vector type for horizontal add/sub");
14769 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14770 // operate independently on 128-bit lanes.
14771 unsigned NumElts = VT.getVectorNumElements();
14772 unsigned NumLanes = VT.getSizeInBits()/128;
14773 unsigned NumLaneElts = NumElts / NumLanes;
14774 assert((NumLaneElts % 2 == 0) &&
14775 "Vector type should have an even number of elements in each lane");
14776 unsigned HalfLaneElts = NumLaneElts/2;
14778 // View LHS in the form
14779 // LHS = VECTOR_SHUFFLE A, B, LMask
14780 // If LHS is not a shuffle then pretend it is the shuffle
14781 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14782 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14785 SmallVector<int, 16> LMask(NumElts);
14786 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14787 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14788 A = LHS.getOperand(0);
14789 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14790 B = LHS.getOperand(1);
14791 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14792 std::copy(Mask.begin(), Mask.end(), LMask.begin());
14794 if (LHS.getOpcode() != ISD::UNDEF)
14796 for (unsigned i = 0; i != NumElts; ++i)
14800 // Likewise, view RHS in the form
14801 // RHS = VECTOR_SHUFFLE C, D, RMask
14803 SmallVector<int, 16> RMask(NumElts);
14804 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14805 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14806 C = RHS.getOperand(0);
14807 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14808 D = RHS.getOperand(1);
14809 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14810 std::copy(Mask.begin(), Mask.end(), RMask.begin());
14812 if (RHS.getOpcode() != ISD::UNDEF)
14814 for (unsigned i = 0; i != NumElts; ++i)
14818 // Check that the shuffles are both shuffling the same vectors.
14819 if (!(A == C && B == D) && !(A == D && B == C))
14822 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14823 if (!A.getNode() && !B.getNode())
14826 // If A and B occur in reverse order in RHS, then "swap" them (which means
14827 // rewriting the mask).
14829 CommuteVectorShuffleMask(RMask, NumElts);
14831 // At this point LHS and RHS are equivalent to
14832 // LHS = VECTOR_SHUFFLE A, B, LMask
14833 // RHS = VECTOR_SHUFFLE A, B, RMask
14834 // Check that the masks correspond to performing a horizontal operation.
14835 for (unsigned i = 0; i != NumElts; ++i) {
14836 int LIdx = LMask[i], RIdx = RMask[i];
14838 // Ignore any UNDEF components.
14839 if (LIdx < 0 || RIdx < 0 ||
14840 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14841 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14844 // Check that successive elements are being operated on. If not, this is
14845 // not a horizontal operation.
14846 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14847 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14848 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14849 if (!(LIdx == Index && RIdx == Index + 1) &&
14850 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14854 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14855 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14859 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14860 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14861 const X86Subtarget *Subtarget) {
14862 EVT VT = N->getValueType(0);
14863 SDValue LHS = N->getOperand(0);
14864 SDValue RHS = N->getOperand(1);
14866 // Try to synthesize horizontal adds from adds of shuffles.
14867 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14868 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14869 isHorizontalBinOp(LHS, RHS, true))
14870 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14874 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14875 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14876 const X86Subtarget *Subtarget) {
14877 EVT VT = N->getValueType(0);
14878 SDValue LHS = N->getOperand(0);
14879 SDValue RHS = N->getOperand(1);
14881 // Try to synthesize horizontal subs from subs of shuffles.
14882 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14883 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14884 isHorizontalBinOp(LHS, RHS, false))
14885 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14889 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14890 /// X86ISD::FXOR nodes.
14891 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14892 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14893 // F[X]OR(0.0, x) -> x
14894 // F[X]OR(x, 0.0) -> x
14895 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14896 if (C->getValueAPF().isPosZero())
14897 return N->getOperand(1);
14898 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14899 if (C->getValueAPF().isPosZero())
14900 return N->getOperand(0);
14904 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14905 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14906 // FAND(0.0, x) -> 0.0
14907 // FAND(x, 0.0) -> 0.0
14908 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14909 if (C->getValueAPF().isPosZero())
14910 return N->getOperand(0);
14911 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14912 if (C->getValueAPF().isPosZero())
14913 return N->getOperand(1);
14917 static SDValue PerformBTCombine(SDNode *N,
14919 TargetLowering::DAGCombinerInfo &DCI) {
14920 // BT ignores high bits in the bit index operand.
14921 SDValue Op1 = N->getOperand(1);
14922 if (Op1.hasOneUse()) {
14923 unsigned BitWidth = Op1.getValueSizeInBits();
14924 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14925 APInt KnownZero, KnownOne;
14926 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14927 !DCI.isBeforeLegalizeOps());
14928 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14929 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14930 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14931 DCI.CommitTargetLoweringOpt(TLO);
14936 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14937 SDValue Op = N->getOperand(0);
14938 if (Op.getOpcode() == ISD::BITCAST)
14939 Op = Op.getOperand(0);
14940 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14941 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14942 VT.getVectorElementType().getSizeInBits() ==
14943 OpVT.getVectorElementType().getSizeInBits()) {
14944 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14949 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14950 TargetLowering::DAGCombinerInfo &DCI,
14951 const X86Subtarget *Subtarget) {
14952 if (!DCI.isBeforeLegalizeOps())
14955 if (!Subtarget->hasAVX())
14958 EVT VT = N->getValueType(0);
14959 SDValue Op = N->getOperand(0);
14960 EVT OpVT = Op.getValueType();
14961 DebugLoc dl = N->getDebugLoc();
14963 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
14964 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
14966 if (Subtarget->hasAVX2())
14967 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
14969 // Optimize vectors in AVX mode
14970 // Sign extend v8i16 to v8i32 and
14973 // Divide input vector into two parts
14974 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14975 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14976 // concat the vectors to original VT
14978 unsigned NumElems = OpVT.getVectorNumElements();
14979 SmallVector<int,8> ShufMask1(NumElems, -1);
14980 for (unsigned i = 0; i != NumElems/2; ++i)
14983 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14986 SmallVector<int,8> ShufMask2(NumElems, -1);
14987 for (unsigned i = 0; i != NumElems/2; ++i)
14988 ShufMask2[i] = i + NumElems/2;
14990 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14993 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
14994 VT.getVectorNumElements()/2);
14996 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
14997 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
14999 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15004 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15005 TargetLowering::DAGCombinerInfo &DCI,
15006 const X86Subtarget *Subtarget) {
15007 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15008 // (and (i32 x86isd::setcc_carry), 1)
15009 // This eliminates the zext. This transformation is necessary because
15010 // ISD::SETCC is always legalized to i8.
15011 DebugLoc dl = N->getDebugLoc();
15012 SDValue N0 = N->getOperand(0);
15013 EVT VT = N->getValueType(0);
15014 EVT OpVT = N0.getValueType();
15016 if (N0.getOpcode() == ISD::AND &&
15018 N0.getOperand(0).hasOneUse()) {
15019 SDValue N00 = N0.getOperand(0);
15020 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15022 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15023 if (!C || C->getZExtValue() != 1)
15025 return DAG.getNode(ISD::AND, dl, VT,
15026 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15027 N00.getOperand(0), N00.getOperand(1)),
15028 DAG.getConstant(1, VT));
15031 // Optimize vectors in AVX mode:
15034 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15035 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15036 // Concat upper and lower parts.
15039 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15040 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15041 // Concat upper and lower parts.
15043 if (!DCI.isBeforeLegalizeOps())
15046 if (!Subtarget->hasAVX())
15049 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15050 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15052 if (Subtarget->hasAVX2())
15053 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15055 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15056 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15057 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15059 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15060 VT.getVectorNumElements()/2);
15062 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15063 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15065 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15071 // Optimize x == -y --> x+y == 0
15072 // x != -y --> x+y != 0
15073 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15074 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15075 SDValue LHS = N->getOperand(0);
15076 SDValue RHS = N->getOperand(1);
15078 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15079 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15080 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15081 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15082 LHS.getValueType(), RHS, LHS.getOperand(1));
15083 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15084 addV, DAG.getConstant(0, addV.getValueType()), CC);
15086 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15088 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15089 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15090 RHS.getValueType(), LHS, RHS.getOperand(1));
15091 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15092 addV, DAG.getConstant(0, addV.getValueType()), CC);
15097 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15098 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15099 unsigned X86CC = N->getConstantOperandVal(0);
15100 SDValue EFLAG = N->getOperand(1);
15101 DebugLoc DL = N->getDebugLoc();
15103 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15104 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15106 if (X86CC == X86::COND_B)
15107 return DAG.getNode(ISD::AND, DL, MVT::i8,
15108 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15109 DAG.getConstant(X86CC, MVT::i8), EFLAG),
15110 DAG.getConstant(1, MVT::i8));
15115 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15116 SDValue Op0 = N->getOperand(0);
15117 EVT InVT = Op0->getValueType(0);
15119 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15120 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15121 DebugLoc dl = N->getDebugLoc();
15122 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15123 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15124 // Notice that we use SINT_TO_FP because we know that the high bits
15125 // are zero and SINT_TO_FP is better supported by the hardware.
15126 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15132 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15133 const X86TargetLowering *XTLI) {
15134 SDValue Op0 = N->getOperand(0);
15135 EVT InVT = Op0->getValueType(0);
15137 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15138 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15139 DebugLoc dl = N->getDebugLoc();
15140 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15141 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15142 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15145 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15146 // a 32-bit target where SSE doesn't support i64->FP operations.
15147 if (Op0.getOpcode() == ISD::LOAD) {
15148 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15149 EVT VT = Ld->getValueType(0);
15150 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15151 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15152 !XTLI->getSubtarget()->is64Bit() &&
15153 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15154 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15155 Ld->getChain(), Op0, DAG);
15156 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15163 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15164 EVT VT = N->getValueType(0);
15166 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15167 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15168 DebugLoc dl = N->getDebugLoc();
15169 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15170 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15171 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15177 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15178 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15179 X86TargetLowering::DAGCombinerInfo &DCI) {
15180 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15181 // the result is either zero or one (depending on the input carry bit).
15182 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15183 if (X86::isZeroNode(N->getOperand(0)) &&
15184 X86::isZeroNode(N->getOperand(1)) &&
15185 // We don't have a good way to replace an EFLAGS use, so only do this when
15187 SDValue(N, 1).use_empty()) {
15188 DebugLoc DL = N->getDebugLoc();
15189 EVT VT = N->getValueType(0);
15190 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15191 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15192 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15193 DAG.getConstant(X86::COND_B,MVT::i8),
15195 DAG.getConstant(1, VT));
15196 return DCI.CombineTo(N, Res1, CarryOut);
15202 // fold (add Y, (sete X, 0)) -> adc 0, Y
15203 // (add Y, (setne X, 0)) -> sbb -1, Y
15204 // (sub (sete X, 0), Y) -> sbb 0, Y
15205 // (sub (setne X, 0), Y) -> adc -1, Y
15206 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15207 DebugLoc DL = N->getDebugLoc();
15209 // Look through ZExts.
15210 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15211 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15214 SDValue SetCC = Ext.getOperand(0);
15215 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15218 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15219 if (CC != X86::COND_E && CC != X86::COND_NE)
15222 SDValue Cmp = SetCC.getOperand(1);
15223 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15224 !X86::isZeroNode(Cmp.getOperand(1)) ||
15225 !Cmp.getOperand(0).getValueType().isInteger())
15228 SDValue CmpOp0 = Cmp.getOperand(0);
15229 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15230 DAG.getConstant(1, CmpOp0.getValueType()));
15232 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15233 if (CC == X86::COND_NE)
15234 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15235 DL, OtherVal.getValueType(), OtherVal,
15236 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15237 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15238 DL, OtherVal.getValueType(), OtherVal,
15239 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15242 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15243 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15244 const X86Subtarget *Subtarget) {
15245 EVT VT = N->getValueType(0);
15246 SDValue Op0 = N->getOperand(0);
15247 SDValue Op1 = N->getOperand(1);
15249 // Try to synthesize horizontal adds from adds of shuffles.
15250 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15251 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15252 isHorizontalBinOp(Op0, Op1, true))
15253 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15255 return OptimizeConditionalInDecrement(N, DAG);
15258 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15259 const X86Subtarget *Subtarget) {
15260 SDValue Op0 = N->getOperand(0);
15261 SDValue Op1 = N->getOperand(1);
15263 // X86 can't encode an immediate LHS of a sub. See if we can push the
15264 // negation into a preceding instruction.
15265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15266 // If the RHS of the sub is a XOR with one use and a constant, invert the
15267 // immediate. Then add one to the LHS of the sub so we can turn
15268 // X-Y -> X+~Y+1, saving one register.
15269 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15270 isa<ConstantSDNode>(Op1.getOperand(1))) {
15271 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15272 EVT VT = Op0.getValueType();
15273 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15275 DAG.getConstant(~XorC, VT));
15276 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15277 DAG.getConstant(C->getAPIntValue()+1, VT));
15281 // Try to synthesize horizontal adds from adds of shuffles.
15282 EVT VT = N->getValueType(0);
15283 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15284 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15285 isHorizontalBinOp(Op0, Op1, true))
15286 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15288 return OptimizeConditionalInDecrement(N, DAG);
15291 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15292 DAGCombinerInfo &DCI) const {
15293 SelectionDAG &DAG = DCI.DAG;
15294 switch (N->getOpcode()) {
15296 case ISD::EXTRACT_VECTOR_ELT:
15297 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15299 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15300 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
15301 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
15302 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
15303 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
15304 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
15307 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
15308 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
15309 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
15310 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
15311 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
15312 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
15313 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
15314 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
15315 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
15316 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
15317 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
15319 case X86ISD::FOR: return PerformFORCombine(N, DAG);
15320 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
15321 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
15322 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
15323 case ISD::ANY_EXTEND:
15324 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
15325 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
15326 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI);
15327 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
15328 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
15329 case X86ISD::SHUFP: // Handle all target specific shuffles
15330 case X86ISD::PALIGN:
15331 case X86ISD::UNPCKH:
15332 case X86ISD::UNPCKL:
15333 case X86ISD::MOVHLPS:
15334 case X86ISD::MOVLHPS:
15335 case X86ISD::PSHUFD:
15336 case X86ISD::PSHUFHW:
15337 case X86ISD::PSHUFLW:
15338 case X86ISD::MOVSS:
15339 case X86ISD::MOVSD:
15340 case X86ISD::VPERMILP:
15341 case X86ISD::VPERM2X128:
15342 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15348 /// isTypeDesirableForOp - Return true if the target has native support for
15349 /// the specified value type and it is 'desirable' to use the type for the
15350 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15351 /// instruction encodings are longer and some i16 instructions are slow.
15352 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15353 if (!isTypeLegal(VT))
15355 if (VT != MVT::i16)
15362 case ISD::SIGN_EXTEND:
15363 case ISD::ZERO_EXTEND:
15364 case ISD::ANY_EXTEND:
15377 /// IsDesirableToPromoteOp - This method query the target whether it is
15378 /// beneficial for dag combiner to promote the specified node. If true, it
15379 /// should return the desired promotion type by reference.
15380 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15381 EVT VT = Op.getValueType();
15382 if (VT != MVT::i16)
15385 bool Promote = false;
15386 bool Commute = false;
15387 switch (Op.getOpcode()) {
15390 LoadSDNode *LD = cast<LoadSDNode>(Op);
15391 // If the non-extending load has a single use and it's not live out, then it
15392 // might be folded.
15393 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15394 Op.hasOneUse()*/) {
15395 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15396 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15397 // The only case where we'd want to promote LOAD (rather then it being
15398 // promoted as an operand is when it's only use is liveout.
15399 if (UI->getOpcode() != ISD::CopyToReg)
15406 case ISD::SIGN_EXTEND:
15407 case ISD::ZERO_EXTEND:
15408 case ISD::ANY_EXTEND:
15413 SDValue N0 = Op.getOperand(0);
15414 // Look out for (store (shl (load), x)).
15415 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15428 SDValue N0 = Op.getOperand(0);
15429 SDValue N1 = Op.getOperand(1);
15430 if (!Commute && MayFoldLoad(N1))
15432 // Avoid disabling potential load folding opportunities.
15433 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15435 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15445 //===----------------------------------------------------------------------===//
15446 // X86 Inline Assembly Support
15447 //===----------------------------------------------------------------------===//
15450 // Helper to match a string separated by whitespace.
15451 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15452 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15454 for (unsigned i = 0, e = args.size(); i != e; ++i) {
15455 StringRef piece(*args[i]);
15456 if (!s.startswith(piece)) // Check if the piece matches.
15459 s = s.substr(piece.size());
15460 StringRef::size_type pos = s.find_first_not_of(" \t");
15461 if (pos == 0) // We matched a prefix.
15469 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15472 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15473 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15475 std::string AsmStr = IA->getAsmString();
15477 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15478 if (!Ty || Ty->getBitWidth() % 16 != 0)
15481 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15482 SmallVector<StringRef, 4> AsmPieces;
15483 SplitString(AsmStr, AsmPieces, ";\n");
15485 switch (AsmPieces.size()) {
15486 default: return false;
15488 // FIXME: this should verify that we are targeting a 486 or better. If not,
15489 // we will turn this bswap into something that will be lowered to logical
15490 // ops instead of emitting the bswap asm. For now, we don't support 486 or
15491 // lower so don't worry about this.
15493 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15494 matchAsm(AsmPieces[0], "bswapl", "$0") ||
15495 matchAsm(AsmPieces[0], "bswapq", "$0") ||
15496 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15497 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15498 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15499 // No need to check constraints, nothing other than the equivalent of
15500 // "=r,0" would be valid here.
15501 return IntrinsicLowering::LowerToByteSwap(CI);
15504 // rorw $$8, ${0:w} --> llvm.bswap.i16
15505 if (CI->getType()->isIntegerTy(16) &&
15506 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15507 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15508 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15510 const std::string &ConstraintsStr = IA->getConstraintString();
15511 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15512 std::sort(AsmPieces.begin(), AsmPieces.end());
15513 if (AsmPieces.size() == 4 &&
15514 AsmPieces[0] == "~{cc}" &&
15515 AsmPieces[1] == "~{dirflag}" &&
15516 AsmPieces[2] == "~{flags}" &&
15517 AsmPieces[3] == "~{fpsr}")
15518 return IntrinsicLowering::LowerToByteSwap(CI);
15522 if (CI->getType()->isIntegerTy(32) &&
15523 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15524 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15525 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15526 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15528 const std::string &ConstraintsStr = IA->getConstraintString();
15529 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15530 std::sort(AsmPieces.begin(), AsmPieces.end());
15531 if (AsmPieces.size() == 4 &&
15532 AsmPieces[0] == "~{cc}" &&
15533 AsmPieces[1] == "~{dirflag}" &&
15534 AsmPieces[2] == "~{flags}" &&
15535 AsmPieces[3] == "~{fpsr}")
15536 return IntrinsicLowering::LowerToByteSwap(CI);
15539 if (CI->getType()->isIntegerTy(64)) {
15540 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15541 if (Constraints.size() >= 2 &&
15542 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15543 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15544 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
15545 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15546 matchAsm(AsmPieces[1], "bswap", "%edx") &&
15547 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15548 return IntrinsicLowering::LowerToByteSwap(CI);
15558 /// getConstraintType - Given a constraint letter, return the type of
15559 /// constraint it is for this target.
15560 X86TargetLowering::ConstraintType
15561 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15562 if (Constraint.size() == 1) {
15563 switch (Constraint[0]) {
15574 return C_RegisterClass;
15598 return TargetLowering::getConstraintType(Constraint);
15601 /// Examine constraint type and operand type and determine a weight value.
15602 /// This object must already have been set up with the operand type
15603 /// and the current alternative constraint selected.
15604 TargetLowering::ConstraintWeight
15605 X86TargetLowering::getSingleConstraintMatchWeight(
15606 AsmOperandInfo &info, const char *constraint) const {
15607 ConstraintWeight weight = CW_Invalid;
15608 Value *CallOperandVal = info.CallOperandVal;
15609 // If we don't have a value, we can't do a match,
15610 // but allow it at the lowest weight.
15611 if (CallOperandVal == NULL)
15613 Type *type = CallOperandVal->getType();
15614 // Look at the constraint type.
15615 switch (*constraint) {
15617 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15628 if (CallOperandVal->getType()->isIntegerTy())
15629 weight = CW_SpecificReg;
15634 if (type->isFloatingPointTy())
15635 weight = CW_SpecificReg;
15638 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15639 weight = CW_SpecificReg;
15643 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15644 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15645 weight = CW_Register;
15648 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15649 if (C->getZExtValue() <= 31)
15650 weight = CW_Constant;
15654 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15655 if (C->getZExtValue() <= 63)
15656 weight = CW_Constant;
15660 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15661 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15662 weight = CW_Constant;
15666 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15667 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15668 weight = CW_Constant;
15672 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15673 if (C->getZExtValue() <= 3)
15674 weight = CW_Constant;
15678 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15679 if (C->getZExtValue() <= 0xff)
15680 weight = CW_Constant;
15685 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15686 weight = CW_Constant;
15690 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15691 if ((C->getSExtValue() >= -0x80000000LL) &&
15692 (C->getSExtValue() <= 0x7fffffffLL))
15693 weight = CW_Constant;
15697 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15698 if (C->getZExtValue() <= 0xffffffff)
15699 weight = CW_Constant;
15706 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15707 /// with another that has more specific requirements based on the type of the
15708 /// corresponding operand.
15709 const char *X86TargetLowering::
15710 LowerXConstraint(EVT ConstraintVT) const {
15711 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15712 // 'f' like normal targets.
15713 if (ConstraintVT.isFloatingPoint()) {
15714 if (Subtarget->hasSSE2())
15716 if (Subtarget->hasSSE1())
15720 return TargetLowering::LowerXConstraint(ConstraintVT);
15723 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15724 /// vector. If it is invalid, don't add anything to Ops.
15725 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15726 std::string &Constraint,
15727 std::vector<SDValue>&Ops,
15728 SelectionDAG &DAG) const {
15729 SDValue Result(0, 0);
15731 // Only support length 1 constraints for now.
15732 if (Constraint.length() > 1) return;
15734 char ConstraintLetter = Constraint[0];
15735 switch (ConstraintLetter) {
15738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15739 if (C->getZExtValue() <= 31) {
15740 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15746 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15747 if (C->getZExtValue() <= 63) {
15748 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15754 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15755 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15756 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15762 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15763 if (C->getZExtValue() <= 255) {
15764 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15770 // 32-bit signed value
15771 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15772 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15773 C->getSExtValue())) {
15774 // Widen to 64 bits here to get it sign extended.
15775 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15778 // FIXME gcc accepts some relocatable values here too, but only in certain
15779 // memory models; it's complicated.
15784 // 32-bit unsigned value
15785 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15786 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15787 C->getZExtValue())) {
15788 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15792 // FIXME gcc accepts some relocatable values here too, but only in certain
15793 // memory models; it's complicated.
15797 // Literal immediates are always ok.
15798 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15799 // Widen to 64 bits here to get it sign extended.
15800 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15804 // In any sort of PIC mode addresses need to be computed at runtime by
15805 // adding in a register or some sort of table lookup. These can't
15806 // be used as immediates.
15807 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15810 // If we are in non-pic codegen mode, we allow the address of a global (with
15811 // an optional displacement) to be used with 'i'.
15812 GlobalAddressSDNode *GA = 0;
15813 int64_t Offset = 0;
15815 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15817 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15818 Offset += GA->getOffset();
15820 } else if (Op.getOpcode() == ISD::ADD) {
15821 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15822 Offset += C->getZExtValue();
15823 Op = Op.getOperand(0);
15826 } else if (Op.getOpcode() == ISD::SUB) {
15827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15828 Offset += -C->getZExtValue();
15829 Op = Op.getOperand(0);
15834 // Otherwise, this isn't something we can handle, reject it.
15838 const GlobalValue *GV = GA->getGlobal();
15839 // If we require an extra load to get this address, as in PIC mode, we
15840 // can't accept it.
15841 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15842 getTargetMachine())))
15845 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15846 GA->getValueType(0), Offset);
15851 if (Result.getNode()) {
15852 Ops.push_back(Result);
15855 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15858 std::pair<unsigned, const TargetRegisterClass*>
15859 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15861 // First, see if this is a constraint that directly corresponds to an LLVM
15863 if (Constraint.size() == 1) {
15864 // GCC Constraint Letters
15865 switch (Constraint[0]) {
15867 // TODO: Slight differences here in allocation order and leaving
15868 // RIP in the class. Do they matter any more here than they do
15869 // in the normal allocation?
15870 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15871 if (Subtarget->is64Bit()) {
15872 if (VT == MVT::i32 || VT == MVT::f32)
15873 return std::make_pair(0U, &X86::GR32RegClass);
15874 if (VT == MVT::i16)
15875 return std::make_pair(0U, &X86::GR16RegClass);
15876 if (VT == MVT::i8 || VT == MVT::i1)
15877 return std::make_pair(0U, &X86::GR8RegClass);
15878 if (VT == MVT::i64 || VT == MVT::f64)
15879 return std::make_pair(0U, &X86::GR64RegClass);
15882 // 32-bit fallthrough
15883 case 'Q': // Q_REGS
15884 if (VT == MVT::i32 || VT == MVT::f32)
15885 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15886 if (VT == MVT::i16)
15887 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15888 if (VT == MVT::i8 || VT == MVT::i1)
15889 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15890 if (VT == MVT::i64)
15891 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15893 case 'r': // GENERAL_REGS
15894 case 'l': // INDEX_REGS
15895 if (VT == MVT::i8 || VT == MVT::i1)
15896 return std::make_pair(0U, &X86::GR8RegClass);
15897 if (VT == MVT::i16)
15898 return std::make_pair(0U, &X86::GR16RegClass);
15899 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15900 return std::make_pair(0U, &X86::GR32RegClass);
15901 return std::make_pair(0U, &X86::GR64RegClass);
15902 case 'R': // LEGACY_REGS
15903 if (VT == MVT::i8 || VT == MVT::i1)
15904 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
15905 if (VT == MVT::i16)
15906 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
15907 if (VT == MVT::i32 || !Subtarget->is64Bit())
15908 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
15909 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
15910 case 'f': // FP Stack registers.
15911 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15912 // value to the correct fpstack register class.
15913 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15914 return std::make_pair(0U, &X86::RFP32RegClass);
15915 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15916 return std::make_pair(0U, &X86::RFP64RegClass);
15917 return std::make_pair(0U, &X86::RFP80RegClass);
15918 case 'y': // MMX_REGS if MMX allowed.
15919 if (!Subtarget->hasMMX()) break;
15920 return std::make_pair(0U, &X86::VR64RegClass);
15921 case 'Y': // SSE_REGS if SSE2 allowed
15922 if (!Subtarget->hasSSE2()) break;
15924 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15925 if (!Subtarget->hasSSE1()) break;
15927 switch (VT.getSimpleVT().SimpleTy) {
15929 // Scalar SSE types.
15932 return std::make_pair(0U, &X86::FR32RegClass);
15935 return std::make_pair(0U, &X86::FR64RegClass);
15943 return std::make_pair(0U, &X86::VR128RegClass);
15951 return std::make_pair(0U, &X86::VR256RegClass);
15957 // Use the default implementation in TargetLowering to convert the register
15958 // constraint into a member of a register class.
15959 std::pair<unsigned, const TargetRegisterClass*> Res;
15960 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15962 // Not found as a standard register?
15963 if (Res.second == 0) {
15964 // Map st(0) -> st(7) -> ST0
15965 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15966 tolower(Constraint[1]) == 's' &&
15967 tolower(Constraint[2]) == 't' &&
15968 Constraint[3] == '(' &&
15969 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15970 Constraint[5] == ')' &&
15971 Constraint[6] == '}') {
15973 Res.first = X86::ST0+Constraint[4]-'0';
15974 Res.second = &X86::RFP80RegClass;
15978 // GCC allows "st(0)" to be called just plain "st".
15979 if (StringRef("{st}").equals_lower(Constraint)) {
15980 Res.first = X86::ST0;
15981 Res.second = &X86::RFP80RegClass;
15986 if (StringRef("{flags}").equals_lower(Constraint)) {
15987 Res.first = X86::EFLAGS;
15988 Res.second = &X86::CCRRegClass;
15992 // 'A' means EAX + EDX.
15993 if (Constraint == "A") {
15994 Res.first = X86::EAX;
15995 Res.second = &X86::GR32_ADRegClass;
16001 // Otherwise, check to see if this is a register class of the wrong value
16002 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16003 // turn into {ax},{dx}.
16004 if (Res.second->hasType(VT))
16005 return Res; // Correct type already, nothing to do.
16007 // All of the single-register GCC register classes map their values onto
16008 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16009 // really want an 8-bit or 32-bit register, map to the appropriate register
16010 // class and return the appropriate register.
16011 if (Res.second == &X86::GR16RegClass) {
16012 if (VT == MVT::i8) {
16013 unsigned DestReg = 0;
16014 switch (Res.first) {
16016 case X86::AX: DestReg = X86::AL; break;
16017 case X86::DX: DestReg = X86::DL; break;
16018 case X86::CX: DestReg = X86::CL; break;
16019 case X86::BX: DestReg = X86::BL; break;
16022 Res.first = DestReg;
16023 Res.second = &X86::GR8RegClass;
16025 } else if (VT == MVT::i32) {
16026 unsigned DestReg = 0;
16027 switch (Res.first) {
16029 case X86::AX: DestReg = X86::EAX; break;
16030 case X86::DX: DestReg = X86::EDX; break;
16031 case X86::CX: DestReg = X86::ECX; break;
16032 case X86::BX: DestReg = X86::EBX; break;
16033 case X86::SI: DestReg = X86::ESI; break;
16034 case X86::DI: DestReg = X86::EDI; break;
16035 case X86::BP: DestReg = X86::EBP; break;
16036 case X86::SP: DestReg = X86::ESP; break;
16039 Res.first = DestReg;
16040 Res.second = &X86::GR32RegClass;
16042 } else if (VT == MVT::i64) {
16043 unsigned DestReg = 0;
16044 switch (Res.first) {
16046 case X86::AX: DestReg = X86::RAX; break;
16047 case X86::DX: DestReg = X86::RDX; break;
16048 case X86::CX: DestReg = X86::RCX; break;
16049 case X86::BX: DestReg = X86::RBX; break;
16050 case X86::SI: DestReg = X86::RSI; break;
16051 case X86::DI: DestReg = X86::RDI; break;
16052 case X86::BP: DestReg = X86::RBP; break;
16053 case X86::SP: DestReg = X86::RSP; break;
16056 Res.first = DestReg;
16057 Res.second = &X86::GR64RegClass;
16060 } else if (Res.second == &X86::FR32RegClass ||
16061 Res.second == &X86::FR64RegClass ||
16062 Res.second == &X86::VR128RegClass) {
16063 // Handle references to XMM physical registers that got mapped into the
16064 // wrong class. This can happen with constraints like {xmm0} where the
16065 // target independent register mapper will just pick the first match it can
16066 // find, ignoring the required type.
16068 if (VT == MVT::f32 || VT == MVT::i32)
16069 Res.second = &X86::FR32RegClass;
16070 else if (VT == MVT::f64 || VT == MVT::i64)
16071 Res.second = &X86::FR64RegClass;
16072 else if (X86::VR128RegClass.hasType(VT))
16073 Res.second = &X86::VR128RegClass;
16074 else if (X86::VR256RegClass.hasType(VT))
16075 Res.second = &X86::VR256RegClass;