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"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
163 RegInfo = TM.getRegisterInfo();
164 TD = getTargetData();
166 // Set up the TargetLowering object.
167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
169 // X86 is weird, it always uses i8 for shift amounts and setcc results.
170 setBooleanContents(ZeroOrOneBooleanContent);
171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 // For 64-bit since we have so many registers use the ILP scheduler, for
175 // 32-bit code use the register pressure specific scheduling.
176 // For Atom, always use ILP scheduling.
177 if (Subtarget->isAtom())
178 setSchedulingPreference(Sched::ILP);
179 else if (Subtarget->is64Bit())
180 setSchedulingPreference(Sched::ILP);
182 setSchedulingPreference(Sched::RegPressure);
183 setStackPointerRegisterToSaveRestore(X86StackPtr);
185 // Bypass i32 with i8 on Atom when compiling with O2
186 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187 addBypassSlowDivType(Type::getInt32Ty(getGlobalContext()), Type::getInt8Ty(getGlobalContext()));
189 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190 // Setup Windows compiler runtime calls.
191 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193 setLibcallName(RTLIB::SREM_I64, "_allrem");
194 setLibcallName(RTLIB::UREM_I64, "_aullrem");
195 setLibcallName(RTLIB::MUL_I64, "_allmul");
196 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
202 // The _ftol2 runtime function has an unusual calling conv, which
203 // is modeled by a special pseudo-instruction.
204 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
210 if (Subtarget->isTargetDarwin()) {
211 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212 setUseUnderscoreSetJmp(false);
213 setUseUnderscoreLongJmp(false);
214 } else if (Subtarget->isTargetMingw()) {
215 // MS runtime is weird: it exports _setjmp, but longjmp!
216 setUseUnderscoreSetJmp(true);
217 setUseUnderscoreLongJmp(false);
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(true);
223 // Set up the register classes.
224 addRegisterClass(MVT::i8, &X86::GR8RegClass);
225 addRegisterClass(MVT::i16, &X86::GR16RegClass);
226 addRegisterClass(MVT::i32, &X86::GR32RegClass);
227 if (Subtarget->is64Bit())
228 addRegisterClass(MVT::i64, &X86::GR64RegClass);
230 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232 // We don't accept any truncstore of integer registers.
233 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
240 // SETOEQ and SETUNE require checking two conditions.
241 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 } else if (!TM.Options.UseSoftFloat) {
258 // We have an algorithm for SSE2->double, and we turn this into a
259 // 64-bit FILD followed by conditional FADD for other targets.
260 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
261 // We have an algorithm for SSE2, and we turn this into a 64-bit
262 // FILD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
266 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
271 if (!TM.Options.UseSoftFloat) {
272 // SSE has no i16 to fp conversion, only i32
273 if (X86ScalarSSEf32) {
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
275 // f32 and f64 cases are Legal, f80 case is not
276 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
283 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
289 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
291 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
294 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
296 if (X86ScalarSSEf32) {
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
298 // f32 and f64 cases are Legal, f80 case is not
299 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
307 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
313 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
314 } else if (!TM.Options.UseSoftFloat) {
315 // Since AVX is a superset of SSE3, only check for SSE here.
316 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317 // Expand FP_TO_UINT into a select.
318 // FIXME: We would like to use a Custom expander here eventually to do
319 // the optimal thing for SSE vs. the default expansion in the legalizer.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
322 // With SSE3 we can use fisttpll to convert to a signed i64; without
323 // SSE, we're stuck with a fistpll.
324 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
327 if (isTargetFTOL()) {
328 // Use the _ftol2 runtime function, which has a pseudo-instruction
329 // to handle its weird calling convention.
330 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
333 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334 if (!X86ScalarSSEf64) {
335 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
336 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
339 // Without SSE, i64->f64 goes through memory.
340 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
344 // Scalar integer divide and remainder are lowered to use operations that
345 // produce two results, to match the available instructions. This exposes
346 // the two-result form to trivial CSE, which is able to combine x/y and x%y
347 // into a single instruction.
349 // Scalar integer multiply-high is also lowered to use two-result
350 // operations, to match the available instructions. However, plain multiply
351 // (low) operations are left as Legal, as there are single-result
352 // instructions for this in x86. Using the two-result multiply instructions
353 // when both high and low results are needed must be arranged by dagcombine.
354 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
356 setOperationAction(ISD::MULHS, VT, Expand);
357 setOperationAction(ISD::MULHU, VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::UDIV, VT, Expand);
360 setOperationAction(ISD::SREM, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
363 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364 setOperationAction(ISD::ADDC, VT, Custom);
365 setOperationAction(ISD::ADDE, VT, Custom);
366 setOperationAction(ISD::SUBC, VT, Custom);
367 setOperationAction(ISD::SUBE, VT, Custom);
370 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
371 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
372 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
373 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
374 if (Subtarget->is64Bit())
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
379 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f32 , Expand);
381 setOperationAction(ISD::FREM , MVT::f64 , Expand);
382 setOperationAction(ISD::FREM , MVT::f80 , Expand);
383 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
385 // Promote the i8 variants and force them on up to i32 which has a shorter
387 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
388 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
390 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
391 if (Subtarget->hasBMI()) {
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
393 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
397 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
398 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
399 if (Subtarget->is64Bit())
400 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
403 if (Subtarget->hasLZCNT()) {
404 // When promoting the i8 variants, force them to i32 for a shorter
406 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
407 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
409 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
411 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
412 if (Subtarget->is64Bit())
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
427 if (Subtarget->hasPOPCNT()) {
428 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
430 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
432 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
433 if (Subtarget->is64Bit())
434 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
437 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
438 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
440 // These should be promoted to a larger select which is supported.
441 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
442 // X86 wants to expand cmov itself.
443 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
445 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
448 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
451 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
457 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
459 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
462 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
463 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
464 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
465 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
466 if (Subtarget->is64Bit())
467 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
469 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
470 if (Subtarget->is64Bit()) {
471 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
472 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
473 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
474 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
475 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
477 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
479 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
480 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
481 if (Subtarget->is64Bit()) {
482 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
483 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
484 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
487 if (Subtarget->hasSSE1())
488 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
490 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
491 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
493 // On X86 and X86-64, atomic operations are lowered to locked instructions.
494 // Locked instructions, in turn, have implicit fence semantics (all memory
495 // operations are flushed before issuing the locked instruction, and they
496 // are not buffered), so we can fold away the common pattern of
497 // fence-atomic-fence.
498 setShouldFoldAtomicFences(true);
500 // Expand certain atomics
501 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
503 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
508 if (!Subtarget->is64Bit()) {
509 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
519 if (Subtarget->hasCmpxchg16b()) {
520 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
523 // FIXME - use subtarget debug flags
524 if (!Subtarget->isTargetDarwin() &&
525 !Subtarget->isTargetELF() &&
526 !Subtarget->isTargetCygMing()) {
527 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
530 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
531 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
532 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
533 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
534 if (Subtarget->is64Bit()) {
535 setExceptionPointerRegister(X86::RAX);
536 setExceptionSelectorRegister(X86::RDX);
538 setExceptionPointerRegister(X86::EAX);
539 setExceptionSelectorRegister(X86::EDX);
541 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
542 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
544 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
545 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
547 setOperationAction(ISD::TRAP, MVT::Other, Legal);
549 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
550 setOperationAction(ISD::VASTART , MVT::Other, Custom);
551 setOperationAction(ISD::VAEND , MVT::Other, Expand);
552 if (Subtarget->is64Bit()) {
553 setOperationAction(ISD::VAARG , MVT::Other, Custom);
554 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
556 setOperationAction(ISD::VAARG , MVT::Other, Expand);
557 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
560 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
561 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
563 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
564 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565 MVT::i64 : MVT::i32, Custom);
566 else if (TM.Options.EnableSegmentedStacks)
567 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568 MVT::i64 : MVT::i32, Custom);
570 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
571 MVT::i64 : MVT::i32, Expand);
573 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
574 // f32 and f64 use SSE.
575 // Set up the FP register classes.
576 addRegisterClass(MVT::f32, &X86::FR32RegClass);
577 addRegisterClass(MVT::f64, &X86::FR64RegClass);
579 // Use ANDPD to simulate FABS.
580 setOperationAction(ISD::FABS , MVT::f64, Custom);
581 setOperationAction(ISD::FABS , MVT::f32, Custom);
583 // Use XORP to simulate FNEG.
584 setOperationAction(ISD::FNEG , MVT::f64, Custom);
585 setOperationAction(ISD::FNEG , MVT::f32, Custom);
587 // Use ANDPD and ORPD to simulate FCOPYSIGN.
588 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
589 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
591 // Lower this to FGETSIGNx86 plus an AND.
592 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
593 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
595 // We don't support sin/cos/fmod
596 setOperationAction(ISD::FSIN , MVT::f64, Expand);
597 setOperationAction(ISD::FCOS , MVT::f64, Expand);
598 setOperationAction(ISD::FSIN , MVT::f32, Expand);
599 setOperationAction(ISD::FCOS , MVT::f32, Expand);
601 // Expand FP immediates into loads from the stack, except for the special
603 addLegalFPImmediate(APFloat(+0.0)); // xorpd
604 addLegalFPImmediate(APFloat(+0.0f)); // xorps
605 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
606 // Use SSE for f32, x87 for f64.
607 // Set up the FP register classes.
608 addRegisterClass(MVT::f32, &X86::FR32RegClass);
609 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
611 // Use ANDPS to simulate FABS.
612 setOperationAction(ISD::FABS , MVT::f32, Custom);
614 // Use XORP to simulate FNEG.
615 setOperationAction(ISD::FNEG , MVT::f32, Custom);
617 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
619 // Use ANDPS and ORPS to simulate FCOPYSIGN.
620 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
623 // We don't support sin/cos/fmod
624 setOperationAction(ISD::FSIN , MVT::f32, Expand);
625 setOperationAction(ISD::FCOS , MVT::f32, Expand);
627 // Special cases we handle for FP constants.
628 addLegalFPImmediate(APFloat(+0.0f)); // xorps
629 addLegalFPImmediate(APFloat(+0.0)); // FLD0
630 addLegalFPImmediate(APFloat(+1.0)); // FLD1
631 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
634 if (!TM.Options.UnsafeFPMath) {
635 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
636 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
638 } else if (!TM.Options.UseSoftFloat) {
639 // f32 and f64 in x87.
640 // Set up the FP register classes.
641 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
642 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
644 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
645 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
646 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
649 if (!TM.Options.UnsafeFPMath) {
650 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
651 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
652 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
653 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
655 addLegalFPImmediate(APFloat(+0.0)); // FLD0
656 addLegalFPImmediate(APFloat(+1.0)); // FLD1
657 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
658 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
659 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
660 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
661 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
662 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
665 // We don't support FMA.
666 setOperationAction(ISD::FMA, MVT::f64, Expand);
667 setOperationAction(ISD::FMA, MVT::f32, Expand);
669 // Long double always uses X87.
670 if (!TM.Options.UseSoftFloat) {
671 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
672 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
673 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
675 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
676 addLegalFPImmediate(TmpFlt); // FLD0
678 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
681 APFloat TmpFlt2(+1.0);
682 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
684 addLegalFPImmediate(TmpFlt2); // FLD1
685 TmpFlt2.changeSign();
686 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
689 if (!TM.Options.UnsafeFPMath) {
690 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
691 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
694 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
695 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
696 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
697 setOperationAction(ISD::FRINT, MVT::f80, Expand);
698 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
699 setOperationAction(ISD::FMA, MVT::f80, Expand);
702 // Always use a library call for pow.
703 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
704 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
705 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
707 setOperationAction(ISD::FLOG, MVT::f80, Expand);
708 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
709 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
710 setOperationAction(ISD::FEXP, MVT::f80, Expand);
711 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
713 // First set operation action for all vector types to either promote
714 // (for widening) or expand (for scalarization). Then we will selectively
715 // turn on ones that can be effectively codegen'd.
716 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
717 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
718 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
733 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
735 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
736 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
772 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
776 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
777 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
778 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
779 setTruncStoreAction((MVT::SimpleValueType)VT,
780 (MVT::SimpleValueType)InnerVT, Expand);
781 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
782 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
783 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
786 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
787 // with -msoft-float, disable use of MMX as well.
788 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
789 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
790 // No operations on x86mmx supported, everything uses intrinsics.
793 // MMX-sized vectors (other than x86mmx) are expected to be expanded
794 // into smaller operations.
795 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
796 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
797 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
798 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
799 setOperationAction(ISD::AND, MVT::v8i8, Expand);
800 setOperationAction(ISD::AND, MVT::v4i16, Expand);
801 setOperationAction(ISD::AND, MVT::v2i32, Expand);
802 setOperationAction(ISD::AND, MVT::v1i64, Expand);
803 setOperationAction(ISD::OR, MVT::v8i8, Expand);
804 setOperationAction(ISD::OR, MVT::v4i16, Expand);
805 setOperationAction(ISD::OR, MVT::v2i32, Expand);
806 setOperationAction(ISD::OR, MVT::v1i64, Expand);
807 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
808 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
809 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
810 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
813 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
814 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
816 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
817 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
818 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
819 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
820 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
821 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
822 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
823 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
825 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
826 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
828 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
829 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
830 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
831 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
832 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
833 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
834 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
835 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
836 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
837 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
839 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
843 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
845 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
846 // registers cannot be used even for integer operations.
847 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
848 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
849 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
850 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
852 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
853 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
854 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
855 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
856 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
857 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
858 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
859 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
860 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
861 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
862 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
863 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
864 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
865 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
866 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
867 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
868 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
870 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
871 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
872 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
873 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
875 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
876 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
877 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
878 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
879 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
881 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
882 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
883 MVT VT = (MVT::SimpleValueType)i;
884 // Do not attempt to custom lower non-power-of-2 vectors
885 if (!isPowerOf2_32(VT.getVectorNumElements()))
887 // Do not attempt to custom lower non-128-bit vectors
888 if (!VT.is128BitVector())
890 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
891 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
895 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
896 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
897 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
898 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
899 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
900 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
902 if (Subtarget->is64Bit()) {
903 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
904 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
907 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
908 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
909 MVT VT = (MVT::SimpleValueType)i;
911 // Do not attempt to promote non-128-bit vectors
912 if (!VT.is128BitVector())
915 setOperationAction(ISD::AND, VT, Promote);
916 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
917 setOperationAction(ISD::OR, VT, Promote);
918 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
919 setOperationAction(ISD::XOR, VT, Promote);
920 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
921 setOperationAction(ISD::LOAD, VT, Promote);
922 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
923 setOperationAction(ISD::SELECT, VT, Promote);
924 AddPromotedToType (ISD::SELECT, VT, 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);
938 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
941 if (Subtarget->hasSSE41()) {
942 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
943 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
944 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
945 setOperationAction(ISD::FRINT, MVT::f32, Legal);
946 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
947 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
948 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
949 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
950 setOperationAction(ISD::FRINT, MVT::f64, Legal);
951 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
953 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
954 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
956 // FIXME: Do we need to handle scalar-to-vector here?
957 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
959 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
960 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
961 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
962 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
963 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
965 // i8 and i16 vectors are custom , because the source register and source
966 // source memory operand types are not the same width. f32 vectors are
967 // custom since the immediate controlling the insert encodes additional
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
971 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
972 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
974 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
975 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
976 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
977 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
979 // FIXME: these should be Legal but thats only for the case where
980 // the index is constant. For now custom expand to deal with that.
981 if (Subtarget->is64Bit()) {
982 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
983 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
987 if (Subtarget->hasSSE2()) {
988 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
989 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
991 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
992 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
994 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
995 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
997 if (Subtarget->hasAVX2()) {
998 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
999 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1001 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1002 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1004 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1006 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1007 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1009 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1010 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1012 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1016 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1017 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1018 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1019 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1020 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1021 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1022 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1024 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1025 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1026 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1028 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1029 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1030 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1031 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1032 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1033 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1034 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1035 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1037 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1038 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1039 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1040 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1041 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1042 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1043 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1044 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1046 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1047 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1048 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1050 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1052 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1053 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1055 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1056 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1058 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1059 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1061 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1062 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1063 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1064 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1066 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1067 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1068 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1070 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1073 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1075 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1076 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1077 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1078 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1079 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1080 setOperationAction(ISD::FMA, MVT::f32, Custom);
1081 setOperationAction(ISD::FMA, MVT::f64, Custom);
1084 if (Subtarget->hasAVX2()) {
1085 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1086 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1087 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1088 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1090 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1091 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1092 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1093 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1095 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1096 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1097 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1098 // Don't lower v32i8 because there is no 128-bit byte mul
1100 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1102 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1103 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1105 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1106 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1108 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1110 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1111 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1112 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1113 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1115 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1116 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1117 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1118 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1120 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1121 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1122 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1123 // Don't lower v32i8 because there is no 128-bit byte mul
1125 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1126 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1128 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1129 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1131 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1134 // Custom lower several nodes for 256-bit types.
1135 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1136 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1137 MVT VT = (MVT::SimpleValueType)i;
1139 // Extract subvector is special because the value type
1140 // (result) is 128-bit but the source is 256-bit wide.
1141 if (VT.is128BitVector())
1142 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1144 // Do not attempt to custom lower other non-256-bit vectors
1145 if (!VT.is256BitVector())
1148 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1149 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1150 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1151 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1152 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1153 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1154 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1157 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1158 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1159 MVT VT = (MVT::SimpleValueType)i;
1161 // Do not attempt to promote non-256-bit vectors
1162 if (!VT.is256BitVector())
1165 setOperationAction(ISD::AND, VT, Promote);
1166 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1167 setOperationAction(ISD::OR, VT, Promote);
1168 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1169 setOperationAction(ISD::XOR, VT, Promote);
1170 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1171 setOperationAction(ISD::LOAD, VT, Promote);
1172 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1173 setOperationAction(ISD::SELECT, VT, Promote);
1174 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1178 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1179 // of this type with custom code.
1180 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1181 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1182 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1186 // We want to custom lower some of our intrinsics.
1187 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1188 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1191 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1192 // handle type legalization for these operations here.
1194 // FIXME: We really should do custom legalization for addition and
1195 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1196 // than generic legalization for 64-bit multiplication-with-overflow, though.
1197 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1198 // Add/Sub/Mul with overflow operations are custom lowered.
1200 setOperationAction(ISD::SADDO, VT, Custom);
1201 setOperationAction(ISD::UADDO, VT, Custom);
1202 setOperationAction(ISD::SSUBO, VT, Custom);
1203 setOperationAction(ISD::USUBO, VT, Custom);
1204 setOperationAction(ISD::SMULO, VT, Custom);
1205 setOperationAction(ISD::UMULO, VT, Custom);
1208 // There are no 8-bit 3-address imul/mul instructions
1209 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1210 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1212 if (!Subtarget->is64Bit()) {
1213 // These libcalls are not available in 32-bit.
1214 setLibcallName(RTLIB::SHL_I128, 0);
1215 setLibcallName(RTLIB::SRL_I128, 0);
1216 setLibcallName(RTLIB::SRA_I128, 0);
1219 // We have target-specific dag combine patterns for the following nodes:
1220 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1221 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1222 setTargetDAGCombine(ISD::VSELECT);
1223 setTargetDAGCombine(ISD::SELECT);
1224 setTargetDAGCombine(ISD::SHL);
1225 setTargetDAGCombine(ISD::SRA);
1226 setTargetDAGCombine(ISD::SRL);
1227 setTargetDAGCombine(ISD::OR);
1228 setTargetDAGCombine(ISD::AND);
1229 setTargetDAGCombine(ISD::ADD);
1230 setTargetDAGCombine(ISD::FADD);
1231 setTargetDAGCombine(ISD::FSUB);
1232 setTargetDAGCombine(ISD::FMA);
1233 setTargetDAGCombine(ISD::SUB);
1234 setTargetDAGCombine(ISD::LOAD);
1235 setTargetDAGCombine(ISD::STORE);
1236 setTargetDAGCombine(ISD::ZERO_EXTEND);
1237 setTargetDAGCombine(ISD::ANY_EXTEND);
1238 setTargetDAGCombine(ISD::SIGN_EXTEND);
1239 setTargetDAGCombine(ISD::TRUNCATE);
1240 setTargetDAGCombine(ISD::UINT_TO_FP);
1241 setTargetDAGCombine(ISD::SINT_TO_FP);
1242 setTargetDAGCombine(ISD::SETCC);
1243 setTargetDAGCombine(ISD::FP_TO_SINT);
1244 if (Subtarget->is64Bit())
1245 setTargetDAGCombine(ISD::MUL);
1246 setTargetDAGCombine(ISD::XOR);
1248 computeRegisterProperties();
1250 // On Darwin, -Os means optimize for size without hurting performance,
1251 // do not reduce the limit.
1252 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1253 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1254 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1255 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1256 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1257 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1258 setPrefLoopAlignment(4); // 2^4 bytes.
1259 benefitFromCodePlacementOpt = true;
1261 // Predictable cmov don't hurt on atom because it's in-order.
1262 predictableSelectIsExpensive = !Subtarget->isAtom();
1264 setPrefFunctionAlignment(4); // 2^4 bytes.
1268 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1269 if (!VT.isVector()) return MVT::i8;
1270 return VT.changeVectorElementTypeToInteger();
1274 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1275 /// the desired ByVal argument alignment.
1276 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1279 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1280 if (VTy->getBitWidth() == 128)
1282 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1283 unsigned EltAlign = 0;
1284 getMaxByValAlign(ATy->getElementType(), EltAlign);
1285 if (EltAlign > MaxAlign)
1286 MaxAlign = EltAlign;
1287 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1288 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1289 unsigned EltAlign = 0;
1290 getMaxByValAlign(STy->getElementType(i), EltAlign);
1291 if (EltAlign > MaxAlign)
1292 MaxAlign = EltAlign;
1299 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1300 /// function arguments in the caller parameter area. For X86, aggregates
1301 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1302 /// are at 4-byte boundaries.
1303 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1304 if (Subtarget->is64Bit()) {
1305 // Max of 8 and alignment of type.
1306 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1313 if (Subtarget->hasSSE1())
1314 getMaxByValAlign(Ty, Align);
1318 /// getOptimalMemOpType - Returns the target specific optimal type for load
1319 /// and store operations as a result of memset, memcpy, and memmove
1320 /// lowering. If DstAlign is zero that means it's safe to destination
1321 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1322 /// means there isn't a need to check it against alignment requirement,
1323 /// probably because the source does not need to be loaded. If
1324 /// 'IsZeroVal' is true, that means it's safe to return a
1325 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1326 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1327 /// constant so it does not need to be loaded.
1328 /// It returns EVT::Other if the type should be determined using generic
1329 /// target-independent logic.
1331 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1332 unsigned DstAlign, unsigned SrcAlign,
1335 MachineFunction &MF) const {
1336 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1337 // linux. This is because the stack realignment code can't handle certain
1338 // cases like PR2962. This should be removed when PR2962 is fixed.
1339 const Function *F = MF.getFunction();
1341 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1343 (Subtarget->isUnalignedMemAccessFast() ||
1344 ((DstAlign == 0 || DstAlign >= 16) &&
1345 (SrcAlign == 0 || SrcAlign >= 16))) &&
1346 Subtarget->getStackAlignment() >= 16) {
1347 if (Subtarget->getStackAlignment() >= 32) {
1348 if (Subtarget->hasAVX2())
1350 if (Subtarget->hasAVX())
1353 if (Subtarget->hasSSE2())
1355 if (Subtarget->hasSSE1())
1357 } else if (!MemcpyStrSrc && Size >= 8 &&
1358 !Subtarget->is64Bit() &&
1359 Subtarget->getStackAlignment() >= 8 &&
1360 Subtarget->hasSSE2()) {
1361 // Do not use f64 to lower memcpy if source is string constant. It's
1362 // better to use i32 to avoid the loads.
1366 if (Subtarget->is64Bit() && Size >= 8)
1371 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1372 /// current function. The returned value is a member of the
1373 /// MachineJumpTableInfo::JTEntryKind enum.
1374 unsigned X86TargetLowering::getJumpTableEncoding() const {
1375 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1377 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1378 Subtarget->isPICStyleGOT())
1379 return MachineJumpTableInfo::EK_Custom32;
1381 // Otherwise, use the normal jump table encoding heuristics.
1382 return TargetLowering::getJumpTableEncoding();
1386 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1387 const MachineBasicBlock *MBB,
1388 unsigned uid,MCContext &Ctx) const{
1389 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1390 Subtarget->isPICStyleGOT());
1391 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1393 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1394 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1397 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1399 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1400 SelectionDAG &DAG) const {
1401 if (!Subtarget->is64Bit())
1402 // This doesn't have DebugLoc associated with it, but is not really the
1403 // same as a Register.
1404 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1408 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1409 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1411 const MCExpr *X86TargetLowering::
1412 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1413 MCContext &Ctx) const {
1414 // X86-64 uses RIP relative addressing based on the jump table label.
1415 if (Subtarget->isPICStyleRIPRel())
1416 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1418 // Otherwise, the reference is relative to the PIC base.
1419 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1422 // FIXME: Why this routine is here? Move to RegInfo!
1423 std::pair<const TargetRegisterClass*, uint8_t>
1424 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1425 const TargetRegisterClass *RRC = 0;
1427 switch (VT.getSimpleVT().SimpleTy) {
1429 return TargetLowering::findRepresentativeClass(VT);
1430 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1431 RRC = Subtarget->is64Bit() ?
1432 (const TargetRegisterClass*)&X86::GR64RegClass :
1433 (const TargetRegisterClass*)&X86::GR32RegClass;
1436 RRC = &X86::VR64RegClass;
1438 case MVT::f32: case MVT::f64:
1439 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1440 case MVT::v4f32: case MVT::v2f64:
1441 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1443 RRC = &X86::VR128RegClass;
1446 return std::make_pair(RRC, Cost);
1449 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1450 unsigned &Offset) const {
1451 if (!Subtarget->isTargetLinux())
1454 if (Subtarget->is64Bit()) {
1455 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1457 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1470 //===----------------------------------------------------------------------===//
1471 // Return Value Calling Convention Implementation
1472 //===----------------------------------------------------------------------===//
1474 #include "X86GenCallingConv.inc"
1477 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1478 MachineFunction &MF, bool isVarArg,
1479 const SmallVectorImpl<ISD::OutputArg> &Outs,
1480 LLVMContext &Context) const {
1481 SmallVector<CCValAssign, 16> RVLocs;
1482 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1484 return CCInfo.CheckReturn(Outs, RetCC_X86);
1488 X86TargetLowering::LowerReturn(SDValue Chain,
1489 CallingConv::ID CallConv, bool isVarArg,
1490 const SmallVectorImpl<ISD::OutputArg> &Outs,
1491 const SmallVectorImpl<SDValue> &OutVals,
1492 DebugLoc dl, SelectionDAG &DAG) const {
1493 MachineFunction &MF = DAG.getMachineFunction();
1494 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1496 SmallVector<CCValAssign, 16> RVLocs;
1497 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1498 RVLocs, *DAG.getContext());
1499 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1501 // Add the regs to the liveout set for the function.
1502 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1503 for (unsigned i = 0; i != RVLocs.size(); ++i)
1504 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1505 MRI.addLiveOut(RVLocs[i].getLocReg());
1509 SmallVector<SDValue, 6> RetOps;
1510 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1511 // Operand #1 = Bytes To Pop
1512 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1515 // Copy the result values into the output registers.
1516 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1517 CCValAssign &VA = RVLocs[i];
1518 assert(VA.isRegLoc() && "Can only return in registers!");
1519 SDValue ValToCopy = OutVals[i];
1520 EVT ValVT = ValToCopy.getValueType();
1522 // Promote values to the appropriate types
1523 if (VA.getLocInfo() == CCValAssign::SExt)
1524 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1525 else if (VA.getLocInfo() == CCValAssign::ZExt)
1526 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1527 else if (VA.getLocInfo() == CCValAssign::AExt)
1528 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1529 else if (VA.getLocInfo() == CCValAssign::BCvt)
1530 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1532 // If this is x86-64, and we disabled SSE, we can't return FP values,
1533 // or SSE or MMX vectors.
1534 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1535 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1536 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1537 report_fatal_error("SSE register return with SSE disabled");
1539 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1540 // llvm-gcc has never done it right and no one has noticed, so this
1541 // should be OK for now.
1542 if (ValVT == MVT::f64 &&
1543 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1544 report_fatal_error("SSE2 register return with SSE2 disabled");
1546 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1547 // the RET instruction and handled by the FP Stackifier.
1548 if (VA.getLocReg() == X86::ST0 ||
1549 VA.getLocReg() == X86::ST1) {
1550 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1551 // change the value to the FP stack register class.
1552 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1553 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1554 RetOps.push_back(ValToCopy);
1555 // Don't emit a copytoreg.
1559 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1560 // which is returned in RAX / RDX.
1561 if (Subtarget->is64Bit()) {
1562 if (ValVT == MVT::x86mmx) {
1563 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1564 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1565 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1567 // If we don't have SSE2 available, convert to v4f32 so the generated
1568 // register is legal.
1569 if (!Subtarget->hasSSE2())
1570 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1575 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1576 Flag = Chain.getValue(1);
1579 // The x86-64 ABI for returning structs by value requires that we copy
1580 // the sret argument into %rax for the return. We saved the argument into
1581 // a virtual register in the entry block, so now we copy the value out
1583 if (Subtarget->is64Bit() &&
1584 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1585 MachineFunction &MF = DAG.getMachineFunction();
1586 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1587 unsigned Reg = FuncInfo->getSRetReturnReg();
1589 "SRetReturnReg should have been set in LowerFormalArguments().");
1590 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1592 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1593 Flag = Chain.getValue(1);
1595 // RAX now acts like a return value.
1596 MRI.addLiveOut(X86::RAX);
1599 RetOps[0] = Chain; // Update chain.
1601 // Add the flag if we have it.
1603 RetOps.push_back(Flag);
1605 return DAG.getNode(X86ISD::RET_FLAG, dl,
1606 MVT::Other, &RetOps[0], RetOps.size());
1609 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1610 if (N->getNumValues() != 1)
1612 if (!N->hasNUsesOfValue(1, 0))
1615 SDValue TCChain = Chain;
1616 SDNode *Copy = *N->use_begin();
1617 if (Copy->getOpcode() == ISD::CopyToReg) {
1618 // If the copy has a glue operand, we conservatively assume it isn't safe to
1619 // perform a tail call.
1620 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1622 TCChain = Copy->getOperand(0);
1623 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1626 bool HasRet = false;
1627 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1629 if (UI->getOpcode() != X86ISD::RET_FLAG)
1642 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1643 ISD::NodeType ExtendKind) const {
1645 // TODO: Is this also valid on 32-bit?
1646 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1647 ReturnMVT = MVT::i8;
1649 ReturnMVT = MVT::i32;
1651 EVT MinVT = getRegisterType(Context, ReturnMVT);
1652 return VT.bitsLT(MinVT) ? MinVT : VT;
1655 /// LowerCallResult - Lower the result values of a call into the
1656 /// appropriate copies out of appropriate physical registers.
1659 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1660 CallingConv::ID CallConv, bool isVarArg,
1661 const SmallVectorImpl<ISD::InputArg> &Ins,
1662 DebugLoc dl, SelectionDAG &DAG,
1663 SmallVectorImpl<SDValue> &InVals) const {
1665 // Assign locations to each value returned by this call.
1666 SmallVector<CCValAssign, 16> RVLocs;
1667 bool Is64Bit = Subtarget->is64Bit();
1668 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1669 getTargetMachine(), RVLocs, *DAG.getContext());
1670 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1672 // Copy all of the result registers out of their specified physreg.
1673 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1674 CCValAssign &VA = RVLocs[i];
1675 EVT CopyVT = VA.getValVT();
1677 // If this is x86-64, and we disabled SSE, we can't return FP values
1678 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1679 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1680 report_fatal_error("SSE register return with SSE disabled");
1685 // If this is a call to a function that returns an fp value on the floating
1686 // point stack, we must guarantee the value is popped from the stack, so
1687 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1688 // if the return value is not used. We use the FpPOP_RETVAL instruction
1690 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1691 // If we prefer to use the value in xmm registers, copy it out as f80 and
1692 // use a truncate to move it from fp stack reg to xmm reg.
1693 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1694 SDValue Ops[] = { Chain, InFlag };
1695 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1696 MVT::Other, MVT::Glue, Ops, 2), 1);
1697 Val = Chain.getValue(0);
1699 // Round the f80 to the right size, which also moves it to the appropriate
1701 if (CopyVT != VA.getValVT())
1702 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1703 // This truncation won't change the value.
1704 DAG.getIntPtrConstant(1));
1706 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1707 CopyVT, InFlag).getValue(1);
1708 Val = Chain.getValue(0);
1710 InFlag = Chain.getValue(2);
1711 InVals.push_back(Val);
1718 //===----------------------------------------------------------------------===//
1719 // C & StdCall & Fast Calling Convention implementation
1720 //===----------------------------------------------------------------------===//
1721 // StdCall calling convention seems to be standard for many Windows' API
1722 // routines and around. It differs from C calling convention just a little:
1723 // callee should clean up the stack, not caller. Symbols should be also
1724 // decorated in some fancy way :) It doesn't support any vector arguments.
1725 // For info on fast calling convention see Fast Calling Convention (tail call)
1726 // implementation LowerX86_32FastCCCallTo.
1728 /// CallIsStructReturn - Determines whether a call uses struct return
1730 enum StructReturnType {
1735 static StructReturnType
1736 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1738 return NotStructReturn;
1740 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1741 if (!Flags.isSRet())
1742 return NotStructReturn;
1743 if (Flags.isInReg())
1744 return RegStructReturn;
1745 return StackStructReturn;
1748 /// ArgsAreStructReturn - Determines whether a function uses struct
1749 /// return semantics.
1750 static StructReturnType
1751 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1753 return NotStructReturn;
1755 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1756 if (!Flags.isSRet())
1757 return NotStructReturn;
1758 if (Flags.isInReg())
1759 return RegStructReturn;
1760 return StackStructReturn;
1763 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1764 /// by "Src" to address "Dst" with size and alignment information specified by
1765 /// the specific parameter attribute. The copy will be passed as a byval
1766 /// function parameter.
1768 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1769 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1771 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1773 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1774 /*isVolatile*/false, /*AlwaysInline=*/true,
1775 MachinePointerInfo(), MachinePointerInfo());
1778 /// IsTailCallConvention - Return true if the calling convention is one that
1779 /// supports tail call optimization.
1780 static bool IsTailCallConvention(CallingConv::ID CC) {
1781 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1784 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1785 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1789 CallingConv::ID CalleeCC = CS.getCallingConv();
1790 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1796 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1797 /// a tailcall target by changing its ABI.
1798 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1799 bool GuaranteedTailCallOpt) {
1800 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1804 X86TargetLowering::LowerMemArgument(SDValue Chain,
1805 CallingConv::ID CallConv,
1806 const SmallVectorImpl<ISD::InputArg> &Ins,
1807 DebugLoc dl, SelectionDAG &DAG,
1808 const CCValAssign &VA,
1809 MachineFrameInfo *MFI,
1811 // Create the nodes corresponding to a load from this parameter slot.
1812 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1813 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1814 getTargetMachine().Options.GuaranteedTailCallOpt);
1815 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1818 // If value is passed by pointer we have address passed instead of the value
1820 if (VA.getLocInfo() == CCValAssign::Indirect)
1821 ValVT = VA.getLocVT();
1823 ValVT = VA.getValVT();
1825 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1826 // changed with more analysis.
1827 // In case of tail call optimization mark all arguments mutable. Since they
1828 // could be overwritten by lowering of arguments in case of a tail call.
1829 if (Flags.isByVal()) {
1830 unsigned Bytes = Flags.getByValSize();
1831 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1832 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1833 return DAG.getFrameIndex(FI, getPointerTy());
1835 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1836 VA.getLocMemOffset(), isImmutable);
1837 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1838 return DAG.getLoad(ValVT, dl, Chain, FIN,
1839 MachinePointerInfo::getFixedStack(FI),
1840 false, false, false, 0);
1845 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1846 CallingConv::ID CallConv,
1848 const SmallVectorImpl<ISD::InputArg> &Ins,
1851 SmallVectorImpl<SDValue> &InVals)
1853 MachineFunction &MF = DAG.getMachineFunction();
1854 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1856 const Function* Fn = MF.getFunction();
1857 if (Fn->hasExternalLinkage() &&
1858 Subtarget->isTargetCygMing() &&
1859 Fn->getName() == "main")
1860 FuncInfo->setForceFramePointer(true);
1862 MachineFrameInfo *MFI = MF.getFrameInfo();
1863 bool Is64Bit = Subtarget->is64Bit();
1864 bool IsWindows = Subtarget->isTargetWindows();
1865 bool IsWin64 = Subtarget->isTargetWin64();
1867 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1868 "Var args not supported with calling convention fastcc or ghc");
1870 // Assign locations to all of the incoming arguments.
1871 SmallVector<CCValAssign, 16> ArgLocs;
1872 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1873 ArgLocs, *DAG.getContext());
1875 // Allocate shadow area for Win64
1877 CCInfo.AllocateStack(32, 8);
1880 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1882 unsigned LastVal = ~0U;
1884 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1885 CCValAssign &VA = ArgLocs[i];
1886 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1888 assert(VA.getValNo() != LastVal &&
1889 "Don't support value assigned to multiple locs yet");
1891 LastVal = VA.getValNo();
1893 if (VA.isRegLoc()) {
1894 EVT RegVT = VA.getLocVT();
1895 const TargetRegisterClass *RC;
1896 if (RegVT == MVT::i32)
1897 RC = &X86::GR32RegClass;
1898 else if (Is64Bit && RegVT == MVT::i64)
1899 RC = &X86::GR64RegClass;
1900 else if (RegVT == MVT::f32)
1901 RC = &X86::FR32RegClass;
1902 else if (RegVT == MVT::f64)
1903 RC = &X86::FR64RegClass;
1904 else if (RegVT.is256BitVector())
1905 RC = &X86::VR256RegClass;
1906 else if (RegVT.is128BitVector())
1907 RC = &X86::VR128RegClass;
1908 else if (RegVT == MVT::x86mmx)
1909 RC = &X86::VR64RegClass;
1911 llvm_unreachable("Unknown argument type!");
1913 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1914 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1916 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1917 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1919 if (VA.getLocInfo() == CCValAssign::SExt)
1920 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1921 DAG.getValueType(VA.getValVT()));
1922 else if (VA.getLocInfo() == CCValAssign::ZExt)
1923 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1924 DAG.getValueType(VA.getValVT()));
1925 else if (VA.getLocInfo() == CCValAssign::BCvt)
1926 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1928 if (VA.isExtInLoc()) {
1929 // Handle MMX values passed in XMM regs.
1930 if (RegVT.isVector()) {
1931 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1934 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1937 assert(VA.isMemLoc());
1938 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1941 // If value is passed via pointer - do a load.
1942 if (VA.getLocInfo() == CCValAssign::Indirect)
1943 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1944 MachinePointerInfo(), false, false, false, 0);
1946 InVals.push_back(ArgValue);
1949 // The x86-64 ABI for returning structs by value requires that we copy
1950 // the sret argument into %rax for the return. Save the argument into
1951 // a virtual register so that we can access it from the return points.
1952 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1953 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1954 unsigned Reg = FuncInfo->getSRetReturnReg();
1956 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1957 FuncInfo->setSRetReturnReg(Reg);
1959 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1960 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1963 unsigned StackSize = CCInfo.getNextStackOffset();
1964 // Align stack specially for tail calls.
1965 if (FuncIsMadeTailCallSafe(CallConv,
1966 MF.getTarget().Options.GuaranteedTailCallOpt))
1967 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1969 // If the function takes variable number of arguments, make a frame index for
1970 // the start of the first vararg value... for expansion of llvm.va_start.
1972 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1973 CallConv != CallingConv::X86_ThisCall)) {
1974 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1977 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1979 // FIXME: We should really autogenerate these arrays
1980 static const uint16_t GPR64ArgRegsWin64[] = {
1981 X86::RCX, X86::RDX, X86::R8, X86::R9
1983 static const uint16_t GPR64ArgRegs64Bit[] = {
1984 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1986 static const uint16_t XMMArgRegs64Bit[] = {
1987 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1988 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1990 const uint16_t *GPR64ArgRegs;
1991 unsigned NumXMMRegs = 0;
1994 // The XMM registers which might contain var arg parameters are shadowed
1995 // in their paired GPR. So we only need to save the GPR to their home
1997 TotalNumIntRegs = 4;
1998 GPR64ArgRegs = GPR64ArgRegsWin64;
2000 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2001 GPR64ArgRegs = GPR64ArgRegs64Bit;
2003 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2006 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2009 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2010 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2011 "SSE register cannot be used when SSE is disabled!");
2012 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2013 NoImplicitFloatOps) &&
2014 "SSE register cannot be used when SSE is disabled!");
2015 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2016 !Subtarget->hasSSE1())
2017 // Kernel mode asks for SSE to be disabled, so don't push them
2019 TotalNumXMMRegs = 0;
2022 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2023 // Get to the caller-allocated home save location. Add 8 to account
2024 // for the return address.
2025 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2026 FuncInfo->setRegSaveFrameIndex(
2027 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2028 // Fixup to set vararg frame on shadow area (4 x i64).
2030 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2032 // For X86-64, if there are vararg parameters that are passed via
2033 // registers, then we must store them to their spots on the stack so
2034 // they may be loaded by deferencing the result of va_next.
2035 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2036 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2037 FuncInfo->setRegSaveFrameIndex(
2038 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2042 // Store the integer parameter registers.
2043 SmallVector<SDValue, 8> MemOps;
2044 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2046 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2047 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2048 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2049 DAG.getIntPtrConstant(Offset));
2050 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2051 &X86::GR64RegClass);
2052 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2054 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2055 MachinePointerInfo::getFixedStack(
2056 FuncInfo->getRegSaveFrameIndex(), Offset),
2058 MemOps.push_back(Store);
2062 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2063 // Now store the XMM (fp + vector) parameter registers.
2064 SmallVector<SDValue, 11> SaveXMMOps;
2065 SaveXMMOps.push_back(Chain);
2067 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2068 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2069 SaveXMMOps.push_back(ALVal);
2071 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2072 FuncInfo->getRegSaveFrameIndex()));
2073 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2074 FuncInfo->getVarArgsFPOffset()));
2076 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2077 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2078 &X86::VR128RegClass);
2079 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2080 SaveXMMOps.push_back(Val);
2082 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2084 &SaveXMMOps[0], SaveXMMOps.size()));
2087 if (!MemOps.empty())
2088 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2089 &MemOps[0], MemOps.size());
2093 // Some CCs need callee pop.
2094 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2095 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2096 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2098 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2099 // If this is an sret function, the return should pop the hidden pointer.
2100 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2101 argsAreStructReturn(Ins) == StackStructReturn)
2102 FuncInfo->setBytesToPopOnReturn(4);
2106 // RegSaveFrameIndex is X86-64 only.
2107 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2108 if (CallConv == CallingConv::X86_FastCall ||
2109 CallConv == CallingConv::X86_ThisCall)
2110 // fastcc functions can't have varargs.
2111 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2114 FuncInfo->setArgumentStackSize(StackSize);
2120 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2121 SDValue StackPtr, SDValue Arg,
2122 DebugLoc dl, SelectionDAG &DAG,
2123 const CCValAssign &VA,
2124 ISD::ArgFlagsTy Flags) const {
2125 unsigned LocMemOffset = VA.getLocMemOffset();
2126 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2127 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2128 if (Flags.isByVal())
2129 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2131 return DAG.getStore(Chain, dl, Arg, PtrOff,
2132 MachinePointerInfo::getStack(LocMemOffset),
2136 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2137 /// optimization is performed and it is required.
2139 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2140 SDValue &OutRetAddr, SDValue Chain,
2141 bool IsTailCall, bool Is64Bit,
2142 int FPDiff, DebugLoc dl) const {
2143 // Adjust the Return address stack slot.
2144 EVT VT = getPointerTy();
2145 OutRetAddr = getReturnAddressFrameIndex(DAG);
2147 // Load the "old" Return address.
2148 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2149 false, false, false, 0);
2150 return SDValue(OutRetAddr.getNode(), 1);
2153 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2154 /// optimization is performed and it is required (FPDiff!=0).
2156 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2157 SDValue Chain, SDValue RetAddrFrIdx,
2158 bool Is64Bit, int FPDiff, DebugLoc dl) {
2159 // Store the return address to the appropriate stack slot.
2160 if (!FPDiff) return Chain;
2161 // Calculate the new stack slot for the return address.
2162 int SlotSize = Is64Bit ? 8 : 4;
2163 int NewReturnAddrFI =
2164 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2165 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2166 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2167 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2168 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2174 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2175 SmallVectorImpl<SDValue> &InVals) const {
2176 SelectionDAG &DAG = CLI.DAG;
2177 DebugLoc &dl = CLI.DL;
2178 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2179 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2180 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2181 SDValue Chain = CLI.Chain;
2182 SDValue Callee = CLI.Callee;
2183 CallingConv::ID CallConv = CLI.CallConv;
2184 bool &isTailCall = CLI.IsTailCall;
2185 bool isVarArg = CLI.IsVarArg;
2187 MachineFunction &MF = DAG.getMachineFunction();
2188 bool Is64Bit = Subtarget->is64Bit();
2189 bool IsWin64 = Subtarget->isTargetWin64();
2190 bool IsWindows = Subtarget->isTargetWindows();
2191 StructReturnType SR = callIsStructReturn(Outs);
2192 bool IsSibcall = false;
2194 if (MF.getTarget().Options.DisableTailCalls)
2198 // Check if it's really possible to do a tail call.
2199 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2200 isVarArg, SR != NotStructReturn,
2201 MF.getFunction()->hasStructRetAttr(),
2202 Outs, OutVals, Ins, DAG);
2204 // Sibcalls are automatically detected tailcalls which do not require
2206 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2213 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2214 "Var args not supported with calling convention fastcc or ghc");
2216 // Analyze operands of the call, assigning locations to each operand.
2217 SmallVector<CCValAssign, 16> ArgLocs;
2218 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2219 ArgLocs, *DAG.getContext());
2221 // Allocate shadow area for Win64
2223 CCInfo.AllocateStack(32, 8);
2226 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2228 // Get a count of how many bytes are to be pushed on the stack.
2229 unsigned NumBytes = CCInfo.getNextStackOffset();
2231 // This is a sibcall. The memory operands are available in caller's
2232 // own caller's stack.
2234 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2235 IsTailCallConvention(CallConv))
2236 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2239 if (isTailCall && !IsSibcall) {
2240 // Lower arguments at fp - stackoffset + fpdiff.
2241 unsigned NumBytesCallerPushed =
2242 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2243 FPDiff = NumBytesCallerPushed - NumBytes;
2245 // Set the delta of movement of the returnaddr stackslot.
2246 // But only set if delta is greater than previous delta.
2247 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2248 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2252 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2254 SDValue RetAddrFrIdx;
2255 // Load return address for tail calls.
2256 if (isTailCall && FPDiff)
2257 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2258 Is64Bit, FPDiff, dl);
2260 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2261 SmallVector<SDValue, 8> MemOpChains;
2264 // Walk the register/memloc assignments, inserting copies/loads. In the case
2265 // of tail call optimization arguments are handle later.
2266 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2267 CCValAssign &VA = ArgLocs[i];
2268 EVT RegVT = VA.getLocVT();
2269 SDValue Arg = OutVals[i];
2270 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2271 bool isByVal = Flags.isByVal();
2273 // Promote the value if needed.
2274 switch (VA.getLocInfo()) {
2275 default: llvm_unreachable("Unknown loc info!");
2276 case CCValAssign::Full: break;
2277 case CCValAssign::SExt:
2278 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2280 case CCValAssign::ZExt:
2281 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2283 case CCValAssign::AExt:
2284 if (RegVT.is128BitVector()) {
2285 // Special case: passing MMX values in XMM registers.
2286 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2287 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2288 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2290 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2292 case CCValAssign::BCvt:
2293 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2295 case CCValAssign::Indirect: {
2296 // Store the argument.
2297 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2298 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2299 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2300 MachinePointerInfo::getFixedStack(FI),
2307 if (VA.isRegLoc()) {
2308 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2309 if (isVarArg && IsWin64) {
2310 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2311 // shadow reg if callee is a varargs function.
2312 unsigned ShadowReg = 0;
2313 switch (VA.getLocReg()) {
2314 case X86::XMM0: ShadowReg = X86::RCX; break;
2315 case X86::XMM1: ShadowReg = X86::RDX; break;
2316 case X86::XMM2: ShadowReg = X86::R8; break;
2317 case X86::XMM3: ShadowReg = X86::R9; break;
2320 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2322 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2323 assert(VA.isMemLoc());
2324 if (StackPtr.getNode() == 0)
2325 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2326 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2327 dl, DAG, VA, Flags));
2331 if (!MemOpChains.empty())
2332 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2333 &MemOpChains[0], MemOpChains.size());
2335 if (Subtarget->isPICStyleGOT()) {
2336 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2339 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2340 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2342 // If we are tail calling and generating PIC/GOT style code load the
2343 // address of the callee into ECX. The value in ecx is used as target of
2344 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2345 // for tail calls on PIC/GOT architectures. Normally we would just put the
2346 // address of GOT into ebx and then call target@PLT. But for tail calls
2347 // ebx would be restored (since ebx is callee saved) before jumping to the
2350 // Note: The actual moving to ECX is done further down.
2351 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2352 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2353 !G->getGlobal()->hasProtectedVisibility())
2354 Callee = LowerGlobalAddress(Callee, DAG);
2355 else if (isa<ExternalSymbolSDNode>(Callee))
2356 Callee = LowerExternalSymbol(Callee, DAG);
2360 if (Is64Bit && isVarArg && !IsWin64) {
2361 // From AMD64 ABI document:
2362 // For calls that may call functions that use varargs or stdargs
2363 // (prototype-less calls or calls to functions containing ellipsis (...) in
2364 // the declaration) %al is used as hidden argument to specify the number
2365 // of SSE registers used. The contents of %al do not need to match exactly
2366 // the number of registers, but must be an ubound on the number of SSE
2367 // registers used and is in the range 0 - 8 inclusive.
2369 // Count the number of XMM registers allocated.
2370 static const uint16_t XMMArgRegs[] = {
2371 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2372 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2374 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2375 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2376 && "SSE registers cannot be used when SSE is disabled");
2378 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2379 DAG.getConstant(NumXMMRegs, MVT::i8)));
2382 // For tail calls lower the arguments to the 'real' stack slot.
2384 // Force all the incoming stack arguments to be loaded from the stack
2385 // before any new outgoing arguments are stored to the stack, because the
2386 // outgoing stack slots may alias the incoming argument stack slots, and
2387 // the alias isn't otherwise explicit. This is slightly more conservative
2388 // than necessary, because it means that each store effectively depends
2389 // on every argument instead of just those arguments it would clobber.
2390 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2392 SmallVector<SDValue, 8> MemOpChains2;
2395 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2396 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2397 CCValAssign &VA = ArgLocs[i];
2400 assert(VA.isMemLoc());
2401 SDValue Arg = OutVals[i];
2402 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2403 // Create frame index.
2404 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2405 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2406 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2407 FIN = DAG.getFrameIndex(FI, getPointerTy());
2409 if (Flags.isByVal()) {
2410 // Copy relative to framepointer.
2411 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2412 if (StackPtr.getNode() == 0)
2413 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2415 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2417 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2421 // Store relative to framepointer.
2422 MemOpChains2.push_back(
2423 DAG.getStore(ArgChain, dl, Arg, FIN,
2424 MachinePointerInfo::getFixedStack(FI),
2430 if (!MemOpChains2.empty())
2431 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2432 &MemOpChains2[0], MemOpChains2.size());
2434 // Store the return address to the appropriate stack slot.
2435 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2439 // Build a sequence of copy-to-reg nodes chained together with token chain
2440 // and flag operands which copy the outgoing args into registers.
2442 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2443 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2444 RegsToPass[i].second, InFlag);
2445 InFlag = Chain.getValue(1);
2448 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2449 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2450 // In the 64-bit large code model, we have to make all calls
2451 // through a register, since the call instruction's 32-bit
2452 // pc-relative offset may not be large enough to hold the whole
2454 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2455 // If the callee is a GlobalAddress node (quite common, every direct call
2456 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2459 // We should use extra load for direct calls to dllimported functions in
2461 const GlobalValue *GV = G->getGlobal();
2462 if (!GV->hasDLLImportLinkage()) {
2463 unsigned char OpFlags = 0;
2464 bool ExtraLoad = false;
2465 unsigned WrapperKind = ISD::DELETED_NODE;
2467 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2468 // external symbols most go through the PLT in PIC mode. If the symbol
2469 // has hidden or protected visibility, or if it is static or local, then
2470 // we don't need to use the PLT - we can directly call it.
2471 if (Subtarget->isTargetELF() &&
2472 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2473 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2474 OpFlags = X86II::MO_PLT;
2475 } else if (Subtarget->isPICStyleStubAny() &&
2476 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2477 (!Subtarget->getTargetTriple().isMacOSX() ||
2478 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2479 // PC-relative references to external symbols should go through $stub,
2480 // unless we're building with the leopard linker or later, which
2481 // automatically synthesizes these stubs.
2482 OpFlags = X86II::MO_DARWIN_STUB;
2483 } else if (Subtarget->isPICStyleRIPRel() &&
2484 isa<Function>(GV) &&
2485 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2486 // If the function is marked as non-lazy, generate an indirect call
2487 // which loads from the GOT directly. This avoids runtime overhead
2488 // at the cost of eager binding (and one extra byte of encoding).
2489 OpFlags = X86II::MO_GOTPCREL;
2490 WrapperKind = X86ISD::WrapperRIP;
2494 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2495 G->getOffset(), OpFlags);
2497 // Add a wrapper if needed.
2498 if (WrapperKind != ISD::DELETED_NODE)
2499 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2500 // Add extra indirection if needed.
2502 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2503 MachinePointerInfo::getGOT(),
2504 false, false, false, 0);
2506 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2507 unsigned char OpFlags = 0;
2509 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2510 // external symbols should go through the PLT.
2511 if (Subtarget->isTargetELF() &&
2512 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2513 OpFlags = X86II::MO_PLT;
2514 } else if (Subtarget->isPICStyleStubAny() &&
2515 (!Subtarget->getTargetTriple().isMacOSX() ||
2516 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2517 // PC-relative references to external symbols should go through $stub,
2518 // unless we're building with the leopard linker or later, which
2519 // automatically synthesizes these stubs.
2520 OpFlags = X86II::MO_DARWIN_STUB;
2523 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2527 // Returns a chain & a flag for retval copy to use.
2528 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2529 SmallVector<SDValue, 8> Ops;
2531 if (!IsSibcall && isTailCall) {
2532 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2533 DAG.getIntPtrConstant(0, true), InFlag);
2534 InFlag = Chain.getValue(1);
2537 Ops.push_back(Chain);
2538 Ops.push_back(Callee);
2541 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2543 // Add argument registers to the end of the list so that they are known live
2545 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2546 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2547 RegsToPass[i].second.getValueType()));
2549 // Add a register mask operand representing the call-preserved registers.
2550 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2551 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2552 assert(Mask && "Missing call preserved mask for calling convention");
2553 Ops.push_back(DAG.getRegisterMask(Mask));
2555 if (InFlag.getNode())
2556 Ops.push_back(InFlag);
2560 //// If this is the first return lowered for this function, add the regs
2561 //// to the liveout set for the function.
2562 // This isn't right, although it's probably harmless on x86; liveouts
2563 // should be computed from returns not tail calls. Consider a void
2564 // function making a tail call to a function returning int.
2565 return DAG.getNode(X86ISD::TC_RETURN, dl,
2566 NodeTys, &Ops[0], Ops.size());
2569 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2570 InFlag = Chain.getValue(1);
2572 // Create the CALLSEQ_END node.
2573 unsigned NumBytesForCalleeToPush;
2574 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2575 getTargetMachine().Options.GuaranteedTailCallOpt))
2576 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2577 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2578 SR == StackStructReturn)
2579 // If this is a call to a struct-return function, the callee
2580 // pops the hidden struct pointer, so we have to push it back.
2581 // This is common for Darwin/X86, Linux & Mingw32 targets.
2582 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2583 NumBytesForCalleeToPush = 4;
2585 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2587 // Returns a flag for retval copy to use.
2589 Chain = DAG.getCALLSEQ_END(Chain,
2590 DAG.getIntPtrConstant(NumBytes, true),
2591 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2594 InFlag = Chain.getValue(1);
2597 // Handle result values, copying them out of physregs into vregs that we
2599 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2600 Ins, dl, DAG, InVals);
2604 //===----------------------------------------------------------------------===//
2605 // Fast Calling Convention (tail call) implementation
2606 //===----------------------------------------------------------------------===//
2608 // Like std call, callee cleans arguments, convention except that ECX is
2609 // reserved for storing the tail called function address. Only 2 registers are
2610 // free for argument passing (inreg). Tail call optimization is performed
2612 // * tailcallopt is enabled
2613 // * caller/callee are fastcc
2614 // On X86_64 architecture with GOT-style position independent code only local
2615 // (within module) calls are supported at the moment.
2616 // To keep the stack aligned according to platform abi the function
2617 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2618 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2619 // If a tail called function callee has more arguments than the caller the
2620 // caller needs to make sure that there is room to move the RETADDR to. This is
2621 // achieved by reserving an area the size of the argument delta right after the
2622 // original REtADDR, but before the saved framepointer or the spilled registers
2623 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2635 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2636 /// for a 16 byte align requirement.
2638 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2639 SelectionDAG& DAG) const {
2640 MachineFunction &MF = DAG.getMachineFunction();
2641 const TargetMachine &TM = MF.getTarget();
2642 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2643 unsigned StackAlignment = TFI.getStackAlignment();
2644 uint64_t AlignMask = StackAlignment - 1;
2645 int64_t Offset = StackSize;
2646 uint64_t SlotSize = TD->getPointerSize();
2647 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2648 // Number smaller than 12 so just add the difference.
2649 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2651 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2652 Offset = ((~AlignMask) & Offset) + StackAlignment +
2653 (StackAlignment-SlotSize);
2658 /// MatchingStackOffset - Return true if the given stack call argument is
2659 /// already available in the same position (relatively) of the caller's
2660 /// incoming argument stack.
2662 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2663 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2664 const X86InstrInfo *TII) {
2665 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2667 if (Arg.getOpcode() == ISD::CopyFromReg) {
2668 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2669 if (!TargetRegisterInfo::isVirtualRegister(VR))
2671 MachineInstr *Def = MRI->getVRegDef(VR);
2674 if (!Flags.isByVal()) {
2675 if (!TII->isLoadFromStackSlot(Def, FI))
2678 unsigned Opcode = Def->getOpcode();
2679 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2680 Def->getOperand(1).isFI()) {
2681 FI = Def->getOperand(1).getIndex();
2682 Bytes = Flags.getByValSize();
2686 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2687 if (Flags.isByVal())
2688 // ByVal argument is passed in as a pointer but it's now being
2689 // dereferenced. e.g.
2690 // define @foo(%struct.X* %A) {
2691 // tail call @bar(%struct.X* byval %A)
2694 SDValue Ptr = Ld->getBasePtr();
2695 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2698 FI = FINode->getIndex();
2699 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2700 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2701 FI = FINode->getIndex();
2702 Bytes = Flags.getByValSize();
2706 assert(FI != INT_MAX);
2707 if (!MFI->isFixedObjectIndex(FI))
2709 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2712 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2713 /// for tail call optimization. Targets which want to do tail call
2714 /// optimization should implement this function.
2716 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2717 CallingConv::ID CalleeCC,
2719 bool isCalleeStructRet,
2720 bool isCallerStructRet,
2721 const SmallVectorImpl<ISD::OutputArg> &Outs,
2722 const SmallVectorImpl<SDValue> &OutVals,
2723 const SmallVectorImpl<ISD::InputArg> &Ins,
2724 SelectionDAG& DAG) const {
2725 if (!IsTailCallConvention(CalleeCC) &&
2726 CalleeCC != CallingConv::C)
2729 // If -tailcallopt is specified, make fastcc functions tail-callable.
2730 const MachineFunction &MF = DAG.getMachineFunction();
2731 const Function *CallerF = DAG.getMachineFunction().getFunction();
2732 CallingConv::ID CallerCC = CallerF->getCallingConv();
2733 bool CCMatch = CallerCC == CalleeCC;
2735 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2736 if (IsTailCallConvention(CalleeCC) && CCMatch)
2741 // Look for obvious safe cases to perform tail call optimization that do not
2742 // require ABI changes. This is what gcc calls sibcall.
2744 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2745 // emit a special epilogue.
2746 if (RegInfo->needsStackRealignment(MF))
2749 // Also avoid sibcall optimization if either caller or callee uses struct
2750 // return semantics.
2751 if (isCalleeStructRet || isCallerStructRet)
2754 // An stdcall caller is expected to clean up its arguments; the callee
2755 // isn't going to do that.
2756 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2759 // Do not sibcall optimize vararg calls unless all arguments are passed via
2761 if (isVarArg && !Outs.empty()) {
2763 // Optimizing for varargs on Win64 is unlikely to be safe without
2764 // additional testing.
2765 if (Subtarget->isTargetWin64())
2768 SmallVector<CCValAssign, 16> ArgLocs;
2769 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2770 getTargetMachine(), ArgLocs, *DAG.getContext());
2772 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2773 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2774 if (!ArgLocs[i].isRegLoc())
2778 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2779 // stack. Therefore, if it's not used by the call it is not safe to optimize
2780 // this into a sibcall.
2781 bool Unused = false;
2782 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2789 SmallVector<CCValAssign, 16> RVLocs;
2790 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2791 getTargetMachine(), RVLocs, *DAG.getContext());
2792 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2793 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2794 CCValAssign &VA = RVLocs[i];
2795 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2800 // If the calling conventions do not match, then we'd better make sure the
2801 // results are returned in the same way as what the caller expects.
2803 SmallVector<CCValAssign, 16> RVLocs1;
2804 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2805 getTargetMachine(), RVLocs1, *DAG.getContext());
2806 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2808 SmallVector<CCValAssign, 16> RVLocs2;
2809 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2810 getTargetMachine(), RVLocs2, *DAG.getContext());
2811 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2813 if (RVLocs1.size() != RVLocs2.size())
2815 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2816 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2818 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2820 if (RVLocs1[i].isRegLoc()) {
2821 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2824 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2830 // If the callee takes no arguments then go on to check the results of the
2832 if (!Outs.empty()) {
2833 // Check if stack adjustment is needed. For now, do not do this if any
2834 // argument is passed on the stack.
2835 SmallVector<CCValAssign, 16> ArgLocs;
2836 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2837 getTargetMachine(), ArgLocs, *DAG.getContext());
2839 // Allocate shadow area for Win64
2840 if (Subtarget->isTargetWin64()) {
2841 CCInfo.AllocateStack(32, 8);
2844 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2845 if (CCInfo.getNextStackOffset()) {
2846 MachineFunction &MF = DAG.getMachineFunction();
2847 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2850 // Check if the arguments are already laid out in the right way as
2851 // the caller's fixed stack objects.
2852 MachineFrameInfo *MFI = MF.getFrameInfo();
2853 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2854 const X86InstrInfo *TII =
2855 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2856 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2857 CCValAssign &VA = ArgLocs[i];
2858 SDValue Arg = OutVals[i];
2859 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2860 if (VA.getLocInfo() == CCValAssign::Indirect)
2862 if (!VA.isRegLoc()) {
2863 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2870 // If the tailcall address may be in a register, then make sure it's
2871 // possible to register allocate for it. In 32-bit, the call address can
2872 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2873 // callee-saved registers are restored. These happen to be the same
2874 // registers used to pass 'inreg' arguments so watch out for those.
2875 if (!Subtarget->is64Bit() &&
2876 !isa<GlobalAddressSDNode>(Callee) &&
2877 !isa<ExternalSymbolSDNode>(Callee)) {
2878 unsigned NumInRegs = 0;
2879 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2880 CCValAssign &VA = ArgLocs[i];
2883 unsigned Reg = VA.getLocReg();
2886 case X86::EAX: case X86::EDX: case X86::ECX:
2887 if (++NumInRegs == 3)
2899 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2900 const TargetLibraryInfo *libInfo) const {
2901 return X86::createFastISel(funcInfo, libInfo);
2905 //===----------------------------------------------------------------------===//
2906 // Other Lowering Hooks
2907 //===----------------------------------------------------------------------===//
2909 static bool MayFoldLoad(SDValue Op) {
2910 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2913 static bool MayFoldIntoStore(SDValue Op) {
2914 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2917 static bool isTargetShuffle(unsigned Opcode) {
2919 default: return false;
2920 case X86ISD::PSHUFD:
2921 case X86ISD::PSHUFHW:
2922 case X86ISD::PSHUFLW:
2924 case X86ISD::PALIGN:
2925 case X86ISD::MOVLHPS:
2926 case X86ISD::MOVLHPD:
2927 case X86ISD::MOVHLPS:
2928 case X86ISD::MOVLPS:
2929 case X86ISD::MOVLPD:
2930 case X86ISD::MOVSHDUP:
2931 case X86ISD::MOVSLDUP:
2932 case X86ISD::MOVDDUP:
2935 case X86ISD::UNPCKL:
2936 case X86ISD::UNPCKH:
2937 case X86ISD::VPERMILP:
2938 case X86ISD::VPERM2X128:
2939 case X86ISD::VPERMI:
2944 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2945 SDValue V1, SelectionDAG &DAG) {
2947 default: llvm_unreachable("Unknown x86 shuffle node");
2948 case X86ISD::MOVSHDUP:
2949 case X86ISD::MOVSLDUP:
2950 case X86ISD::MOVDDUP:
2951 return DAG.getNode(Opc, dl, VT, V1);
2955 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2956 SDValue V1, unsigned TargetMask,
2957 SelectionDAG &DAG) {
2959 default: llvm_unreachable("Unknown x86 shuffle node");
2960 case X86ISD::PSHUFD:
2961 case X86ISD::PSHUFHW:
2962 case X86ISD::PSHUFLW:
2963 case X86ISD::VPERMILP:
2964 case X86ISD::VPERMI:
2965 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2969 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2970 SDValue V1, SDValue V2, unsigned TargetMask,
2971 SelectionDAG &DAG) {
2973 default: llvm_unreachable("Unknown x86 shuffle node");
2974 case X86ISD::PALIGN:
2976 case X86ISD::VPERM2X128:
2977 return DAG.getNode(Opc, dl, VT, V1, V2,
2978 DAG.getConstant(TargetMask, MVT::i8));
2982 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2983 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2985 default: llvm_unreachable("Unknown x86 shuffle node");
2986 case X86ISD::MOVLHPS:
2987 case X86ISD::MOVLHPD:
2988 case X86ISD::MOVHLPS:
2989 case X86ISD::MOVLPS:
2990 case X86ISD::MOVLPD:
2993 case X86ISD::UNPCKL:
2994 case X86ISD::UNPCKH:
2995 return DAG.getNode(Opc, dl, VT, V1, V2);
2999 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3000 MachineFunction &MF = DAG.getMachineFunction();
3001 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3002 int ReturnAddrIndex = FuncInfo->getRAIndex();
3004 if (ReturnAddrIndex == 0) {
3005 // Set up a frame object for the return address.
3006 uint64_t SlotSize = TD->getPointerSize();
3007 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3009 FuncInfo->setRAIndex(ReturnAddrIndex);
3012 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3016 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3017 bool hasSymbolicDisplacement) {
3018 // Offset should fit into 32 bit immediate field.
3019 if (!isInt<32>(Offset))
3022 // If we don't have a symbolic displacement - we don't have any extra
3024 if (!hasSymbolicDisplacement)
3027 // FIXME: Some tweaks might be needed for medium code model.
3028 if (M != CodeModel::Small && M != CodeModel::Kernel)
3031 // For small code model we assume that latest object is 16MB before end of 31
3032 // bits boundary. We may also accept pretty large negative constants knowing
3033 // that all objects are in the positive half of address space.
3034 if (M == CodeModel::Small && Offset < 16*1024*1024)
3037 // For kernel code model we know that all object resist in the negative half
3038 // of 32bits address space. We may not accept negative offsets, since they may
3039 // be just off and we may accept pretty large positive ones.
3040 if (M == CodeModel::Kernel && Offset > 0)
3046 /// isCalleePop - Determines whether the callee is required to pop its
3047 /// own arguments. Callee pop is necessary to support tail calls.
3048 bool X86::isCalleePop(CallingConv::ID CallingConv,
3049 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3053 switch (CallingConv) {
3056 case CallingConv::X86_StdCall:
3058 case CallingConv::X86_FastCall:
3060 case CallingConv::X86_ThisCall:
3062 case CallingConv::Fast:
3064 case CallingConv::GHC:
3069 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3070 /// specific condition code, returning the condition code and the LHS/RHS of the
3071 /// comparison to make.
3072 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3073 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3075 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3076 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3077 // X > -1 -> X == 0, jump !sign.
3078 RHS = DAG.getConstant(0, RHS.getValueType());
3079 return X86::COND_NS;
3081 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3082 // X < 0 -> X == 0, jump on sign.
3085 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3087 RHS = DAG.getConstant(0, RHS.getValueType());
3088 return X86::COND_LE;
3092 switch (SetCCOpcode) {
3093 default: llvm_unreachable("Invalid integer condition!");
3094 case ISD::SETEQ: return X86::COND_E;
3095 case ISD::SETGT: return X86::COND_G;
3096 case ISD::SETGE: return X86::COND_GE;
3097 case ISD::SETLT: return X86::COND_L;
3098 case ISD::SETLE: return X86::COND_LE;
3099 case ISD::SETNE: return X86::COND_NE;
3100 case ISD::SETULT: return X86::COND_B;
3101 case ISD::SETUGT: return X86::COND_A;
3102 case ISD::SETULE: return X86::COND_BE;
3103 case ISD::SETUGE: return X86::COND_AE;
3107 // First determine if it is required or is profitable to flip the operands.
3109 // If LHS is a foldable load, but RHS is not, flip the condition.
3110 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3111 !ISD::isNON_EXTLoad(RHS.getNode())) {
3112 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3113 std::swap(LHS, RHS);
3116 switch (SetCCOpcode) {
3122 std::swap(LHS, RHS);
3126 // On a floating point condition, the flags are set as follows:
3128 // 0 | 0 | 0 | X > Y
3129 // 0 | 0 | 1 | X < Y
3130 // 1 | 0 | 0 | X == Y
3131 // 1 | 1 | 1 | unordered
3132 switch (SetCCOpcode) {
3133 default: llvm_unreachable("Condcode should be pre-legalized away");
3135 case ISD::SETEQ: return X86::COND_E;
3136 case ISD::SETOLT: // flipped
3138 case ISD::SETGT: return X86::COND_A;
3139 case ISD::SETOLE: // flipped
3141 case ISD::SETGE: return X86::COND_AE;
3142 case ISD::SETUGT: // flipped
3144 case ISD::SETLT: return X86::COND_B;
3145 case ISD::SETUGE: // flipped
3147 case ISD::SETLE: return X86::COND_BE;
3149 case ISD::SETNE: return X86::COND_NE;
3150 case ISD::SETUO: return X86::COND_P;
3151 case ISD::SETO: return X86::COND_NP;
3153 case ISD::SETUNE: return X86::COND_INVALID;
3157 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3158 /// code. Current x86 isa includes the following FP cmov instructions:
3159 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3160 static bool hasFPCMov(unsigned X86CC) {
3176 /// isFPImmLegal - Returns true if the target can instruction select the
3177 /// specified FP immediate natively. If false, the legalizer will
3178 /// materialize the FP immediate as a load from a constant pool.
3179 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3180 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3181 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3187 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3188 /// the specified range (L, H].
3189 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3190 return (Val < 0) || (Val >= Low && Val < Hi);
3193 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3194 /// specified value.
3195 static bool isUndefOrEqual(int Val, int CmpVal) {
3196 if (Val < 0 || Val == CmpVal)
3201 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3202 /// from position Pos and ending in Pos+Size, falls within the specified
3203 /// sequential range (L, L+Pos]. or is undef.
3204 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3205 unsigned Pos, unsigned Size, int Low) {
3206 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3207 if (!isUndefOrEqual(Mask[i], Low))
3212 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3213 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3214 /// the second operand.
3215 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3216 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3217 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3218 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3219 return (Mask[0] < 2 && Mask[1] < 2);
3223 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3224 /// is suitable for input to PSHUFHW.
3225 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3226 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3229 // Lower quadword copied in order or undef.
3230 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3233 // Upper quadword shuffled.
3234 for (unsigned i = 4; i != 8; ++i)
3235 if (!isUndefOrInRange(Mask[i], 4, 8))
3238 if (VT == MVT::v16i16) {
3239 // Lower quadword copied in order or undef.
3240 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3243 // Upper quadword shuffled.
3244 for (unsigned i = 12; i != 16; ++i)
3245 if (!isUndefOrInRange(Mask[i], 12, 16))
3252 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3253 /// is suitable for input to PSHUFLW.
3254 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3255 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3258 // Upper quadword copied in order.
3259 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3262 // Lower quadword shuffled.
3263 for (unsigned i = 0; i != 4; ++i)
3264 if (!isUndefOrInRange(Mask[i], 0, 4))
3267 if (VT == MVT::v16i16) {
3268 // Upper quadword copied in order.
3269 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3272 // Lower quadword shuffled.
3273 for (unsigned i = 8; i != 12; ++i)
3274 if (!isUndefOrInRange(Mask[i], 8, 12))
3281 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3282 /// is suitable for input to PALIGNR.
3283 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3284 const X86Subtarget *Subtarget) {
3285 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3286 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3289 unsigned NumElts = VT.getVectorNumElements();
3290 unsigned NumLanes = VT.getSizeInBits()/128;
3291 unsigned NumLaneElts = NumElts/NumLanes;
3293 // Do not handle 64-bit element shuffles with palignr.
3294 if (NumLaneElts == 2)
3297 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3299 for (i = 0; i != NumLaneElts; ++i) {
3304 // Lane is all undef, go to next lane
3305 if (i == NumLaneElts)
3308 int Start = Mask[i+l];
3310 // Make sure its in this lane in one of the sources
3311 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3312 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3315 // If not lane 0, then we must match lane 0
3316 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3319 // Correct second source to be contiguous with first source
3320 if (Start >= (int)NumElts)
3321 Start -= NumElts - NumLaneElts;
3323 // Make sure we're shifting in the right direction.
3324 if (Start <= (int)(i+l))
3329 // Check the rest of the elements to see if they are consecutive.
3330 for (++i; i != NumLaneElts; ++i) {
3331 int Idx = Mask[i+l];
3333 // Make sure its in this lane
3334 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3335 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3338 // If not lane 0, then we must match lane 0
3339 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3342 if (Idx >= (int)NumElts)
3343 Idx -= NumElts - NumLaneElts;
3345 if (!isUndefOrEqual(Idx, Start+i))
3354 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3355 /// the two vector operands have swapped position.
3356 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3357 unsigned NumElems) {
3358 for (unsigned i = 0; i != NumElems; ++i) {
3362 else if (idx < (int)NumElems)
3363 Mask[i] = idx + NumElems;
3365 Mask[i] = idx - NumElems;
3369 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3370 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3371 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3372 /// reverse of what x86 shuffles want.
3373 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3374 bool Commuted = false) {
3375 if (!HasAVX && VT.getSizeInBits() == 256)
3378 unsigned NumElems = VT.getVectorNumElements();
3379 unsigned NumLanes = VT.getSizeInBits()/128;
3380 unsigned NumLaneElems = NumElems/NumLanes;
3382 if (NumLaneElems != 2 && NumLaneElems != 4)
3385 // VSHUFPSY divides the resulting vector into 4 chunks.
3386 // The sources are also splitted into 4 chunks, and each destination
3387 // chunk must come from a different source chunk.
3389 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3390 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3392 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3393 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3395 // VSHUFPDY divides the resulting vector into 4 chunks.
3396 // The sources are also splitted into 4 chunks, and each destination
3397 // chunk must come from a different source chunk.
3399 // SRC1 => X3 X2 X1 X0
3400 // SRC2 => Y3 Y2 Y1 Y0
3402 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3404 unsigned HalfLaneElems = NumLaneElems/2;
3405 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3406 for (unsigned i = 0; i != NumLaneElems; ++i) {
3407 int Idx = Mask[i+l];
3408 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3409 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3411 // For VSHUFPSY, the mask of the second half must be the same as the
3412 // first but with the appropriate offsets. This works in the same way as
3413 // VPERMILPS works with masks.
3414 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3416 if (!isUndefOrEqual(Idx, Mask[i]+l))
3424 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3425 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3426 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3427 if (!VT.is128BitVector())
3430 unsigned NumElems = VT.getVectorNumElements();
3435 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3436 return isUndefOrEqual(Mask[0], 6) &&
3437 isUndefOrEqual(Mask[1], 7) &&
3438 isUndefOrEqual(Mask[2], 2) &&
3439 isUndefOrEqual(Mask[3], 3);
3442 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3443 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3445 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3446 if (!VT.is128BitVector())
3449 unsigned NumElems = VT.getVectorNumElements();
3454 return isUndefOrEqual(Mask[0], 2) &&
3455 isUndefOrEqual(Mask[1], 3) &&
3456 isUndefOrEqual(Mask[2], 2) &&
3457 isUndefOrEqual(Mask[3], 3);
3460 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3461 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3462 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3463 if (!VT.is128BitVector())
3466 unsigned NumElems = VT.getVectorNumElements();
3468 if (NumElems != 2 && NumElems != 4)
3471 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3472 if (!isUndefOrEqual(Mask[i], i + NumElems))
3475 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3476 if (!isUndefOrEqual(Mask[i], i))
3482 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3483 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3484 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3485 if (!VT.is128BitVector())
3488 unsigned NumElems = VT.getVectorNumElements();
3490 if (NumElems != 2 && NumElems != 4)
3493 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3494 if (!isUndefOrEqual(Mask[i], i))
3497 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3498 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3505 // Some special combinations that can be optimized.
3508 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3509 SelectionDAG &DAG) {
3510 EVT VT = SVOp->getValueType(0);
3511 DebugLoc dl = SVOp->getDebugLoc();
3513 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3516 ArrayRef<int> Mask = SVOp->getMask();
3518 // These are the special masks that may be optimized.
3519 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3520 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3521 bool MatchEvenMask = true;
3522 bool MatchOddMask = true;
3523 for (int i=0; i<8; ++i) {
3524 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3525 MatchEvenMask = false;
3526 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3527 MatchOddMask = false;
3530 if (!MatchEvenMask && !MatchOddMask)
3533 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3535 SDValue Op0 = SVOp->getOperand(0);
3536 SDValue Op1 = SVOp->getOperand(1);
3538 if (MatchEvenMask) {
3539 // Shift the second operand right to 32 bits.
3540 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3541 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3543 // Shift the first operand left to 32 bits.
3544 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3545 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3547 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3548 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3551 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3552 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3553 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3554 bool HasAVX2, bool V2IsSplat = false) {
3555 unsigned NumElts = VT.getVectorNumElements();
3557 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3558 "Unsupported vector type for unpckh");
3560 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3561 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3564 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3565 // independently on 128-bit lanes.
3566 unsigned NumLanes = VT.getSizeInBits()/128;
3567 unsigned NumLaneElts = NumElts/NumLanes;
3569 for (unsigned l = 0; l != NumLanes; ++l) {
3570 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3571 i != (l+1)*NumLaneElts;
3574 int BitI1 = Mask[i+1];
3575 if (!isUndefOrEqual(BitI, j))
3578 if (!isUndefOrEqual(BitI1, NumElts))
3581 if (!isUndefOrEqual(BitI1, j + NumElts))
3590 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3591 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3592 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3593 bool HasAVX2, bool V2IsSplat = false) {
3594 unsigned NumElts = VT.getVectorNumElements();
3596 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3597 "Unsupported vector type for unpckh");
3599 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3600 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3603 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3604 // independently on 128-bit lanes.
3605 unsigned NumLanes = VT.getSizeInBits()/128;
3606 unsigned NumLaneElts = NumElts/NumLanes;
3608 for (unsigned l = 0; l != NumLanes; ++l) {
3609 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3610 i != (l+1)*NumLaneElts; i += 2, ++j) {
3612 int BitI1 = Mask[i+1];
3613 if (!isUndefOrEqual(BitI, j))
3616 if (isUndefOrEqual(BitI1, NumElts))
3619 if (!isUndefOrEqual(BitI1, j+NumElts))
3627 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3628 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3630 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3632 unsigned NumElts = VT.getVectorNumElements();
3634 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3635 "Unsupported vector type for unpckh");
3637 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3638 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3641 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3642 // FIXME: Need a better way to get rid of this, there's no latency difference
3643 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3644 // the former later. We should also remove the "_undef" special mask.
3645 if (NumElts == 4 && VT.getSizeInBits() == 256)
3648 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3649 // independently on 128-bit lanes.
3650 unsigned NumLanes = VT.getSizeInBits()/128;
3651 unsigned NumLaneElts = NumElts/NumLanes;
3653 for (unsigned l = 0; l != NumLanes; ++l) {
3654 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3655 i != (l+1)*NumLaneElts;
3658 int BitI1 = Mask[i+1];
3660 if (!isUndefOrEqual(BitI, j))
3662 if (!isUndefOrEqual(BitI1, j))
3670 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3671 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3673 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3674 unsigned NumElts = VT.getVectorNumElements();
3676 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3677 "Unsupported vector type for unpckh");
3679 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3680 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3683 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3684 // independently on 128-bit lanes.
3685 unsigned NumLanes = VT.getSizeInBits()/128;
3686 unsigned NumLaneElts = NumElts/NumLanes;
3688 for (unsigned l = 0; l != NumLanes; ++l) {
3689 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3690 i != (l+1)*NumLaneElts; i += 2, ++j) {
3692 int BitI1 = Mask[i+1];
3693 if (!isUndefOrEqual(BitI, j))
3695 if (!isUndefOrEqual(BitI1, j))
3702 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3703 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3704 /// MOVSD, and MOVD, i.e. setting the lowest element.
3705 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3706 if (VT.getVectorElementType().getSizeInBits() < 32)
3708 if (!VT.is128BitVector())
3711 unsigned NumElts = VT.getVectorNumElements();
3713 if (!isUndefOrEqual(Mask[0], NumElts))
3716 for (unsigned i = 1; i != NumElts; ++i)
3717 if (!isUndefOrEqual(Mask[i], i))
3723 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3724 /// as permutations between 128-bit chunks or halves. As an example: this
3726 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3727 /// The first half comes from the second half of V1 and the second half from the
3728 /// the second half of V2.
3729 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3730 if (!HasAVX || !VT.is256BitVector())
3733 // The shuffle result is divided into half A and half B. In total the two
3734 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3735 // B must come from C, D, E or F.
3736 unsigned HalfSize = VT.getVectorNumElements()/2;
3737 bool MatchA = false, MatchB = false;
3739 // Check if A comes from one of C, D, E, F.
3740 for (unsigned Half = 0; Half != 4; ++Half) {
3741 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3747 // Check if B comes from one of C, D, E, F.
3748 for (unsigned Half = 0; Half != 4; ++Half) {
3749 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3755 return MatchA && MatchB;
3758 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3759 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3760 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3761 EVT VT = SVOp->getValueType(0);
3763 unsigned HalfSize = VT.getVectorNumElements()/2;
3765 unsigned FstHalf = 0, SndHalf = 0;
3766 for (unsigned i = 0; i < HalfSize; ++i) {
3767 if (SVOp->getMaskElt(i) > 0) {
3768 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3772 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3773 if (SVOp->getMaskElt(i) > 0) {
3774 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3779 return (FstHalf | (SndHalf << 4));
3782 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3783 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3784 /// Note that VPERMIL mask matching is different depending whether theunderlying
3785 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3786 /// to the same elements of the low, but to the higher half of the source.
3787 /// In VPERMILPD the two lanes could be shuffled independently of each other
3788 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3789 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3793 unsigned NumElts = VT.getVectorNumElements();
3794 // Only match 256-bit with 32/64-bit types
3795 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3798 unsigned NumLanes = VT.getSizeInBits()/128;
3799 unsigned LaneSize = NumElts/NumLanes;
3800 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3801 for (unsigned i = 0; i != LaneSize; ++i) {
3802 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3804 if (NumElts != 8 || l == 0)
3806 // VPERMILPS handling
3809 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3817 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3818 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3819 /// element of vector 2 and the other elements to come from vector 1 in order.
3820 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3821 bool V2IsSplat = false, bool V2IsUndef = false) {
3822 if (!VT.is128BitVector())
3825 unsigned NumOps = VT.getVectorNumElements();
3826 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3829 if (!isUndefOrEqual(Mask[0], 0))
3832 for (unsigned i = 1; i != NumOps; ++i)
3833 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3834 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3835 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3841 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3842 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3843 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3844 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3845 const X86Subtarget *Subtarget) {
3846 if (!Subtarget->hasSSE3())
3849 unsigned NumElems = VT.getVectorNumElements();
3851 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3852 (VT.getSizeInBits() == 256 && NumElems != 8))
3855 // "i+1" is the value the indexed mask element must have
3856 for (unsigned i = 0; i != NumElems; i += 2)
3857 if (!isUndefOrEqual(Mask[i], i+1) ||
3858 !isUndefOrEqual(Mask[i+1], i+1))
3864 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3865 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3866 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3867 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3868 const X86Subtarget *Subtarget) {
3869 if (!Subtarget->hasSSE3())
3872 unsigned NumElems = VT.getVectorNumElements();
3874 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3875 (VT.getSizeInBits() == 256 && NumElems != 8))
3878 // "i" is the value the indexed mask element must have
3879 for (unsigned i = 0; i != NumElems; i += 2)
3880 if (!isUndefOrEqual(Mask[i], i) ||
3881 !isUndefOrEqual(Mask[i+1], i))
3887 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3888 /// specifies a shuffle of elements that is suitable for input to 256-bit
3889 /// version of MOVDDUP.
3890 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3891 if (!HasAVX || !VT.is256BitVector())
3894 unsigned NumElts = VT.getVectorNumElements();
3898 for (unsigned i = 0; i != NumElts/2; ++i)
3899 if (!isUndefOrEqual(Mask[i], 0))
3901 for (unsigned i = NumElts/2; i != NumElts; ++i)
3902 if (!isUndefOrEqual(Mask[i], NumElts/2))
3907 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to 128-bit
3909 /// version of MOVDDUP.
3910 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3911 if (!VT.is128BitVector())
3914 unsigned e = VT.getVectorNumElements() / 2;
3915 for (unsigned i = 0; i != e; ++i)
3916 if (!isUndefOrEqual(Mask[i], i))
3918 for (unsigned i = 0; i != e; ++i)
3919 if (!isUndefOrEqual(Mask[e+i], i))
3924 /// isVEXTRACTF128Index - Return true if the specified
3925 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3926 /// suitable for input to VEXTRACTF128.
3927 bool X86::isVEXTRACTF128Index(SDNode *N) {
3928 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3931 // The index should be aligned on a 128-bit boundary.
3933 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3935 unsigned VL = N->getValueType(0).getVectorNumElements();
3936 unsigned VBits = N->getValueType(0).getSizeInBits();
3937 unsigned ElSize = VBits / VL;
3938 bool Result = (Index * ElSize) % 128 == 0;
3943 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3944 /// operand specifies a subvector insert that is suitable for input to
3946 bool X86::isVINSERTF128Index(SDNode *N) {
3947 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3950 // The index should be aligned on a 128-bit boundary.
3952 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3954 unsigned VL = N->getValueType(0).getVectorNumElements();
3955 unsigned VBits = N->getValueType(0).getSizeInBits();
3956 unsigned ElSize = VBits / VL;
3957 bool Result = (Index * ElSize) % 128 == 0;
3962 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3963 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3964 /// Handles 128-bit and 256-bit.
3965 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3966 EVT VT = N->getValueType(0);
3968 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3969 "Unsupported vector type for PSHUF/SHUFP");
3971 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3972 // independently on 128-bit lanes.
3973 unsigned NumElts = VT.getVectorNumElements();
3974 unsigned NumLanes = VT.getSizeInBits()/128;
3975 unsigned NumLaneElts = NumElts/NumLanes;
3977 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3978 "Only supports 2 or 4 elements per lane");
3980 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3982 for (unsigned i = 0; i != NumElts; ++i) {
3983 int Elt = N->getMaskElt(i);
3984 if (Elt < 0) continue;
3985 Elt &= NumLaneElts - 1;
3986 unsigned ShAmt = (i << Shift) % 8;
3987 Mask |= Elt << ShAmt;
3993 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3994 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3995 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3996 EVT VT = N->getValueType(0);
3998 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3999 "Unsupported vector type for PSHUFHW");
4001 unsigned NumElts = VT.getVectorNumElements();
4004 for (unsigned l = 0; l != NumElts; l += 8) {
4005 // 8 nodes per lane, but we only care about the last 4.
4006 for (unsigned i = 0; i < 4; ++i) {
4007 int Elt = N->getMaskElt(l+i+4);
4008 if (Elt < 0) continue;
4009 Elt &= 0x3; // only 2-bits.
4010 Mask |= Elt << (i * 2);
4017 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4018 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4019 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4020 EVT VT = N->getValueType(0);
4022 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4023 "Unsupported vector type for PSHUFHW");
4025 unsigned NumElts = VT.getVectorNumElements();
4028 for (unsigned l = 0; l != NumElts; l += 8) {
4029 // 8 nodes per lane, but we only care about the first 4.
4030 for (unsigned i = 0; i < 4; ++i) {
4031 int Elt = N->getMaskElt(l+i);
4032 if (Elt < 0) continue;
4033 Elt &= 0x3; // only 2-bits
4034 Mask |= Elt << (i * 2);
4041 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4042 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4043 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4044 EVT VT = SVOp->getValueType(0);
4045 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4047 unsigned NumElts = VT.getVectorNumElements();
4048 unsigned NumLanes = VT.getSizeInBits()/128;
4049 unsigned NumLaneElts = NumElts/NumLanes;
4053 for (i = 0; i != NumElts; ++i) {
4054 Val = SVOp->getMaskElt(i);
4058 if (Val >= (int)NumElts)
4059 Val -= NumElts - NumLaneElts;
4061 assert(Val - i > 0 && "PALIGNR imm should be positive");
4062 return (Val - i) * EltSize;
4065 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4066 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4068 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4069 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4070 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4073 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4075 EVT VecVT = N->getOperand(0).getValueType();
4076 EVT ElVT = VecVT.getVectorElementType();
4078 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4079 return Index / NumElemsPerChunk;
4082 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4083 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4085 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4086 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4087 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4090 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4092 EVT VecVT = N->getValueType(0);
4093 EVT ElVT = VecVT.getVectorElementType();
4095 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4096 return Index / NumElemsPerChunk;
4099 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4100 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4101 /// Handles 256-bit.
4102 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4103 EVT VT = N->getValueType(0);
4105 unsigned NumElts = VT.getVectorNumElements();
4107 assert((VT.is256BitVector() && NumElts == 4) &&
4108 "Unsupported vector type for VPERMQ/VPERMPD");
4111 for (unsigned i = 0; i != NumElts; ++i) {
4112 int Elt = N->getMaskElt(i);
4115 Mask |= Elt << (i*2);
4120 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4122 bool X86::isZeroNode(SDValue Elt) {
4123 return ((isa<ConstantSDNode>(Elt) &&
4124 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4125 (isa<ConstantFPSDNode>(Elt) &&
4126 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4129 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4130 /// their permute mask.
4131 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4132 SelectionDAG &DAG) {
4133 EVT VT = SVOp->getValueType(0);
4134 unsigned NumElems = VT.getVectorNumElements();
4135 SmallVector<int, 8> MaskVec;
4137 for (unsigned i = 0; i != NumElems; ++i) {
4138 int Idx = SVOp->getMaskElt(i);
4140 if (Idx < (int)NumElems)
4145 MaskVec.push_back(Idx);
4147 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4148 SVOp->getOperand(0), &MaskVec[0]);
4151 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4152 /// match movhlps. The lower half elements should come from upper half of
4153 /// V1 (and in order), and the upper half elements should come from the upper
4154 /// half of V2 (and in order).
4155 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4156 if (!VT.is128BitVector())
4158 if (VT.getVectorNumElements() != 4)
4160 for (unsigned i = 0, e = 2; i != e; ++i)
4161 if (!isUndefOrEqual(Mask[i], i+2))
4163 for (unsigned i = 2; i != 4; ++i)
4164 if (!isUndefOrEqual(Mask[i], i+4))
4169 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4170 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4172 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4173 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4175 N = N->getOperand(0).getNode();
4176 if (!ISD::isNON_EXTLoad(N))
4179 *LD = cast<LoadSDNode>(N);
4183 // Test whether the given value is a vector value which will be legalized
4185 static bool WillBeConstantPoolLoad(SDNode *N) {
4186 if (N->getOpcode() != ISD::BUILD_VECTOR)
4189 // Check for any non-constant elements.
4190 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4191 switch (N->getOperand(i).getNode()->getOpcode()) {
4193 case ISD::ConstantFP:
4200 // Vectors of all-zeros and all-ones are materialized with special
4201 // instructions rather than being loaded.
4202 return !ISD::isBuildVectorAllZeros(N) &&
4203 !ISD::isBuildVectorAllOnes(N);
4206 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4207 /// match movlp{s|d}. The lower half elements should come from lower half of
4208 /// V1 (and in order), and the upper half elements should come from the upper
4209 /// half of V2 (and in order). And since V1 will become the source of the
4210 /// MOVLP, it must be either a vector load or a scalar load to vector.
4211 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4212 ArrayRef<int> Mask, EVT VT) {
4213 if (!VT.is128BitVector())
4216 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4218 // Is V2 is a vector load, don't do this transformation. We will try to use
4219 // load folding shufps op.
4220 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4223 unsigned NumElems = VT.getVectorNumElements();
4225 if (NumElems != 2 && NumElems != 4)
4227 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4228 if (!isUndefOrEqual(Mask[i], i))
4230 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4231 if (!isUndefOrEqual(Mask[i], i+NumElems))
4236 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4238 static bool isSplatVector(SDNode *N) {
4239 if (N->getOpcode() != ISD::BUILD_VECTOR)
4242 SDValue SplatValue = N->getOperand(0);
4243 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4244 if (N->getOperand(i) != SplatValue)
4249 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4250 /// to an zero vector.
4251 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4252 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4253 SDValue V1 = N->getOperand(0);
4254 SDValue V2 = N->getOperand(1);
4255 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4256 for (unsigned i = 0; i != NumElems; ++i) {
4257 int Idx = N->getMaskElt(i);
4258 if (Idx >= (int)NumElems) {
4259 unsigned Opc = V2.getOpcode();
4260 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4262 if (Opc != ISD::BUILD_VECTOR ||
4263 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4265 } else if (Idx >= 0) {
4266 unsigned Opc = V1.getOpcode();
4267 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4269 if (Opc != ISD::BUILD_VECTOR ||
4270 !X86::isZeroNode(V1.getOperand(Idx)))
4277 /// getZeroVector - Returns a vector of specified type with all zero elements.
4279 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4280 SelectionDAG &DAG, DebugLoc dl) {
4281 assert(VT.isVector() && "Expected a vector type");
4282 unsigned Size = VT.getSizeInBits();
4284 // Always build SSE zero vectors as <4 x i32> bitcasted
4285 // to their dest type. This ensures they get CSE'd.
4287 if (Size == 128) { // SSE
4288 if (Subtarget->hasSSE2()) { // SSE2
4289 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4290 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4292 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4293 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4295 } else if (Size == 256) { // AVX
4296 if (Subtarget->hasAVX2()) { // AVX2
4297 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4298 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4299 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4301 // 256-bit logic and arithmetic instructions in AVX are all
4302 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4303 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4304 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4305 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4308 llvm_unreachable("Unexpected vector type");
4310 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4313 /// getOnesVector - Returns a vector of specified type with all bits set.
4314 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4315 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4316 /// Then bitcast to their original type, ensuring they get CSE'd.
4317 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4319 assert(VT.isVector() && "Expected a vector type");
4320 unsigned Size = VT.getSizeInBits();
4322 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4325 if (HasAVX2) { // AVX2
4326 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4327 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4329 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4330 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4332 } else if (Size == 128) {
4333 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4335 llvm_unreachable("Unexpected vector type");
4337 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4340 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4341 /// that point to V2 points to its first element.
4342 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4343 for (unsigned i = 0; i != NumElems; ++i) {
4344 if (Mask[i] > (int)NumElems) {
4350 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4351 /// operation of specified width.
4352 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4354 unsigned NumElems = VT.getVectorNumElements();
4355 SmallVector<int, 8> Mask;
4356 Mask.push_back(NumElems);
4357 for (unsigned i = 1; i != NumElems; ++i)
4359 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4362 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4363 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4365 unsigned NumElems = VT.getVectorNumElements();
4366 SmallVector<int, 8> Mask;
4367 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4369 Mask.push_back(i + NumElems);
4371 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4374 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4375 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4377 unsigned NumElems = VT.getVectorNumElements();
4378 SmallVector<int, 8> Mask;
4379 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4380 Mask.push_back(i + Half);
4381 Mask.push_back(i + NumElems + Half);
4383 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4386 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4387 // a generic shuffle instruction because the target has no such instructions.
4388 // Generate shuffles which repeat i16 and i8 several times until they can be
4389 // represented by v4f32 and then be manipulated by target suported shuffles.
4390 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4391 EVT VT = V.getValueType();
4392 int NumElems = VT.getVectorNumElements();
4393 DebugLoc dl = V.getDebugLoc();
4395 while (NumElems > 4) {
4396 if (EltNo < NumElems/2) {
4397 V = getUnpackl(DAG, dl, VT, V, V);
4399 V = getUnpackh(DAG, dl, VT, V, V);
4400 EltNo -= NumElems/2;
4407 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4408 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4409 EVT VT = V.getValueType();
4410 DebugLoc dl = V.getDebugLoc();
4411 unsigned Size = VT.getSizeInBits();
4414 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4415 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4416 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4418 } else if (Size == 256) {
4419 // To use VPERMILPS to splat scalars, the second half of indicies must
4420 // refer to the higher part, which is a duplication of the lower one,
4421 // because VPERMILPS can only handle in-lane permutations.
4422 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4423 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4425 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4426 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4429 llvm_unreachable("Vector size not supported");
4431 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4434 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4435 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4436 EVT SrcVT = SV->getValueType(0);
4437 SDValue V1 = SV->getOperand(0);
4438 DebugLoc dl = SV->getDebugLoc();
4440 int EltNo = SV->getSplatIndex();
4441 int NumElems = SrcVT.getVectorNumElements();
4442 unsigned Size = SrcVT.getSizeInBits();
4444 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4445 "Unknown how to promote splat for type");
4447 // Extract the 128-bit part containing the splat element and update
4448 // the splat element index when it refers to the higher register.
4450 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4451 if (EltNo >= NumElems/2)
4452 EltNo -= NumElems/2;
4455 // All i16 and i8 vector types can't be used directly by a generic shuffle
4456 // instruction because the target has no such instruction. Generate shuffles
4457 // which repeat i16 and i8 several times until they fit in i32, and then can
4458 // be manipulated by target suported shuffles.
4459 EVT EltVT = SrcVT.getVectorElementType();
4460 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4461 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4463 // Recreate the 256-bit vector and place the same 128-bit vector
4464 // into the low and high part. This is necessary because we want
4465 // to use VPERM* to shuffle the vectors
4467 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4470 return getLegalSplat(DAG, V1, EltNo);
4473 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4474 /// vector of zero or undef vector. This produces a shuffle where the low
4475 /// element of V2 is swizzled into the zero/undef vector, landing at element
4476 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4477 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4479 const X86Subtarget *Subtarget,
4480 SelectionDAG &DAG) {
4481 EVT VT = V2.getValueType();
4483 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4484 unsigned NumElems = VT.getVectorNumElements();
4485 SmallVector<int, 16> MaskVec;
4486 for (unsigned i = 0; i != NumElems; ++i)
4487 // If this is the insertion idx, put the low elt of V2 here.
4488 MaskVec.push_back(i == Idx ? NumElems : i);
4489 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4492 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4493 /// target specific opcode. Returns true if the Mask could be calculated.
4494 /// Sets IsUnary to true if only uses one source.
4495 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4496 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4497 unsigned NumElems = VT.getVectorNumElements();
4501 switch(N->getOpcode()) {
4503 ImmN = N->getOperand(N->getNumOperands()-1);
4504 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4506 case X86ISD::UNPCKH:
4507 DecodeUNPCKHMask(VT, Mask);
4509 case X86ISD::UNPCKL:
4510 DecodeUNPCKLMask(VT, Mask);
4512 case X86ISD::MOVHLPS:
4513 DecodeMOVHLPSMask(NumElems, Mask);
4515 case X86ISD::MOVLHPS:
4516 DecodeMOVLHPSMask(NumElems, Mask);
4518 case X86ISD::PSHUFD:
4519 case X86ISD::VPERMILP:
4520 ImmN = N->getOperand(N->getNumOperands()-1);
4521 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524 case X86ISD::PSHUFHW:
4525 ImmN = N->getOperand(N->getNumOperands()-1);
4526 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529 case X86ISD::PSHUFLW:
4530 ImmN = N->getOperand(N->getNumOperands()-1);
4531 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4534 case X86ISD::VPERMI:
4535 ImmN = N->getOperand(N->getNumOperands()-1);
4536 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4540 case X86ISD::MOVSD: {
4541 // The index 0 always comes from the first element of the second source,
4542 // this is why MOVSS and MOVSD are used in the first place. The other
4543 // elements come from the other positions of the first source vector
4544 Mask.push_back(NumElems);
4545 for (unsigned i = 1; i != NumElems; ++i) {
4550 case X86ISD::VPERM2X128:
4551 ImmN = N->getOperand(N->getNumOperands()-1);
4552 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4553 if (Mask.empty()) return false;
4555 case X86ISD::MOVDDUP:
4556 case X86ISD::MOVLHPD:
4557 case X86ISD::MOVLPD:
4558 case X86ISD::MOVLPS:
4559 case X86ISD::MOVSHDUP:
4560 case X86ISD::MOVSLDUP:
4561 case X86ISD::PALIGN:
4562 // Not yet implemented
4564 default: llvm_unreachable("unknown target shuffle node");
4570 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4571 /// element of the result of the vector shuffle.
4572 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4575 return SDValue(); // Limit search depth.
4577 SDValue V = SDValue(N, 0);
4578 EVT VT = V.getValueType();
4579 unsigned Opcode = V.getOpcode();
4581 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4582 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4583 int Elt = SV->getMaskElt(Index);
4586 return DAG.getUNDEF(VT.getVectorElementType());
4588 unsigned NumElems = VT.getVectorNumElements();
4589 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4590 : SV->getOperand(1);
4591 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4594 // Recurse into target specific vector shuffles to find scalars.
4595 if (isTargetShuffle(Opcode)) {
4596 MVT ShufVT = V.getValueType().getSimpleVT();
4597 unsigned NumElems = ShufVT.getVectorNumElements();
4598 SmallVector<int, 16> ShuffleMask;
4602 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4605 int Elt = ShuffleMask[Index];
4607 return DAG.getUNDEF(ShufVT.getVectorElementType());
4609 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4611 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4615 // Actual nodes that may contain scalar elements
4616 if (Opcode == ISD::BITCAST) {
4617 V = V.getOperand(0);
4618 EVT SrcVT = V.getValueType();
4619 unsigned NumElems = VT.getVectorNumElements();
4621 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4625 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4626 return (Index == 0) ? V.getOperand(0)
4627 : DAG.getUNDEF(VT.getVectorElementType());
4629 if (V.getOpcode() == ISD::BUILD_VECTOR)
4630 return V.getOperand(Index);
4635 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4636 /// shuffle operation which come from a consecutively from a zero. The
4637 /// search can start in two different directions, from left or right.
4639 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4640 bool ZerosFromLeft, SelectionDAG &DAG) {
4642 for (i = 0; i != NumElems; ++i) {
4643 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4644 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4645 if (!(Elt.getNode() &&
4646 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4653 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4654 /// correspond consecutively to elements from one of the vector operands,
4655 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4657 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4658 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4659 unsigned NumElems, unsigned &OpNum) {
4660 bool SeenV1 = false;
4661 bool SeenV2 = false;
4663 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4664 int Idx = SVOp->getMaskElt(i);
4665 // Ignore undef indicies
4669 if (Idx < (int)NumElems)
4674 // Only accept consecutive elements from the same vector
4675 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4679 OpNum = SeenV1 ? 0 : 1;
4683 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4684 /// logical left shift of a vector.
4685 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4686 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4687 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4688 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4689 false /* check zeros from right */, DAG);
4695 // Considering the elements in the mask that are not consecutive zeros,
4696 // check if they consecutively come from only one of the source vectors.
4698 // V1 = {X, A, B, C} 0
4700 // vector_shuffle V1, V2 <1, 2, 3, X>
4702 if (!isShuffleMaskConsecutive(SVOp,
4703 0, // Mask Start Index
4704 NumElems-NumZeros, // Mask End Index(exclusive)
4705 NumZeros, // Where to start looking in the src vector
4706 NumElems, // Number of elements in vector
4707 OpSrc)) // Which source operand ?
4712 ShVal = SVOp->getOperand(OpSrc);
4716 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4717 /// logical left shift of a vector.
4718 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4719 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4720 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4721 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4722 true /* check zeros from left */, DAG);
4728 // Considering the elements in the mask that are not consecutive zeros,
4729 // check if they consecutively come from only one of the source vectors.
4731 // 0 { A, B, X, X } = V2
4733 // vector_shuffle V1, V2 <X, X, 4, 5>
4735 if (!isShuffleMaskConsecutive(SVOp,
4736 NumZeros, // Mask Start Index
4737 NumElems, // Mask End Index(exclusive)
4738 0, // Where to start looking in the src vector
4739 NumElems, // Number of elements in vector
4740 OpSrc)) // Which source operand ?
4745 ShVal = SVOp->getOperand(OpSrc);
4749 /// isVectorShift - Returns true if the shuffle can be implemented as a
4750 /// logical left or right shift of a vector.
4751 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4752 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4753 // Although the logic below support any bitwidth size, there are no
4754 // shift instructions which handle more than 128-bit vectors.
4755 if (!SVOp->getValueType(0).is128BitVector())
4758 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4759 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4765 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4767 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4768 unsigned NumNonZero, unsigned NumZero,
4770 const X86Subtarget* Subtarget,
4771 const TargetLowering &TLI) {
4775 DebugLoc dl = Op.getDebugLoc();
4778 for (unsigned i = 0; i < 16; ++i) {
4779 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4780 if (ThisIsNonZero && First) {
4782 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4784 V = DAG.getUNDEF(MVT::v8i16);
4789 SDValue ThisElt(0, 0), LastElt(0, 0);
4790 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4791 if (LastIsNonZero) {
4792 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4793 MVT::i16, Op.getOperand(i-1));
4795 if (ThisIsNonZero) {
4796 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4797 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4798 ThisElt, DAG.getConstant(8, MVT::i8));
4800 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4804 if (ThisElt.getNode())
4805 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4806 DAG.getIntPtrConstant(i/2));
4810 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4813 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4815 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4816 unsigned NumNonZero, unsigned NumZero,
4818 const X86Subtarget* Subtarget,
4819 const TargetLowering &TLI) {
4823 DebugLoc dl = Op.getDebugLoc();
4826 for (unsigned i = 0; i < 8; ++i) {
4827 bool isNonZero = (NonZeros & (1 << i)) != 0;
4831 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4833 V = DAG.getUNDEF(MVT::v8i16);
4836 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4837 MVT::v8i16, V, Op.getOperand(i),
4838 DAG.getIntPtrConstant(i));
4845 /// getVShift - Return a vector logical shift node.
4847 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4848 unsigned NumBits, SelectionDAG &DAG,
4849 const TargetLowering &TLI, DebugLoc dl) {
4850 assert(VT.is128BitVector() && "Unknown type for VShift");
4851 EVT ShVT = MVT::v2i64;
4852 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4853 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4854 return DAG.getNode(ISD::BITCAST, dl, VT,
4855 DAG.getNode(Opc, dl, ShVT, SrcOp,
4856 DAG.getConstant(NumBits,
4857 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4861 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4862 SelectionDAG &DAG) const {
4864 // Check if the scalar load can be widened into a vector load. And if
4865 // the address is "base + cst" see if the cst can be "absorbed" into
4866 // the shuffle mask.
4867 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4868 SDValue Ptr = LD->getBasePtr();
4869 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4871 EVT PVT = LD->getValueType(0);
4872 if (PVT != MVT::i32 && PVT != MVT::f32)
4877 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4878 FI = FINode->getIndex();
4880 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4881 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4882 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4883 Offset = Ptr.getConstantOperandVal(1);
4884 Ptr = Ptr.getOperand(0);
4889 // FIXME: 256-bit vector instructions don't require a strict alignment,
4890 // improve this code to support it better.
4891 unsigned RequiredAlign = VT.getSizeInBits()/8;
4892 SDValue Chain = LD->getChain();
4893 // Make sure the stack object alignment is at least 16 or 32.
4894 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4895 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4896 if (MFI->isFixedObjectIndex(FI)) {
4897 // Can't change the alignment. FIXME: It's possible to compute
4898 // the exact stack offset and reference FI + adjust offset instead.
4899 // If someone *really* cares about this. That's the way to implement it.
4902 MFI->setObjectAlignment(FI, RequiredAlign);
4906 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4907 // Ptr + (Offset & ~15).
4910 if ((Offset % RequiredAlign) & 3)
4912 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4914 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4915 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4917 int EltNo = (Offset - StartOffset) >> 2;
4918 unsigned NumElems = VT.getVectorNumElements();
4920 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4921 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4922 LD->getPointerInfo().getWithOffset(StartOffset),
4923 false, false, false, 0);
4925 SmallVector<int, 8> Mask;
4926 for (unsigned i = 0; i != NumElems; ++i)
4927 Mask.push_back(EltNo);
4929 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4935 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4936 /// vector of type 'VT', see if the elements can be replaced by a single large
4937 /// load which has the same value as a build_vector whose operands are 'elts'.
4939 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4941 /// FIXME: we'd also like to handle the case where the last elements are zero
4942 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4943 /// There's even a handy isZeroNode for that purpose.
4944 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4945 DebugLoc &DL, SelectionDAG &DAG) {
4946 EVT EltVT = VT.getVectorElementType();
4947 unsigned NumElems = Elts.size();
4949 LoadSDNode *LDBase = NULL;
4950 unsigned LastLoadedElt = -1U;
4952 // For each element in the initializer, see if we've found a load or an undef.
4953 // If we don't find an initial load element, or later load elements are
4954 // non-consecutive, bail out.
4955 for (unsigned i = 0; i < NumElems; ++i) {
4956 SDValue Elt = Elts[i];
4958 if (!Elt.getNode() ||
4959 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4962 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4964 LDBase = cast<LoadSDNode>(Elt.getNode());
4968 if (Elt.getOpcode() == ISD::UNDEF)
4971 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4972 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4977 // If we have found an entire vector of loads and undefs, then return a large
4978 // load of the entire vector width starting at the base pointer. If we found
4979 // consecutive loads for the low half, generate a vzext_load node.
4980 if (LastLoadedElt == NumElems - 1) {
4981 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4982 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4983 LDBase->getPointerInfo(),
4984 LDBase->isVolatile(), LDBase->isNonTemporal(),
4985 LDBase->isInvariant(), 0);
4986 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4987 LDBase->getPointerInfo(),
4988 LDBase->isVolatile(), LDBase->isNonTemporal(),
4989 LDBase->isInvariant(), LDBase->getAlignment());
4991 if (NumElems == 4 && LastLoadedElt == 1 &&
4992 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4993 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4994 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4996 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4997 LDBase->getPointerInfo(),
4998 LDBase->getAlignment(),
4999 false/*isVolatile*/, true/*ReadMem*/,
5002 // Make sure the newly-created LOAD is in the same position as LDBase in
5003 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5004 // update uses of LDBase's output chain to use the TokenFactor.
5005 if (LDBase->hasAnyUseOfValue(1)) {
5006 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5007 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5008 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5009 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5010 SDValue(ResNode.getNode(), 1));
5013 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5018 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5019 /// to generate a splat value for the following cases:
5020 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5021 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5022 /// a scalar load, or a constant.
5023 /// The VBROADCAST node is returned when a pattern is found,
5024 /// or SDValue() otherwise.
5026 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5027 if (!Subtarget->hasAVX())
5030 EVT VT = Op.getValueType();
5031 DebugLoc dl = Op.getDebugLoc();
5033 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5034 "Unsupported vector type for broadcast.");
5039 switch (Op.getOpcode()) {
5041 // Unknown pattern found.
5044 case ISD::BUILD_VECTOR: {
5045 // The BUILD_VECTOR node must be a splat.
5046 if (!isSplatVector(Op.getNode()))
5049 Ld = Op.getOperand(0);
5050 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5051 Ld.getOpcode() == ISD::ConstantFP);
5053 // The suspected load node has several users. Make sure that all
5054 // of its users are from the BUILD_VECTOR node.
5055 // Constants may have multiple users.
5056 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5061 case ISD::VECTOR_SHUFFLE: {
5062 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5064 // Shuffles must have a splat mask where the first element is
5066 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5069 SDValue Sc = Op.getOperand(0);
5070 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5071 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5073 if (!Subtarget->hasAVX2())
5076 // Use the register form of the broadcast instruction available on AVX2.
5077 if (VT.is256BitVector())
5078 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5079 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5082 Ld = Sc.getOperand(0);
5083 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5084 Ld.getOpcode() == ISD::ConstantFP);
5086 // The scalar_to_vector node and the suspected
5087 // load node must have exactly one user.
5088 // Constants may have multiple users.
5089 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5095 bool Is256 = VT.is256BitVector();
5097 // Handle the broadcasting a single constant scalar from the constant pool
5098 // into a vector. On Sandybridge it is still better to load a constant vector
5099 // from the constant pool and not to broadcast it from a scalar.
5100 if (ConstSplatVal && Subtarget->hasAVX2()) {
5101 EVT CVT = Ld.getValueType();
5102 assert(!CVT.isVector() && "Must not broadcast a vector type");
5103 unsigned ScalarSize = CVT.getSizeInBits();
5105 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5106 const Constant *C = 0;
5107 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5108 C = CI->getConstantIntValue();
5109 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5110 C = CF->getConstantFPValue();
5112 assert(C && "Invalid constant type");
5114 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5115 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5116 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5117 MachinePointerInfo::getConstantPool(),
5118 false, false, false, Alignment);
5120 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5124 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5125 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5127 // Handle AVX2 in-register broadcasts.
5128 if (!IsLoad && Subtarget->hasAVX2() &&
5129 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5130 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5132 // The scalar source must be a normal load.
5136 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5137 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5139 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5140 // double since there is no vbroadcastsd xmm
5141 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5142 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5143 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5146 // Unsupported broadcast.
5150 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5151 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5152 // constraint of matching input/output vector elements.
5154 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5155 DebugLoc DL = Op.getDebugLoc();
5156 SDNode *N = Op.getNode();
5157 EVT VT = Op.getValueType();
5158 unsigned NumElts = Op.getNumOperands();
5160 // Check supported types and sub-targets.
5162 // Only v2f32 -> v2f64 needs special handling.
5163 if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5168 SmallVector<int, 8> Mask;
5169 EVT SrcVT = MVT::Other;
5171 // Check the patterns could be translated into X86vfpext.
5172 for (unsigned i = 0; i < NumElts; ++i) {
5173 SDValue In = N->getOperand(i);
5174 unsigned Opcode = In.getOpcode();
5176 // Skip if the element is undefined.
5177 if (Opcode == ISD::UNDEF) {
5182 // Quit if one of the elements is not defined from 'fpext'.
5183 if (Opcode != ISD::FP_EXTEND)
5186 // Check how the source of 'fpext' is defined.
5187 SDValue L2In = In.getOperand(0);
5188 EVT L2InVT = L2In.getValueType();
5190 // Check the original type
5191 if (SrcVT == MVT::Other)
5193 else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5196 // Check whether the value being 'fpext'ed is extracted from the same
5198 Opcode = L2In.getOpcode();
5200 // Quit if it's not extracted with a constant index.
5201 if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5202 !isa<ConstantSDNode>(L2In.getOperand(1)))
5205 SDValue ExtractedFromVec = L2In.getOperand(0);
5207 if (VecIn.getNode() == 0) {
5208 VecIn = ExtractedFromVec;
5209 VecInVT = ExtractedFromVec.getValueType();
5210 } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5213 Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5216 // Quit if all operands of BUILD_VECTOR are undefined.
5217 if (!VecIn.getNode())
5220 // Fill the remaining mask as undef.
5221 for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5224 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5225 DAG.getVectorShuffle(VecInVT, DL,
5226 VecIn, DAG.getUNDEF(VecInVT),
5231 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5232 DebugLoc dl = Op.getDebugLoc();
5234 EVT VT = Op.getValueType();
5235 EVT ExtVT = VT.getVectorElementType();
5236 unsigned NumElems = Op.getNumOperands();
5238 // Vectors containing all zeros can be matched by pxor and xorps later
5239 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5240 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5241 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5242 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5245 return getZeroVector(VT, Subtarget, DAG, dl);
5248 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5249 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5250 // vpcmpeqd on 256-bit vectors.
5251 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5252 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5255 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5258 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5259 if (Broadcast.getNode())
5262 SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5263 if (FpExt.getNode())
5266 unsigned EVTBits = ExtVT.getSizeInBits();
5268 unsigned NumZero = 0;
5269 unsigned NumNonZero = 0;
5270 unsigned NonZeros = 0;
5271 bool IsAllConstants = true;
5272 SmallSet<SDValue, 8> Values;
5273 for (unsigned i = 0; i < NumElems; ++i) {
5274 SDValue Elt = Op.getOperand(i);
5275 if (Elt.getOpcode() == ISD::UNDEF)
5278 if (Elt.getOpcode() != ISD::Constant &&
5279 Elt.getOpcode() != ISD::ConstantFP)
5280 IsAllConstants = false;
5281 if (X86::isZeroNode(Elt))
5284 NonZeros |= (1 << i);
5289 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5290 if (NumNonZero == 0)
5291 return DAG.getUNDEF(VT);
5293 // Special case for single non-zero, non-undef, element.
5294 if (NumNonZero == 1) {
5295 unsigned Idx = CountTrailingZeros_32(NonZeros);
5296 SDValue Item = Op.getOperand(Idx);
5298 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5299 // the value are obviously zero, truncate the value to i32 and do the
5300 // insertion that way. Only do this if the value is non-constant or if the
5301 // value is a constant being inserted into element 0. It is cheaper to do
5302 // a constant pool load than it is to do a movd + shuffle.
5303 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5304 (!IsAllConstants || Idx == 0)) {
5305 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5307 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5308 EVT VecVT = MVT::v4i32;
5309 unsigned VecElts = 4;
5311 // Truncate the value (which may itself be a constant) to i32, and
5312 // convert it to a vector with movd (S2V+shuffle to zero extend).
5313 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5314 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5315 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5317 // Now we have our 32-bit value zero extended in the low element of
5318 // a vector. If Idx != 0, swizzle it into place.
5320 SmallVector<int, 4> Mask;
5321 Mask.push_back(Idx);
5322 for (unsigned i = 1; i != VecElts; ++i)
5324 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5327 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5331 // If we have a constant or non-constant insertion into the low element of
5332 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5333 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5334 // depending on what the source datatype is.
5337 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5339 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5340 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5341 if (VT.is256BitVector()) {
5342 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5343 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5344 Item, DAG.getIntPtrConstant(0));
5346 assert(VT.is128BitVector() && "Expected an SSE value type!");
5347 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5348 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5349 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5352 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5353 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5354 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5355 if (VT.is256BitVector()) {
5356 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5357 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5359 assert(VT.is128BitVector() && "Expected an SSE value type!");
5360 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5362 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5366 // Is it a vector logical left shift?
5367 if (NumElems == 2 && Idx == 1 &&
5368 X86::isZeroNode(Op.getOperand(0)) &&
5369 !X86::isZeroNode(Op.getOperand(1))) {
5370 unsigned NumBits = VT.getSizeInBits();
5371 return getVShift(true, VT,
5372 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5373 VT, Op.getOperand(1)),
5374 NumBits/2, DAG, *this, dl);
5377 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5380 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5381 // is a non-constant being inserted into an element other than the low one,
5382 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5383 // movd/movss) to move this into the low element, then shuffle it into
5385 if (EVTBits == 32) {
5386 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5388 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5389 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5390 SmallVector<int, 8> MaskVec;
5391 for (unsigned i = 0; i != NumElems; ++i)
5392 MaskVec.push_back(i == Idx ? 0 : 1);
5393 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5397 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5398 if (Values.size() == 1) {
5399 if (EVTBits == 32) {
5400 // Instead of a shuffle like this:
5401 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5402 // Check if it's possible to issue this instead.
5403 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5404 unsigned Idx = CountTrailingZeros_32(NonZeros);
5405 SDValue Item = Op.getOperand(Idx);
5406 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5407 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5412 // A vector full of immediates; various special cases are already
5413 // handled, so this is best done with a single constant-pool load.
5417 // For AVX-length vectors, build the individual 128-bit pieces and use
5418 // shuffles to put them in place.
5419 if (VT.is256BitVector()) {
5420 SmallVector<SDValue, 32> V;
5421 for (unsigned i = 0; i != NumElems; ++i)
5422 V.push_back(Op.getOperand(i));
5424 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5426 // Build both the lower and upper subvector.
5427 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5428 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5431 // Recreate the wider vector with the lower and upper part.
5432 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5435 // Let legalizer expand 2-wide build_vectors.
5436 if (EVTBits == 64) {
5437 if (NumNonZero == 1) {
5438 // One half is zero or undef.
5439 unsigned Idx = CountTrailingZeros_32(NonZeros);
5440 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5441 Op.getOperand(Idx));
5442 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5447 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5448 if (EVTBits == 8 && NumElems == 16) {
5449 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5451 if (V.getNode()) return V;
5454 if (EVTBits == 16 && NumElems == 8) {
5455 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5457 if (V.getNode()) return V;
5460 // If element VT is == 32 bits, turn it into a number of shuffles.
5461 SmallVector<SDValue, 8> V(NumElems);
5462 if (NumElems == 4 && NumZero > 0) {
5463 for (unsigned i = 0; i < 4; ++i) {
5464 bool isZero = !(NonZeros & (1 << i));
5466 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5468 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5471 for (unsigned i = 0; i < 2; ++i) {
5472 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5475 V[i] = V[i*2]; // Must be a zero vector.
5478 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5481 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5484 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5489 bool Reverse1 = (NonZeros & 0x3) == 2;
5490 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5494 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5495 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5497 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5500 if (Values.size() > 1 && VT.is128BitVector()) {
5501 // Check for a build vector of consecutive loads.
5502 for (unsigned i = 0; i < NumElems; ++i)
5503 V[i] = Op.getOperand(i);
5505 // Check for elements which are consecutive loads.
5506 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5510 // For SSE 4.1, use insertps to put the high elements into the low element.
5511 if (getSubtarget()->hasSSE41()) {
5513 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5514 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5516 Result = DAG.getUNDEF(VT);
5518 for (unsigned i = 1; i < NumElems; ++i) {
5519 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5520 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5521 Op.getOperand(i), DAG.getIntPtrConstant(i));
5526 // Otherwise, expand into a number of unpckl*, start by extending each of
5527 // our (non-undef) elements to the full vector width with the element in the
5528 // bottom slot of the vector (which generates no code for SSE).
5529 for (unsigned i = 0; i < NumElems; ++i) {
5530 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5531 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5533 V[i] = DAG.getUNDEF(VT);
5536 // Next, we iteratively mix elements, e.g. for v4f32:
5537 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5538 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5539 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5540 unsigned EltStride = NumElems >> 1;
5541 while (EltStride != 0) {
5542 for (unsigned i = 0; i < EltStride; ++i) {
5543 // If V[i+EltStride] is undef and this is the first round of mixing,
5544 // then it is safe to just drop this shuffle: V[i] is already in the
5545 // right place, the one element (since it's the first round) being
5546 // inserted as undef can be dropped. This isn't safe for successive
5547 // rounds because they will permute elements within both vectors.
5548 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5549 EltStride == NumElems/2)
5552 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5561 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5562 // to create 256-bit vectors from two other 128-bit ones.
5563 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5564 DebugLoc dl = Op.getDebugLoc();
5565 EVT ResVT = Op.getValueType();
5567 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5569 SDValue V1 = Op.getOperand(0);
5570 SDValue V2 = Op.getOperand(1);
5571 unsigned NumElems = ResVT.getVectorNumElements();
5573 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5576 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5577 assert(Op.getNumOperands() == 2);
5579 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5580 // from two other 128-bit ones.
5581 return LowerAVXCONCAT_VECTORS(Op, DAG);
5584 // Try to lower a shuffle node into a simple blend instruction.
5586 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5587 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5588 SDValue V1 = SVOp->getOperand(0);
5589 SDValue V2 = SVOp->getOperand(1);
5590 DebugLoc dl = SVOp->getDebugLoc();
5591 MVT VT = SVOp->getValueType(0).getSimpleVT();
5592 unsigned NumElems = VT.getVectorNumElements();
5594 if (!Subtarget->hasSSE41())
5600 switch (VT.SimpleTy) {
5601 default: return SDValue();
5603 ISDNo = X86ISD::BLENDPW;
5608 ISDNo = X86ISD::BLENDPS;
5613 ISDNo = X86ISD::BLENDPD;
5618 if (!Subtarget->hasAVX())
5620 ISDNo = X86ISD::BLENDPS;
5625 if (!Subtarget->hasAVX())
5627 ISDNo = X86ISD::BLENDPD;
5631 assert(ISDNo && "Invalid Op Number");
5633 unsigned MaskVals = 0;
5635 for (unsigned i = 0; i != NumElems; ++i) {
5636 int EltIdx = SVOp->getMaskElt(i);
5637 if (EltIdx == (int)i || EltIdx < 0)
5639 else if (EltIdx == (int)(i + NumElems))
5640 continue; // Bit is set to zero;
5645 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5646 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5647 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5648 DAG.getConstant(MaskVals, MVT::i32));
5649 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5652 // v8i16 shuffles - Prefer shuffles in the following order:
5653 // 1. [all] pshuflw, pshufhw, optional move
5654 // 2. [ssse3] 1 x pshufb
5655 // 3. [ssse3] 2 x pshufb + 1 x por
5656 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5658 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5659 SelectionDAG &DAG) {
5660 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5661 SDValue V1 = SVOp->getOperand(0);
5662 SDValue V2 = SVOp->getOperand(1);
5663 DebugLoc dl = SVOp->getDebugLoc();
5664 SmallVector<int, 8> MaskVals;
5666 // Determine if more than 1 of the words in each of the low and high quadwords
5667 // of the result come from the same quadword of one of the two inputs. Undef
5668 // mask values count as coming from any quadword, for better codegen.
5669 unsigned LoQuad[] = { 0, 0, 0, 0 };
5670 unsigned HiQuad[] = { 0, 0, 0, 0 };
5671 std::bitset<4> InputQuads;
5672 for (unsigned i = 0; i < 8; ++i) {
5673 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5674 int EltIdx = SVOp->getMaskElt(i);
5675 MaskVals.push_back(EltIdx);
5684 InputQuads.set(EltIdx / 4);
5687 int BestLoQuad = -1;
5688 unsigned MaxQuad = 1;
5689 for (unsigned i = 0; i < 4; ++i) {
5690 if (LoQuad[i] > MaxQuad) {
5692 MaxQuad = LoQuad[i];
5696 int BestHiQuad = -1;
5698 for (unsigned i = 0; i < 4; ++i) {
5699 if (HiQuad[i] > MaxQuad) {
5701 MaxQuad = HiQuad[i];
5705 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5706 // of the two input vectors, shuffle them into one input vector so only a
5707 // single pshufb instruction is necessary. If There are more than 2 input
5708 // quads, disable the next transformation since it does not help SSSE3.
5709 bool V1Used = InputQuads[0] || InputQuads[1];
5710 bool V2Used = InputQuads[2] || InputQuads[3];
5711 if (Subtarget->hasSSSE3()) {
5712 if (InputQuads.count() == 2 && V1Used && V2Used) {
5713 BestLoQuad = InputQuads[0] ? 0 : 1;
5714 BestHiQuad = InputQuads[2] ? 2 : 3;
5716 if (InputQuads.count() > 2) {
5722 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5723 // the shuffle mask. If a quad is scored as -1, that means that it contains
5724 // words from all 4 input quadwords.
5726 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5728 BestLoQuad < 0 ? 0 : BestLoQuad,
5729 BestHiQuad < 0 ? 1 : BestHiQuad
5731 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5732 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5733 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5734 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5736 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5737 // source words for the shuffle, to aid later transformations.
5738 bool AllWordsInNewV = true;
5739 bool InOrder[2] = { true, true };
5740 for (unsigned i = 0; i != 8; ++i) {
5741 int idx = MaskVals[i];
5743 InOrder[i/4] = false;
5744 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5746 AllWordsInNewV = false;
5750 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5751 if (AllWordsInNewV) {
5752 for (int i = 0; i != 8; ++i) {
5753 int idx = MaskVals[i];
5756 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5757 if ((idx != i) && idx < 4)
5759 if ((idx != i) && idx > 3)
5768 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5769 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5770 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5771 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5772 unsigned TargetMask = 0;
5773 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5774 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5775 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5776 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5777 getShufflePSHUFLWImmediate(SVOp);
5778 V1 = NewV.getOperand(0);
5779 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5783 // If we have SSSE3, and all words of the result are from 1 input vector,
5784 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5785 // is present, fall back to case 4.
5786 if (Subtarget->hasSSSE3()) {
5787 SmallVector<SDValue,16> pshufbMask;
5789 // If we have elements from both input vectors, set the high bit of the
5790 // shuffle mask element to zero out elements that come from V2 in the V1
5791 // mask, and elements that come from V1 in the V2 mask, so that the two
5792 // results can be OR'd together.
5793 bool TwoInputs = V1Used && V2Used;
5794 for (unsigned i = 0; i != 8; ++i) {
5795 int EltIdx = MaskVals[i] * 2;
5796 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5797 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5798 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5799 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5801 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5802 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5803 DAG.getNode(ISD::BUILD_VECTOR, dl,
5804 MVT::v16i8, &pshufbMask[0], 16));
5806 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5808 // Calculate the shuffle mask for the second input, shuffle it, and
5809 // OR it with the first shuffled input.
5811 for (unsigned i = 0; i != 8; ++i) {
5812 int EltIdx = MaskVals[i] * 2;
5813 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5814 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5815 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5816 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5818 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5819 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5820 DAG.getNode(ISD::BUILD_VECTOR, dl,
5821 MVT::v16i8, &pshufbMask[0], 16));
5822 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5823 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5826 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5827 // and update MaskVals with new element order.
5828 std::bitset<8> InOrder;
5829 if (BestLoQuad >= 0) {
5830 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5831 for (int i = 0; i != 4; ++i) {
5832 int idx = MaskVals[i];
5835 } else if ((idx / 4) == BestLoQuad) {
5840 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5843 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5844 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5845 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5847 getShufflePSHUFLWImmediate(SVOp), DAG);
5851 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5852 // and update MaskVals with the new element order.
5853 if (BestHiQuad >= 0) {
5854 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5855 for (unsigned i = 4; i != 8; ++i) {
5856 int idx = MaskVals[i];
5859 } else if ((idx / 4) == BestHiQuad) {
5860 MaskV[i] = (idx & 3) + 4;
5864 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5867 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5868 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5869 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5871 getShufflePSHUFHWImmediate(SVOp), DAG);
5875 // In case BestHi & BestLo were both -1, which means each quadword has a word
5876 // from each of the four input quadwords, calculate the InOrder bitvector now
5877 // before falling through to the insert/extract cleanup.
5878 if (BestLoQuad == -1 && BestHiQuad == -1) {
5880 for (int i = 0; i != 8; ++i)
5881 if (MaskVals[i] < 0 || MaskVals[i] == i)
5885 // The other elements are put in the right place using pextrw and pinsrw.
5886 for (unsigned i = 0; i != 8; ++i) {
5889 int EltIdx = MaskVals[i];
5892 SDValue ExtOp = (EltIdx < 8) ?
5893 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5894 DAG.getIntPtrConstant(EltIdx)) :
5895 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5896 DAG.getIntPtrConstant(EltIdx - 8));
5897 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5898 DAG.getIntPtrConstant(i));
5903 // v16i8 shuffles - Prefer shuffles in the following order:
5904 // 1. [ssse3] 1 x pshufb
5905 // 2. [ssse3] 2 x pshufb + 1 x por
5906 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5908 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5910 const X86TargetLowering &TLI) {
5911 SDValue V1 = SVOp->getOperand(0);
5912 SDValue V2 = SVOp->getOperand(1);
5913 DebugLoc dl = SVOp->getDebugLoc();
5914 ArrayRef<int> MaskVals = SVOp->getMask();
5916 // If we have SSSE3, case 1 is generated when all result bytes come from
5917 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5918 // present, fall back to case 3.
5920 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5921 if (TLI.getSubtarget()->hasSSSE3()) {
5922 SmallVector<SDValue,16> pshufbMask;
5924 // If all result elements are from one input vector, then only translate
5925 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5927 // Otherwise, we have elements from both input vectors, and must zero out
5928 // elements that come from V2 in the first mask, and V1 in the second mask
5929 // so that we can OR them together.
5930 for (unsigned i = 0; i != 16; ++i) {
5931 int EltIdx = MaskVals[i];
5932 if (EltIdx < 0 || EltIdx >= 16)
5934 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5936 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5937 DAG.getNode(ISD::BUILD_VECTOR, dl,
5938 MVT::v16i8, &pshufbMask[0], 16));
5940 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5941 // the 2nd operand if it's undefined or zero.
5942 if (V2.getOpcode() == ISD::UNDEF ||
5943 ISD::isBuildVectorAllZeros(V2.getNode()))
5946 // Calculate the shuffle mask for the second input, shuffle it, and
5947 // OR it with the first shuffled input.
5949 for (unsigned i = 0; i != 16; ++i) {
5950 int EltIdx = MaskVals[i];
5951 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5952 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5954 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5955 DAG.getNode(ISD::BUILD_VECTOR, dl,
5956 MVT::v16i8, &pshufbMask[0], 16));
5957 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5960 // No SSSE3 - Calculate in place words and then fix all out of place words
5961 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5962 // the 16 different words that comprise the two doublequadword input vectors.
5963 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5964 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5966 for (int i = 0; i != 8; ++i) {
5967 int Elt0 = MaskVals[i*2];
5968 int Elt1 = MaskVals[i*2+1];
5970 // This word of the result is all undef, skip it.
5971 if (Elt0 < 0 && Elt1 < 0)
5974 // This word of the result is already in the correct place, skip it.
5975 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5978 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5979 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5982 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5983 // using a single extract together, load it and store it.
5984 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5985 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5986 DAG.getIntPtrConstant(Elt1 / 2));
5987 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5988 DAG.getIntPtrConstant(i));
5992 // If Elt1 is defined, extract it from the appropriate source. If the
5993 // source byte is not also odd, shift the extracted word left 8 bits
5994 // otherwise clear the bottom 8 bits if we need to do an or.
5996 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5997 DAG.getIntPtrConstant(Elt1 / 2));
5998 if ((Elt1 & 1) == 0)
5999 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6001 TLI.getShiftAmountTy(InsElt.getValueType())));
6003 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6004 DAG.getConstant(0xFF00, MVT::i16));
6006 // If Elt0 is defined, extract it from the appropriate source. If the
6007 // source byte is not also even, shift the extracted word right 8 bits. If
6008 // Elt1 was also defined, OR the extracted values together before
6009 // inserting them in the result.
6011 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6012 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6013 if ((Elt0 & 1) != 0)
6014 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6016 TLI.getShiftAmountTy(InsElt0.getValueType())));
6018 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6019 DAG.getConstant(0x00FF, MVT::i16));
6020 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6023 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6024 DAG.getIntPtrConstant(i));
6026 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6029 // v32i8 shuffles - Translate to VPSHUFB if possible.
6031 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6032 const X86Subtarget *Subtarget,
6033 SelectionDAG &DAG) {
6034 EVT VT = SVOp->getValueType(0);
6035 SDValue V1 = SVOp->getOperand(0);
6036 SDValue V2 = SVOp->getOperand(1);
6037 DebugLoc dl = SVOp->getDebugLoc();
6038 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6040 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6041 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6042 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6044 // VPSHUFB may be generated if
6045 // (1) one of input vector is undefined or zeroinitializer.
6046 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6047 // And (2) the mask indexes don't cross the 128-bit lane.
6048 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6049 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6052 if (V1IsAllZero && !V2IsAllZero) {
6053 CommuteVectorShuffleMask(MaskVals, 32);
6056 SmallVector<SDValue, 32> pshufbMask;
6057 for (unsigned i = 0; i != 32; i++) {
6058 int EltIdx = MaskVals[i];
6059 if (EltIdx < 0 || EltIdx >= 32)
6062 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6063 // Cross lane is not allowed.
6067 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6069 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6070 DAG.getNode(ISD::BUILD_VECTOR, dl,
6071 MVT::v32i8, &pshufbMask[0], 32));
6074 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6075 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6076 /// done when every pair / quad of shuffle mask elements point to elements in
6077 /// the right sequence. e.g.
6078 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6080 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6081 SelectionDAG &DAG, DebugLoc dl) {
6082 MVT VT = SVOp->getValueType(0).getSimpleVT();
6083 unsigned NumElems = VT.getVectorNumElements();
6086 switch (VT.SimpleTy) {
6087 default: llvm_unreachable("Unexpected!");
6088 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6089 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6090 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6091 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6092 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6093 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6096 SmallVector<int, 8> MaskVec;
6097 for (unsigned i = 0; i != NumElems; i += Scale) {
6099 for (unsigned j = 0; j != Scale; ++j) {
6100 int EltIdx = SVOp->getMaskElt(i+j);
6104 StartIdx = (EltIdx / Scale);
6105 if (EltIdx != (int)(StartIdx*Scale + j))
6108 MaskVec.push_back(StartIdx);
6111 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6112 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6113 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6116 /// getVZextMovL - Return a zero-extending vector move low node.
6118 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6119 SDValue SrcOp, SelectionDAG &DAG,
6120 const X86Subtarget *Subtarget, DebugLoc dl) {
6121 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6122 LoadSDNode *LD = NULL;
6123 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6124 LD = dyn_cast<LoadSDNode>(SrcOp);
6126 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6128 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6129 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6130 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6131 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6132 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6134 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6135 return DAG.getNode(ISD::BITCAST, dl, VT,
6136 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6137 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6145 return DAG.getNode(ISD::BITCAST, dl, VT,
6146 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6147 DAG.getNode(ISD::BITCAST, dl,
6151 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6152 /// which could not be matched by any known target speficic shuffle
6154 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6156 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6157 if (NewOp.getNode())
6160 EVT VT = SVOp->getValueType(0);
6162 unsigned NumElems = VT.getVectorNumElements();
6163 unsigned NumLaneElems = NumElems / 2;
6165 DebugLoc dl = SVOp->getDebugLoc();
6166 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6167 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6170 SmallVector<int, 16> Mask;
6171 for (unsigned l = 0; l < 2; ++l) {
6172 // Build a shuffle mask for the output, discovering on the fly which
6173 // input vectors to use as shuffle operands (recorded in InputUsed).
6174 // If building a suitable shuffle vector proves too hard, then bail
6175 // out with UseBuildVector set.
6176 bool UseBuildVector = false;
6177 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6178 unsigned LaneStart = l * NumLaneElems;
6179 for (unsigned i = 0; i != NumLaneElems; ++i) {
6180 // The mask element. This indexes into the input.
6181 int Idx = SVOp->getMaskElt(i+LaneStart);
6183 // the mask element does not index into any input vector.
6188 // The input vector this mask element indexes into.
6189 int Input = Idx / NumLaneElems;
6191 // Turn the index into an offset from the start of the input vector.
6192 Idx -= Input * NumLaneElems;
6194 // Find or create a shuffle vector operand to hold this input.
6196 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6197 if (InputUsed[OpNo] == Input)
6198 // This input vector is already an operand.
6200 if (InputUsed[OpNo] < 0) {
6201 // Create a new operand for this input vector.
6202 InputUsed[OpNo] = Input;
6207 if (OpNo >= array_lengthof(InputUsed)) {
6208 // More than two input vectors used! Give up on trying to create a
6209 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6210 UseBuildVector = true;
6214 // Add the mask index for the new shuffle vector.
6215 Mask.push_back(Idx + OpNo * NumLaneElems);
6218 if (UseBuildVector) {
6219 SmallVector<SDValue, 16> SVOps;
6220 for (unsigned i = 0; i != NumLaneElems; ++i) {
6221 // The mask element. This indexes into the input.
6222 int Idx = SVOp->getMaskElt(i+LaneStart);
6224 SVOps.push_back(DAG.getUNDEF(EltVT));
6228 // The input vector this mask element indexes into.
6229 int Input = Idx / NumElems;
6231 // Turn the index into an offset from the start of the input vector.
6232 Idx -= Input * NumElems;
6234 // Extract the vector element by hand.
6235 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6236 SVOp->getOperand(Input),
6237 DAG.getIntPtrConstant(Idx)));
6240 // Construct the output using a BUILD_VECTOR.
6241 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6243 } else if (InputUsed[0] < 0) {
6244 // No input vectors were used! The result is undefined.
6245 Output[l] = DAG.getUNDEF(NVT);
6247 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6248 (InputUsed[0] % 2) * NumLaneElems,
6250 // If only one input was used, use an undefined vector for the other.
6251 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6252 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6253 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6254 // At least one input vector was used. Create a new shuffle vector.
6255 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6261 // Concatenate the result back
6262 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6265 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6266 /// 4 elements, and match them with several different shuffle types.
6268 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6269 SDValue V1 = SVOp->getOperand(0);
6270 SDValue V2 = SVOp->getOperand(1);
6271 DebugLoc dl = SVOp->getDebugLoc();
6272 EVT VT = SVOp->getValueType(0);
6274 assert(VT.is128BitVector() && "Unsupported vector size");
6276 std::pair<int, int> Locs[4];
6277 int Mask1[] = { -1, -1, -1, -1 };
6278 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6282 for (unsigned i = 0; i != 4; ++i) {
6283 int Idx = PermMask[i];
6285 Locs[i] = std::make_pair(-1, -1);
6287 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6289 Locs[i] = std::make_pair(0, NumLo);
6293 Locs[i] = std::make_pair(1, NumHi);
6295 Mask1[2+NumHi] = Idx;
6301 if (NumLo <= 2 && NumHi <= 2) {
6302 // If no more than two elements come from either vector. This can be
6303 // implemented with two shuffles. First shuffle gather the elements.
6304 // The second shuffle, which takes the first shuffle as both of its
6305 // vector operands, put the elements into the right order.
6306 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6308 int Mask2[] = { -1, -1, -1, -1 };
6310 for (unsigned i = 0; i != 4; ++i)
6311 if (Locs[i].first != -1) {
6312 unsigned Idx = (i < 2) ? 0 : 4;
6313 Idx += Locs[i].first * 2 + Locs[i].second;
6317 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6320 if (NumLo == 3 || NumHi == 3) {
6321 // Otherwise, we must have three elements from one vector, call it X, and
6322 // one element from the other, call it Y. First, use a shufps to build an
6323 // intermediate vector with the one element from Y and the element from X
6324 // that will be in the same half in the final destination (the indexes don't
6325 // matter). Then, use a shufps to build the final vector, taking the half
6326 // containing the element from Y from the intermediate, and the other half
6329 // Normalize it so the 3 elements come from V1.
6330 CommuteVectorShuffleMask(PermMask, 4);
6334 // Find the element from V2.
6336 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6337 int Val = PermMask[HiIndex];
6344 Mask1[0] = PermMask[HiIndex];
6346 Mask1[2] = PermMask[HiIndex^1];
6348 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6351 Mask1[0] = PermMask[0];
6352 Mask1[1] = PermMask[1];
6353 Mask1[2] = HiIndex & 1 ? 6 : 4;
6354 Mask1[3] = HiIndex & 1 ? 4 : 6;
6355 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6358 Mask1[0] = HiIndex & 1 ? 2 : 0;
6359 Mask1[1] = HiIndex & 1 ? 0 : 2;
6360 Mask1[2] = PermMask[2];
6361 Mask1[3] = PermMask[3];
6366 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6369 // Break it into (shuffle shuffle_hi, shuffle_lo).
6370 int LoMask[] = { -1, -1, -1, -1 };
6371 int HiMask[] = { -1, -1, -1, -1 };
6373 int *MaskPtr = LoMask;
6374 unsigned MaskIdx = 0;
6377 for (unsigned i = 0; i != 4; ++i) {
6384 int Idx = PermMask[i];
6386 Locs[i] = std::make_pair(-1, -1);
6387 } else if (Idx < 4) {
6388 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6389 MaskPtr[LoIdx] = Idx;
6392 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6393 MaskPtr[HiIdx] = Idx;
6398 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6399 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6400 int MaskOps[] = { -1, -1, -1, -1 };
6401 for (unsigned i = 0; i != 4; ++i)
6402 if (Locs[i].first != -1)
6403 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6404 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6407 static bool MayFoldVectorLoad(SDValue V) {
6408 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6409 V = V.getOperand(0);
6410 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6411 V = V.getOperand(0);
6412 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6413 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6414 // BUILD_VECTOR (load), undef
6415 V = V.getOperand(0);
6421 // FIXME: the version above should always be used. Since there's
6422 // a bug where several vector shuffles can't be folded because the
6423 // DAG is not updated during lowering and a node claims to have two
6424 // uses while it only has one, use this version, and let isel match
6425 // another instruction if the load really happens to have more than
6426 // one use. Remove this version after this bug get fixed.
6427 // rdar://8434668, PR8156
6428 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6429 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6430 V = V.getOperand(0);
6431 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6432 V = V.getOperand(0);
6433 if (ISD::isNormalLoad(V.getNode()))
6439 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6440 EVT VT = Op.getValueType();
6442 // Canonizalize to v2f64.
6443 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6444 return DAG.getNode(ISD::BITCAST, dl, VT,
6445 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6450 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6452 SDValue V1 = Op.getOperand(0);
6453 SDValue V2 = Op.getOperand(1);
6454 EVT VT = Op.getValueType();
6456 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6458 if (HasSSE2 && VT == MVT::v2f64)
6459 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6461 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6462 return DAG.getNode(ISD::BITCAST, dl, VT,
6463 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6464 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6465 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6469 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6470 SDValue V1 = Op.getOperand(0);
6471 SDValue V2 = Op.getOperand(1);
6472 EVT VT = Op.getValueType();
6474 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6475 "unsupported shuffle type");
6477 if (V2.getOpcode() == ISD::UNDEF)
6481 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6485 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6486 SDValue V1 = Op.getOperand(0);
6487 SDValue V2 = Op.getOperand(1);
6488 EVT VT = Op.getValueType();
6489 unsigned NumElems = VT.getVectorNumElements();
6491 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6492 // operand of these instructions is only memory, so check if there's a
6493 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6495 bool CanFoldLoad = false;
6497 // Trivial case, when V2 comes from a load.
6498 if (MayFoldVectorLoad(V2))
6501 // When V1 is a load, it can be folded later into a store in isel, example:
6502 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6504 // (MOVLPSmr addr:$src1, VR128:$src2)
6505 // So, recognize this potential and also use MOVLPS or MOVLPD
6506 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6509 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6511 if (HasSSE2 && NumElems == 2)
6512 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6515 // If we don't care about the second element, proceed to use movss.
6516 if (SVOp->getMaskElt(1) != -1)
6517 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6520 // movl and movlp will both match v2i64, but v2i64 is never matched by
6521 // movl earlier because we make it strict to avoid messing with the movlp load
6522 // folding logic (see the code above getMOVLP call). Match it here then,
6523 // this is horrible, but will stay like this until we move all shuffle
6524 // matching to x86 specific nodes. Note that for the 1st condition all
6525 // types are matched with movsd.
6527 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6528 // as to remove this logic from here, as much as possible
6529 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6530 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6531 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6534 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6536 // Invert the operand order and use SHUFPS to match it.
6537 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6538 getShuffleSHUFImmediate(SVOp), DAG);
6542 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6543 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6544 EVT VT = Op.getValueType();
6545 DebugLoc dl = Op.getDebugLoc();
6546 SDValue V1 = Op.getOperand(0);
6547 SDValue V2 = Op.getOperand(1);
6549 if (isZeroShuffle(SVOp))
6550 return getZeroVector(VT, Subtarget, DAG, dl);
6552 // Handle splat operations
6553 if (SVOp->isSplat()) {
6554 unsigned NumElem = VT.getVectorNumElements();
6555 int Size = VT.getSizeInBits();
6557 // Use vbroadcast whenever the splat comes from a foldable load
6558 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6559 if (Broadcast.getNode())
6562 // Handle splats by matching through known shuffle masks
6563 if ((Size == 128 && NumElem <= 4) ||
6564 (Size == 256 && NumElem < 8))
6567 // All remaning splats are promoted to target supported vector shuffles.
6568 return PromoteSplat(SVOp, DAG);
6571 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6573 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6574 VT == MVT::v16i16 || VT == MVT::v32i8) {
6575 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6576 if (NewOp.getNode())
6577 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6578 } else if ((VT == MVT::v4i32 ||
6579 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6580 // FIXME: Figure out a cleaner way to do this.
6581 // Try to make use of movq to zero out the top part.
6582 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6583 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6584 if (NewOp.getNode()) {
6585 EVT NewVT = NewOp.getValueType();
6586 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6587 NewVT, true, false))
6588 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6589 DAG, Subtarget, dl);
6591 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6592 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6593 if (NewOp.getNode()) {
6594 EVT NewVT = NewOp.getValueType();
6595 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6596 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6597 DAG, Subtarget, dl);
6605 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6606 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6607 SDValue V1 = Op.getOperand(0);
6608 SDValue V2 = Op.getOperand(1);
6609 EVT VT = Op.getValueType();
6610 DebugLoc dl = Op.getDebugLoc();
6611 unsigned NumElems = VT.getVectorNumElements();
6612 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6613 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6614 bool V1IsSplat = false;
6615 bool V2IsSplat = false;
6616 bool HasSSE2 = Subtarget->hasSSE2();
6617 bool HasAVX = Subtarget->hasAVX();
6618 bool HasAVX2 = Subtarget->hasAVX2();
6619 MachineFunction &MF = DAG.getMachineFunction();
6620 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6622 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6624 if (V1IsUndef && V2IsUndef)
6625 return DAG.getUNDEF(VT);
6627 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6629 // Vector shuffle lowering takes 3 steps:
6631 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6632 // narrowing and commutation of operands should be handled.
6633 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6635 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6636 // so the shuffle can be broken into other shuffles and the legalizer can
6637 // try the lowering again.
6639 // The general idea is that no vector_shuffle operation should be left to
6640 // be matched during isel, all of them must be converted to a target specific
6643 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6644 // narrowing and commutation of operands should be handled. The actual code
6645 // doesn't include all of those, work in progress...
6646 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6647 if (NewOp.getNode())
6650 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6652 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6653 // unpckh_undef). Only use pshufd if speed is more important than size.
6654 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6655 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6656 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6657 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6659 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6660 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6661 return getMOVDDup(Op, dl, V1, DAG);
6663 if (isMOVHLPS_v_undef_Mask(M, VT))
6664 return getMOVHighToLow(Op, dl, DAG);
6666 // Use to match splats
6667 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6668 (VT == MVT::v2f64 || VT == MVT::v2i64))
6669 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6671 if (isPSHUFDMask(M, VT)) {
6672 // The actual implementation will match the mask in the if above and then
6673 // during isel it can match several different instructions, not only pshufd
6674 // as its name says, sad but true, emulate the behavior for now...
6675 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6676 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6678 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6680 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6681 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6683 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6684 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6686 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6690 // Check if this can be converted into a logical shift.
6691 bool isLeft = false;
6694 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6695 if (isShift && ShVal.hasOneUse()) {
6696 // If the shifted value has multiple uses, it may be cheaper to use
6697 // v_set0 + movlhps or movhlps, etc.
6698 EVT EltVT = VT.getVectorElementType();
6699 ShAmt *= EltVT.getSizeInBits();
6700 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6703 if (isMOVLMask(M, VT)) {
6704 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6705 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6706 if (!isMOVLPMask(M, VT)) {
6707 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6708 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6710 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6711 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6715 // FIXME: fold these into legal mask.
6716 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6717 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6719 if (isMOVHLPSMask(M, VT))
6720 return getMOVHighToLow(Op, dl, DAG);
6722 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6723 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6725 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6726 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6728 if (isMOVLPMask(M, VT))
6729 return getMOVLP(Op, dl, DAG, HasSSE2);
6731 if (ShouldXformToMOVHLPS(M, VT) ||
6732 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6733 return CommuteVectorShuffle(SVOp, DAG);
6736 // No better options. Use a vshldq / vsrldq.
6737 EVT EltVT = VT.getVectorElementType();
6738 ShAmt *= EltVT.getSizeInBits();
6739 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6742 bool Commuted = false;
6743 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6744 // 1,1,1,1 -> v8i16 though.
6745 V1IsSplat = isSplatVector(V1.getNode());
6746 V2IsSplat = isSplatVector(V2.getNode());
6748 // Canonicalize the splat or undef, if present, to be on the RHS.
6749 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6750 CommuteVectorShuffleMask(M, NumElems);
6752 std::swap(V1IsSplat, V2IsSplat);
6756 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6757 // Shuffling low element of v1 into undef, just return v1.
6760 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6761 // the instruction selector will not match, so get a canonical MOVL with
6762 // swapped operands to undo the commute.
6763 return getMOVL(DAG, dl, VT, V2, V1);
6766 if (isUNPCKLMask(M, VT, HasAVX2))
6767 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6769 if (isUNPCKHMask(M, VT, HasAVX2))
6770 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6773 // Normalize mask so all entries that point to V2 points to its first
6774 // element then try to match unpck{h|l} again. If match, return a
6775 // new vector_shuffle with the corrected mask.p
6776 SmallVector<int, 8> NewMask(M.begin(), M.end());
6777 NormalizeMask(NewMask, NumElems);
6778 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6779 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6780 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6781 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6785 // Commute is back and try unpck* again.
6786 // FIXME: this seems wrong.
6787 CommuteVectorShuffleMask(M, NumElems);
6789 std::swap(V1IsSplat, V2IsSplat);
6792 if (isUNPCKLMask(M, VT, HasAVX2))
6793 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6795 if (isUNPCKHMask(M, VT, HasAVX2))
6796 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6799 // Normalize the node to match x86 shuffle ops if needed
6800 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6801 return CommuteVectorShuffle(SVOp, DAG);
6803 // The checks below are all present in isShuffleMaskLegal, but they are
6804 // inlined here right now to enable us to directly emit target specific
6805 // nodes, and remove one by one until they don't return Op anymore.
6807 if (isPALIGNRMask(M, VT, Subtarget))
6808 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6809 getShufflePALIGNRImmediate(SVOp),
6812 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6813 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6814 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6815 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6818 if (isPSHUFHWMask(M, VT, HasAVX2))
6819 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6820 getShufflePSHUFHWImmediate(SVOp),
6823 if (isPSHUFLWMask(M, VT, HasAVX2))
6824 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6825 getShufflePSHUFLWImmediate(SVOp),
6828 if (isSHUFPMask(M, VT, HasAVX))
6829 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6830 getShuffleSHUFImmediate(SVOp), DAG);
6832 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6833 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6834 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6835 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6837 //===--------------------------------------------------------------------===//
6838 // Generate target specific nodes for 128 or 256-bit shuffles only
6839 // supported in the AVX instruction set.
6842 // Handle VMOVDDUPY permutations
6843 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6844 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6846 // Handle VPERMILPS/D* permutations
6847 if (isVPERMILPMask(M, VT, HasAVX)) {
6848 if (HasAVX2 && VT == MVT::v8i32)
6849 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6850 getShuffleSHUFImmediate(SVOp), DAG);
6851 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6852 getShuffleSHUFImmediate(SVOp), DAG);
6855 // Handle VPERM2F128/VPERM2I128 permutations
6856 if (isVPERM2X128Mask(M, VT, HasAVX))
6857 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6858 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6860 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6861 if (BlendOp.getNode())
6864 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6865 SmallVector<SDValue, 8> permclMask;
6866 for (unsigned i = 0; i != 8; ++i) {
6867 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6869 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6871 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6872 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6873 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6876 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6877 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6878 getShuffleCLImmediate(SVOp), DAG);
6881 //===--------------------------------------------------------------------===//
6882 // Since no target specific shuffle was selected for this generic one,
6883 // lower it into other known shuffles. FIXME: this isn't true yet, but
6884 // this is the plan.
6887 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6888 if (VT == MVT::v8i16) {
6889 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6890 if (NewOp.getNode())
6894 if (VT == MVT::v16i8) {
6895 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6896 if (NewOp.getNode())
6900 if (VT == MVT::v32i8) {
6901 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6902 if (NewOp.getNode())
6906 // Handle all 128-bit wide vectors with 4 elements, and match them with
6907 // several different shuffle types.
6908 if (NumElems == 4 && VT.is128BitVector())
6909 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6911 // Handle general 256-bit shuffles
6912 if (VT.is256BitVector())
6913 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6919 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6920 SelectionDAG &DAG) const {
6921 EVT VT = Op.getValueType();
6922 DebugLoc dl = Op.getDebugLoc();
6924 if (!Op.getOperand(0).getValueType().is128BitVector())
6927 if (VT.getSizeInBits() == 8) {
6928 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6929 Op.getOperand(0), Op.getOperand(1));
6930 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6931 DAG.getValueType(VT));
6932 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6935 if (VT.getSizeInBits() == 16) {
6936 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6937 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6939 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6940 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6941 DAG.getNode(ISD::BITCAST, dl,
6945 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6946 Op.getOperand(0), Op.getOperand(1));
6947 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6948 DAG.getValueType(VT));
6949 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6952 if (VT == MVT::f32) {
6953 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6954 // the result back to FR32 register. It's only worth matching if the
6955 // result has a single use which is a store or a bitcast to i32. And in
6956 // the case of a store, it's not worth it if the index is a constant 0,
6957 // because a MOVSSmr can be used instead, which is smaller and faster.
6958 if (!Op.hasOneUse())
6960 SDNode *User = *Op.getNode()->use_begin();
6961 if ((User->getOpcode() != ISD::STORE ||
6962 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6963 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6964 (User->getOpcode() != ISD::BITCAST ||
6965 User->getValueType(0) != MVT::i32))
6967 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6968 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6971 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6974 if (VT == MVT::i32 || VT == MVT::i64) {
6975 // ExtractPS/pextrq works with constant index.
6976 if (isa<ConstantSDNode>(Op.getOperand(1)))
6984 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6985 SelectionDAG &DAG) const {
6986 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6989 SDValue Vec = Op.getOperand(0);
6990 EVT VecVT = Vec.getValueType();
6992 // If this is a 256-bit vector result, first extract the 128-bit vector and
6993 // then extract the element from the 128-bit vector.
6994 if (VecVT.is256BitVector()) {
6995 DebugLoc dl = Op.getNode()->getDebugLoc();
6996 unsigned NumElems = VecVT.getVectorNumElements();
6997 SDValue Idx = Op.getOperand(1);
6998 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7000 // Get the 128-bit vector.
7001 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7003 if (IdxVal >= NumElems/2)
7004 IdxVal -= NumElems/2;
7005 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7006 DAG.getConstant(IdxVal, MVT::i32));
7009 assert(VecVT.is128BitVector() && "Unexpected vector length");
7011 if (Subtarget->hasSSE41()) {
7012 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7017 EVT VT = Op.getValueType();
7018 DebugLoc dl = Op.getDebugLoc();
7019 // TODO: handle v16i8.
7020 if (VT.getSizeInBits() == 16) {
7021 SDValue Vec = Op.getOperand(0);
7022 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7024 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7025 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7026 DAG.getNode(ISD::BITCAST, dl,
7029 // Transform it so it match pextrw which produces a 32-bit result.
7030 EVT EltVT = MVT::i32;
7031 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7032 Op.getOperand(0), Op.getOperand(1));
7033 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7034 DAG.getValueType(VT));
7035 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7038 if (VT.getSizeInBits() == 32) {
7039 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7043 // SHUFPS the element to the lowest double word, then movss.
7044 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7045 EVT VVT = Op.getOperand(0).getValueType();
7046 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7047 DAG.getUNDEF(VVT), Mask);
7048 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7049 DAG.getIntPtrConstant(0));
7052 if (VT.getSizeInBits() == 64) {
7053 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7054 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7055 // to match extract_elt for f64.
7056 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7060 // UNPCKHPD the element to the lowest double word, then movsd.
7061 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7062 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7063 int Mask[2] = { 1, -1 };
7064 EVT VVT = Op.getOperand(0).getValueType();
7065 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7066 DAG.getUNDEF(VVT), Mask);
7067 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7068 DAG.getIntPtrConstant(0));
7075 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7076 SelectionDAG &DAG) const {
7077 EVT VT = Op.getValueType();
7078 EVT EltVT = VT.getVectorElementType();
7079 DebugLoc dl = Op.getDebugLoc();
7081 SDValue N0 = Op.getOperand(0);
7082 SDValue N1 = Op.getOperand(1);
7083 SDValue N2 = Op.getOperand(2);
7085 if (!VT.is128BitVector())
7088 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7089 isa<ConstantSDNode>(N2)) {
7091 if (VT == MVT::v8i16)
7092 Opc = X86ISD::PINSRW;
7093 else if (VT == MVT::v16i8)
7094 Opc = X86ISD::PINSRB;
7096 Opc = X86ISD::PINSRB;
7098 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7100 if (N1.getValueType() != MVT::i32)
7101 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7102 if (N2.getValueType() != MVT::i32)
7103 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7104 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7107 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7108 // Bits [7:6] of the constant are the source select. This will always be
7109 // zero here. The DAG Combiner may combine an extract_elt index into these
7110 // bits. For example (insert (extract, 3), 2) could be matched by putting
7111 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7112 // Bits [5:4] of the constant are the destination select. This is the
7113 // value of the incoming immediate.
7114 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7115 // combine either bitwise AND or insert of float 0.0 to set these bits.
7116 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7117 // Create this as a scalar to vector..
7118 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7119 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7122 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7123 // PINSR* works with constant index.
7130 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7131 EVT VT = Op.getValueType();
7132 EVT EltVT = VT.getVectorElementType();
7134 DebugLoc dl = Op.getDebugLoc();
7135 SDValue N0 = Op.getOperand(0);
7136 SDValue N1 = Op.getOperand(1);
7137 SDValue N2 = Op.getOperand(2);
7139 // If this is a 256-bit vector result, first extract the 128-bit vector,
7140 // insert the element into the extracted half and then place it back.
7141 if (VT.is256BitVector()) {
7142 if (!isa<ConstantSDNode>(N2))
7145 // Get the desired 128-bit vector half.
7146 unsigned NumElems = VT.getVectorNumElements();
7147 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7148 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7150 // Insert the element into the desired half.
7151 bool Upper = IdxVal >= NumElems/2;
7152 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7153 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7155 // Insert the changed part back to the 256-bit vector
7156 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7159 if (Subtarget->hasSSE41())
7160 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7162 if (EltVT == MVT::i8)
7165 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7166 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7167 // as its second argument.
7168 if (N1.getValueType() != MVT::i32)
7169 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7170 if (N2.getValueType() != MVT::i32)
7171 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7172 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7177 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7178 LLVMContext *Context = DAG.getContext();
7179 DebugLoc dl = Op.getDebugLoc();
7180 EVT OpVT = Op.getValueType();
7182 // If this is a 256-bit vector result, first insert into a 128-bit
7183 // vector and then insert into the 256-bit vector.
7184 if (!OpVT.is128BitVector()) {
7185 // Insert into a 128-bit vector.
7186 EVT VT128 = EVT::getVectorVT(*Context,
7187 OpVT.getVectorElementType(),
7188 OpVT.getVectorNumElements() / 2);
7190 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7192 // Insert the 128-bit vector.
7193 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7196 if (OpVT == MVT::v1i64 &&
7197 Op.getOperand(0).getValueType() == MVT::i64)
7198 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7200 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7201 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7202 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7203 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7206 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7207 // a simple subregister reference or explicit instructions to grab
7208 // upper bits of a vector.
7209 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7210 SelectionDAG &DAG) {
7211 if (Subtarget->hasAVX()) {
7212 DebugLoc dl = Op.getNode()->getDebugLoc();
7213 SDValue Vec = Op.getNode()->getOperand(0);
7214 SDValue Idx = Op.getNode()->getOperand(1);
7216 if (Op.getNode()->getValueType(0).is128BitVector() &&
7217 Vec.getNode()->getValueType(0).is256BitVector() &&
7218 isa<ConstantSDNode>(Idx)) {
7219 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7220 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7226 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7227 // simple superregister reference or explicit instructions to insert
7228 // the upper bits of a vector.
7229 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7230 SelectionDAG &DAG) {
7231 if (Subtarget->hasAVX()) {
7232 DebugLoc dl = Op.getNode()->getDebugLoc();
7233 SDValue Vec = Op.getNode()->getOperand(0);
7234 SDValue SubVec = Op.getNode()->getOperand(1);
7235 SDValue Idx = Op.getNode()->getOperand(2);
7237 if (Op.getNode()->getValueType(0).is256BitVector() &&
7238 SubVec.getNode()->getValueType(0).is128BitVector() &&
7239 isa<ConstantSDNode>(Idx)) {
7240 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7241 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7247 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7248 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7249 // one of the above mentioned nodes. It has to be wrapped because otherwise
7250 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7251 // be used to form addressing mode. These wrapped nodes will be selected
7254 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7255 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7257 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7259 unsigned char OpFlag = 0;
7260 unsigned WrapperKind = X86ISD::Wrapper;
7261 CodeModel::Model M = getTargetMachine().getCodeModel();
7263 if (Subtarget->isPICStyleRIPRel() &&
7264 (M == CodeModel::Small || M == CodeModel::Kernel))
7265 WrapperKind = X86ISD::WrapperRIP;
7266 else if (Subtarget->isPICStyleGOT())
7267 OpFlag = X86II::MO_GOTOFF;
7268 else if (Subtarget->isPICStyleStubPIC())
7269 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7271 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7273 CP->getOffset(), OpFlag);
7274 DebugLoc DL = CP->getDebugLoc();
7275 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7276 // With PIC, the address is actually $g + Offset.
7278 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7279 DAG.getNode(X86ISD::GlobalBaseReg,
7280 DebugLoc(), getPointerTy()),
7287 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7288 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7290 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7292 unsigned char OpFlag = 0;
7293 unsigned WrapperKind = X86ISD::Wrapper;
7294 CodeModel::Model M = getTargetMachine().getCodeModel();
7296 if (Subtarget->isPICStyleRIPRel() &&
7297 (M == CodeModel::Small || M == CodeModel::Kernel))
7298 WrapperKind = X86ISD::WrapperRIP;
7299 else if (Subtarget->isPICStyleGOT())
7300 OpFlag = X86II::MO_GOTOFF;
7301 else if (Subtarget->isPICStyleStubPIC())
7302 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7304 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7306 DebugLoc DL = JT->getDebugLoc();
7307 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7309 // With PIC, the address is actually $g + Offset.
7311 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7312 DAG.getNode(X86ISD::GlobalBaseReg,
7313 DebugLoc(), getPointerTy()),
7320 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7321 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7323 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7325 unsigned char OpFlag = 0;
7326 unsigned WrapperKind = X86ISD::Wrapper;
7327 CodeModel::Model M = getTargetMachine().getCodeModel();
7329 if (Subtarget->isPICStyleRIPRel() &&
7330 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7331 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7332 OpFlag = X86II::MO_GOTPCREL;
7333 WrapperKind = X86ISD::WrapperRIP;
7334 } else if (Subtarget->isPICStyleGOT()) {
7335 OpFlag = X86II::MO_GOT;
7336 } else if (Subtarget->isPICStyleStubPIC()) {
7337 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7338 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7339 OpFlag = X86II::MO_DARWIN_NONLAZY;
7342 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7344 DebugLoc DL = Op.getDebugLoc();
7345 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7348 // With PIC, the address is actually $g + Offset.
7349 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7350 !Subtarget->is64Bit()) {
7351 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7352 DAG.getNode(X86ISD::GlobalBaseReg,
7353 DebugLoc(), getPointerTy()),
7357 // For symbols that require a load from a stub to get the address, emit the
7359 if (isGlobalStubReference(OpFlag))
7360 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7361 MachinePointerInfo::getGOT(), false, false, false, 0);
7367 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7368 // Create the TargetBlockAddressAddress node.
7369 unsigned char OpFlags =
7370 Subtarget->ClassifyBlockAddressReference();
7371 CodeModel::Model M = getTargetMachine().getCodeModel();
7372 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7373 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7374 DebugLoc dl = Op.getDebugLoc();
7375 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7378 if (Subtarget->isPICStyleRIPRel() &&
7379 (M == CodeModel::Small || M == CodeModel::Kernel))
7380 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7382 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7384 // With PIC, the address is actually $g + Offset.
7385 if (isGlobalRelativeToPICBase(OpFlags)) {
7386 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7387 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7395 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7397 SelectionDAG &DAG) const {
7398 // Create the TargetGlobalAddress node, folding in the constant
7399 // offset if it is legal.
7400 unsigned char OpFlags =
7401 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7402 CodeModel::Model M = getTargetMachine().getCodeModel();
7404 if (OpFlags == X86II::MO_NO_FLAG &&
7405 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7406 // A direct static reference to a global.
7407 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7410 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7413 if (Subtarget->isPICStyleRIPRel() &&
7414 (M == CodeModel::Small || M == CodeModel::Kernel))
7415 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7417 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7419 // With PIC, the address is actually $g + Offset.
7420 if (isGlobalRelativeToPICBase(OpFlags)) {
7421 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7422 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7426 // For globals that require a load from a stub to get the address, emit the
7428 if (isGlobalStubReference(OpFlags))
7429 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7430 MachinePointerInfo::getGOT(), false, false, false, 0);
7432 // If there was a non-zero offset that we didn't fold, create an explicit
7435 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7436 DAG.getConstant(Offset, getPointerTy()));
7442 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7443 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7444 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7445 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7449 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7450 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7451 unsigned char OperandFlags, bool LocalDynamic = false) {
7452 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7453 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7454 DebugLoc dl = GA->getDebugLoc();
7455 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7456 GA->getValueType(0),
7460 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7464 SDValue Ops[] = { Chain, TGA, *InFlag };
7465 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7467 SDValue Ops[] = { Chain, TGA };
7468 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7471 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7472 MFI->setAdjustsStack(true);
7474 SDValue Flag = Chain.getValue(1);
7475 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7478 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7480 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7483 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7484 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7485 DAG.getNode(X86ISD::GlobalBaseReg,
7486 DebugLoc(), PtrVT), InFlag);
7487 InFlag = Chain.getValue(1);
7489 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7492 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7494 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7496 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7497 X86::RAX, X86II::MO_TLSGD);
7500 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7504 DebugLoc dl = GA->getDebugLoc();
7506 // Get the start address of the TLS block for this module.
7507 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7508 .getInfo<X86MachineFunctionInfo>();
7509 MFI->incNumLocalDynamicTLSAccesses();
7513 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7514 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7517 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7518 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7519 InFlag = Chain.getValue(1);
7520 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7521 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7524 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7528 unsigned char OperandFlags = X86II::MO_DTPOFF;
7529 unsigned WrapperKind = X86ISD::Wrapper;
7530 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7531 GA->getValueType(0),
7532 GA->getOffset(), OperandFlags);
7533 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7535 // Add x@dtpoff with the base.
7536 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7539 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7540 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7541 const EVT PtrVT, TLSModel::Model model,
7542 bool is64Bit, bool isPIC) {
7543 DebugLoc dl = GA->getDebugLoc();
7545 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7546 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7547 is64Bit ? 257 : 256));
7549 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7550 DAG.getIntPtrConstant(0),
7551 MachinePointerInfo(Ptr),
7552 false, false, false, 0);
7554 unsigned char OperandFlags = 0;
7555 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7557 unsigned WrapperKind = X86ISD::Wrapper;
7558 if (model == TLSModel::LocalExec) {
7559 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7560 } else if (model == TLSModel::InitialExec) {
7562 OperandFlags = X86II::MO_GOTTPOFF;
7563 WrapperKind = X86ISD::WrapperRIP;
7565 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7568 llvm_unreachable("Unexpected model");
7571 // emit "addl x@ntpoff,%eax" (local exec)
7572 // or "addl x@indntpoff,%eax" (initial exec)
7573 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7574 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7575 GA->getValueType(0),
7576 GA->getOffset(), OperandFlags);
7577 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7579 if (model == TLSModel::InitialExec) {
7580 if (isPIC && !is64Bit) {
7581 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7582 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7586 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7587 MachinePointerInfo::getGOT(), false, false, false,
7591 // The address of the thread local variable is the add of the thread
7592 // pointer with the offset of the variable.
7593 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7597 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7599 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7600 const GlobalValue *GV = GA->getGlobal();
7602 if (Subtarget->isTargetELF()) {
7603 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7606 case TLSModel::GeneralDynamic:
7607 if (Subtarget->is64Bit())
7608 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7609 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7610 case TLSModel::LocalDynamic:
7611 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7612 Subtarget->is64Bit());
7613 case TLSModel::InitialExec:
7614 case TLSModel::LocalExec:
7615 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7616 Subtarget->is64Bit(),
7617 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7619 llvm_unreachable("Unknown TLS model.");
7622 if (Subtarget->isTargetDarwin()) {
7623 // Darwin only has one model of TLS. Lower to that.
7624 unsigned char OpFlag = 0;
7625 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7626 X86ISD::WrapperRIP : X86ISD::Wrapper;
7628 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7630 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7631 !Subtarget->is64Bit();
7633 OpFlag = X86II::MO_TLVP_PIC_BASE;
7635 OpFlag = X86II::MO_TLVP;
7636 DebugLoc DL = Op.getDebugLoc();
7637 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7638 GA->getValueType(0),
7639 GA->getOffset(), OpFlag);
7640 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7642 // With PIC32, the address is actually $g + Offset.
7644 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7645 DAG.getNode(X86ISD::GlobalBaseReg,
7646 DebugLoc(), getPointerTy()),
7649 // Lowering the machine isd will make sure everything is in the right
7651 SDValue Chain = DAG.getEntryNode();
7652 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7653 SDValue Args[] = { Chain, Offset };
7654 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7656 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7657 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7658 MFI->setAdjustsStack(true);
7660 // And our return value (tls address) is in the standard call return value
7662 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7663 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7667 if (Subtarget->isTargetWindows()) {
7668 // Just use the implicit TLS architecture
7669 // Need to generate someting similar to:
7670 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7672 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7673 // mov rcx, qword [rdx+rcx*8]
7674 // mov eax, .tls$:tlsvar
7675 // [rax+rcx] contains the address
7676 // Windows 64bit: gs:0x58
7677 // Windows 32bit: fs:__tls_array
7679 // If GV is an alias then use the aliasee for determining
7680 // thread-localness.
7681 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7682 GV = GA->resolveAliasedGlobal(false);
7683 DebugLoc dl = GA->getDebugLoc();
7684 SDValue Chain = DAG.getEntryNode();
7686 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7687 // %gs:0x58 (64-bit).
7688 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7689 ? Type::getInt8PtrTy(*DAG.getContext(),
7691 : Type::getInt32PtrTy(*DAG.getContext(),
7694 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7695 Subtarget->is64Bit()
7696 ? DAG.getIntPtrConstant(0x58)
7697 : DAG.getExternalSymbol("_tls_array",
7699 MachinePointerInfo(Ptr),
7700 false, false, false, 0);
7702 // Load the _tls_index variable
7703 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7704 if (Subtarget->is64Bit())
7705 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7706 IDX, MachinePointerInfo(), MVT::i32,
7709 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7710 false, false, false, 0);
7712 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7714 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7716 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7717 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7718 false, false, false, 0);
7720 // Get the offset of start of .tls section
7721 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7722 GA->getValueType(0),
7723 GA->getOffset(), X86II::MO_SECREL);
7724 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7726 // The address of the thread local variable is the add of the thread
7727 // pointer with the offset of the variable.
7728 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7731 llvm_unreachable("TLS not implemented for this target.");
7735 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7736 /// and take a 2 x i32 value to shift plus a shift amount.
7737 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7738 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7739 EVT VT = Op.getValueType();
7740 unsigned VTBits = VT.getSizeInBits();
7741 DebugLoc dl = Op.getDebugLoc();
7742 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7743 SDValue ShOpLo = Op.getOperand(0);
7744 SDValue ShOpHi = Op.getOperand(1);
7745 SDValue ShAmt = Op.getOperand(2);
7746 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7747 DAG.getConstant(VTBits - 1, MVT::i8))
7748 : DAG.getConstant(0, VT);
7751 if (Op.getOpcode() == ISD::SHL_PARTS) {
7752 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7753 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7755 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7756 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7759 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7760 DAG.getConstant(VTBits, MVT::i8));
7761 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7762 AndNode, DAG.getConstant(0, MVT::i8));
7765 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7766 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7767 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7769 if (Op.getOpcode() == ISD::SHL_PARTS) {
7770 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7771 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7773 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7774 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7777 SDValue Ops[2] = { Lo, Hi };
7778 return DAG.getMergeValues(Ops, 2, dl);
7781 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7782 SelectionDAG &DAG) const {
7783 EVT SrcVT = Op.getOperand(0).getValueType();
7785 if (SrcVT.isVector())
7788 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7789 "Unknown SINT_TO_FP to lower!");
7791 // These are really Legal; return the operand so the caller accepts it as
7793 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7795 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7796 Subtarget->is64Bit()) {
7800 DebugLoc dl = Op.getDebugLoc();
7801 unsigned Size = SrcVT.getSizeInBits()/8;
7802 MachineFunction &MF = DAG.getMachineFunction();
7803 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7804 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7805 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7807 MachinePointerInfo::getFixedStack(SSFI),
7809 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7812 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7814 SelectionDAG &DAG) const {
7816 DebugLoc DL = Op.getDebugLoc();
7818 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7820 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7822 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7824 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7826 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7827 MachineMemOperand *MMO;
7829 int SSFI = FI->getIndex();
7831 DAG.getMachineFunction()
7832 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7833 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7835 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7836 StackSlot = StackSlot.getOperand(1);
7838 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7839 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7841 Tys, Ops, array_lengthof(Ops),
7845 Chain = Result.getValue(1);
7846 SDValue InFlag = Result.getValue(2);
7848 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7849 // shouldn't be necessary except that RFP cannot be live across
7850 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7851 MachineFunction &MF = DAG.getMachineFunction();
7852 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7853 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7854 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7855 Tys = DAG.getVTList(MVT::Other);
7857 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7859 MachineMemOperand *MMO =
7860 DAG.getMachineFunction()
7861 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7862 MachineMemOperand::MOStore, SSFISize, SSFISize);
7864 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7865 Ops, array_lengthof(Ops),
7866 Op.getValueType(), MMO);
7867 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7868 MachinePointerInfo::getFixedStack(SSFI),
7869 false, false, false, 0);
7875 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7876 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7877 SelectionDAG &DAG) const {
7878 // This algorithm is not obvious. Here it is what we're trying to output:
7881 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7882 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7886 pshufd $0x4e, %xmm0, %xmm1
7891 DebugLoc dl = Op.getDebugLoc();
7892 LLVMContext *Context = DAG.getContext();
7894 // Build some magic constants.
7895 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7896 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7897 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7899 SmallVector<Constant*,2> CV1;
7901 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7903 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7904 Constant *C1 = ConstantVector::get(CV1);
7905 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7907 // Load the 64-bit value into an XMM register.
7908 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7910 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7911 MachinePointerInfo::getConstantPool(),
7912 false, false, false, 16);
7913 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7914 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7917 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7918 MachinePointerInfo::getConstantPool(),
7919 false, false, false, 16);
7920 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7921 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7924 if (Subtarget->hasSSE3()) {
7925 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7926 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7928 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7929 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7931 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7932 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7937 DAG.getIntPtrConstant(0));
7940 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7941 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7942 SelectionDAG &DAG) const {
7943 DebugLoc dl = Op.getDebugLoc();
7944 // FP constant to bias correct the final result.
7945 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7948 // Load the 32-bit value into an XMM register.
7949 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7952 // Zero out the upper parts of the register.
7953 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7955 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7956 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7957 DAG.getIntPtrConstant(0));
7959 // Or the load with the bias.
7960 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7961 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7962 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7964 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7965 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7966 MVT::v2f64, Bias)));
7967 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7968 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7969 DAG.getIntPtrConstant(0));
7971 // Subtract the bias.
7972 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7974 // Handle final rounding.
7975 EVT DestVT = Op.getValueType();
7977 if (DestVT.bitsLT(MVT::f64))
7978 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7979 DAG.getIntPtrConstant(0));
7980 if (DestVT.bitsGT(MVT::f64))
7981 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7983 // Handle final rounding.
7987 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7988 SelectionDAG &DAG) const {
7989 SDValue N0 = Op.getOperand(0);
7990 DebugLoc dl = Op.getDebugLoc();
7992 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7993 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7994 // the optimization here.
7995 if (DAG.SignBitIsZero(N0))
7996 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7998 EVT SrcVT = N0.getValueType();
7999 EVT DstVT = Op.getValueType();
8000 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8001 return LowerUINT_TO_FP_i64(Op, DAG);
8002 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8003 return LowerUINT_TO_FP_i32(Op, DAG);
8004 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8007 // Make a 64-bit buffer, and use it to build an FILD.
8008 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8009 if (SrcVT == MVT::i32) {
8010 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8011 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8012 getPointerTy(), StackSlot, WordOff);
8013 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8014 StackSlot, MachinePointerInfo(),
8016 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8017 OffsetSlot, MachinePointerInfo(),
8019 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8023 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8024 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8025 StackSlot, MachinePointerInfo(),
8027 // For i64 source, we need to add the appropriate power of 2 if the input
8028 // was negative. This is the same as the optimization in
8029 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8030 // we must be careful to do the computation in x87 extended precision, not
8031 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8032 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8033 MachineMemOperand *MMO =
8034 DAG.getMachineFunction()
8035 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8036 MachineMemOperand::MOLoad, 8, 8);
8038 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8039 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8040 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8043 APInt FF(32, 0x5F800000ULL);
8045 // Check whether the sign bit is set.
8046 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8047 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8050 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8051 SDValue FudgePtr = DAG.getConstantPool(
8052 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8055 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8056 SDValue Zero = DAG.getIntPtrConstant(0);
8057 SDValue Four = DAG.getIntPtrConstant(4);
8058 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8060 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8062 // Load the value out, extending it from f32 to f80.
8063 // FIXME: Avoid the extend by constructing the right constant pool?
8064 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8065 FudgePtr, MachinePointerInfo::getConstantPool(),
8066 MVT::f32, false, false, 4);
8067 // Extend everything to 80 bits to force it to be done on x87.
8068 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8069 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8072 std::pair<SDValue,SDValue> X86TargetLowering::
8073 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8074 DebugLoc DL = Op.getDebugLoc();
8076 EVT DstTy = Op.getValueType();
8078 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8079 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8083 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8084 DstTy.getSimpleVT() >= MVT::i16 &&
8085 "Unknown FP_TO_INT to lower!");
8087 // These are really Legal.
8088 if (DstTy == MVT::i32 &&
8089 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8090 return std::make_pair(SDValue(), SDValue());
8091 if (Subtarget->is64Bit() &&
8092 DstTy == MVT::i64 &&
8093 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8094 return std::make_pair(SDValue(), SDValue());
8096 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8097 // stack slot, or into the FTOL runtime function.
8098 MachineFunction &MF = DAG.getMachineFunction();
8099 unsigned MemSize = DstTy.getSizeInBits()/8;
8100 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8101 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8104 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8105 Opc = X86ISD::WIN_FTOL;
8107 switch (DstTy.getSimpleVT().SimpleTy) {
8108 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8109 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8110 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8111 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8114 SDValue Chain = DAG.getEntryNode();
8115 SDValue Value = Op.getOperand(0);
8116 EVT TheVT = Op.getOperand(0).getValueType();
8117 // FIXME This causes a redundant load/store if the SSE-class value is already
8118 // in memory, such as if it is on the callstack.
8119 if (isScalarFPTypeInSSEReg(TheVT)) {
8120 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8121 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8122 MachinePointerInfo::getFixedStack(SSFI),
8124 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8126 Chain, StackSlot, DAG.getValueType(TheVT)
8129 MachineMemOperand *MMO =
8130 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8131 MachineMemOperand::MOLoad, MemSize, MemSize);
8132 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8134 Chain = Value.getValue(1);
8135 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8136 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8139 MachineMemOperand *MMO =
8140 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8141 MachineMemOperand::MOStore, MemSize, MemSize);
8143 if (Opc != X86ISD::WIN_FTOL) {
8144 // Build the FP_TO_INT*_IN_MEM
8145 SDValue Ops[] = { Chain, Value, StackSlot };
8146 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8147 Ops, 3, DstTy, MMO);
8148 return std::make_pair(FIST, StackSlot);
8150 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8151 DAG.getVTList(MVT::Other, MVT::Glue),
8153 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8154 MVT::i32, ftol.getValue(1));
8155 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8156 MVT::i32, eax.getValue(2));
8157 SDValue Ops[] = { eax, edx };
8158 SDValue pair = IsReplace
8159 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8160 : DAG.getMergeValues(Ops, 2, DL);
8161 return std::make_pair(pair, SDValue());
8165 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8166 SelectionDAG &DAG) const {
8167 if (Op.getValueType().isVector())
8170 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8171 /*IsSigned=*/ true, /*IsReplace=*/ false);
8172 SDValue FIST = Vals.first, StackSlot = Vals.second;
8173 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8174 if (FIST.getNode() == 0) return Op;
8176 if (StackSlot.getNode())
8178 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8179 FIST, StackSlot, MachinePointerInfo(),
8180 false, false, false, 0);
8182 // The node is the result.
8186 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8187 SelectionDAG &DAG) const {
8188 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8189 /*IsSigned=*/ false, /*IsReplace=*/ false);
8190 SDValue FIST = Vals.first, StackSlot = Vals.second;
8191 assert(FIST.getNode() && "Unexpected failure");
8193 if (StackSlot.getNode())
8195 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8196 FIST, StackSlot, MachinePointerInfo(),
8197 false, false, false, 0);
8199 // The node is the result.
8203 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8204 LLVMContext *Context = DAG.getContext();
8205 DebugLoc dl = Op.getDebugLoc();
8206 EVT VT = Op.getValueType();
8208 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8209 if (VT.isVector()) {
8210 EltVT = VT.getVectorElementType();
8211 NumElts = VT.getVectorNumElements();
8214 if (EltVT == MVT::f64)
8215 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8217 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8218 C = ConstantVector::getSplat(NumElts, C);
8219 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8220 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8221 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8222 MachinePointerInfo::getConstantPool(),
8223 false, false, false, Alignment);
8224 if (VT.isVector()) {
8225 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8226 return DAG.getNode(ISD::BITCAST, dl, VT,
8227 DAG.getNode(ISD::AND, dl, ANDVT,
8228 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8230 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8232 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8235 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8236 LLVMContext *Context = DAG.getContext();
8237 DebugLoc dl = Op.getDebugLoc();
8238 EVT VT = Op.getValueType();
8240 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8241 if (VT.isVector()) {
8242 EltVT = VT.getVectorElementType();
8243 NumElts = VT.getVectorNumElements();
8246 if (EltVT == MVT::f64)
8247 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8249 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8250 C = ConstantVector::getSplat(NumElts, C);
8251 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8252 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8253 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8254 MachinePointerInfo::getConstantPool(),
8255 false, false, false, Alignment);
8256 if (VT.isVector()) {
8257 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8258 return DAG.getNode(ISD::BITCAST, dl, VT,
8259 DAG.getNode(ISD::XOR, dl, XORVT,
8260 DAG.getNode(ISD::BITCAST, dl, XORVT,
8262 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8265 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8268 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8269 LLVMContext *Context = DAG.getContext();
8270 SDValue Op0 = Op.getOperand(0);
8271 SDValue Op1 = Op.getOperand(1);
8272 DebugLoc dl = Op.getDebugLoc();
8273 EVT VT = Op.getValueType();
8274 EVT SrcVT = Op1.getValueType();
8276 // If second operand is smaller, extend it first.
8277 if (SrcVT.bitsLT(VT)) {
8278 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8281 // And if it is bigger, shrink it first.
8282 if (SrcVT.bitsGT(VT)) {
8283 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8287 // At this point the operands and the result should have the same
8288 // type, and that won't be f80 since that is not custom lowered.
8290 // First get the sign bit of second operand.
8291 SmallVector<Constant*,4> CV;
8292 if (SrcVT == MVT::f64) {
8293 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8294 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8296 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8297 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8298 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8299 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8301 Constant *C = ConstantVector::get(CV);
8302 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8303 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8304 MachinePointerInfo::getConstantPool(),
8305 false, false, false, 16);
8306 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8308 // Shift sign bit right or left if the two operands have different types.
8309 if (SrcVT.bitsGT(VT)) {
8310 // Op0 is MVT::f32, Op1 is MVT::f64.
8311 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8312 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8313 DAG.getConstant(32, MVT::i32));
8314 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8315 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8316 DAG.getIntPtrConstant(0));
8319 // Clear first operand sign bit.
8321 if (VT == MVT::f64) {
8322 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8323 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8325 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8326 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8327 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8328 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8330 C = ConstantVector::get(CV);
8331 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8332 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8333 MachinePointerInfo::getConstantPool(),
8334 false, false, false, 16);
8335 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8337 // Or the value with the sign bit.
8338 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8341 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8342 SDValue N0 = Op.getOperand(0);
8343 DebugLoc dl = Op.getDebugLoc();
8344 EVT VT = Op.getValueType();
8346 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8347 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8348 DAG.getConstant(1, VT));
8349 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8352 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8354 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8355 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8357 if (!Subtarget->hasSSE41())
8360 if (!Op->hasOneUse())
8363 SDNode *N = Op.getNode();
8364 DebugLoc DL = N->getDebugLoc();
8366 SmallVector<SDValue, 8> Opnds;
8367 DenseMap<SDValue, unsigned> VecInMap;
8368 EVT VT = MVT::Other;
8370 // Recognize a special case where a vector is casted into wide integer to
8372 Opnds.push_back(N->getOperand(0));
8373 Opnds.push_back(N->getOperand(1));
8375 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8376 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8377 // BFS traverse all OR'd operands.
8378 if (I->getOpcode() == ISD::OR) {
8379 Opnds.push_back(I->getOperand(0));
8380 Opnds.push_back(I->getOperand(1));
8381 // Re-evaluate the number of nodes to be traversed.
8382 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8386 // Quit if a non-EXTRACT_VECTOR_ELT
8387 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8390 // Quit if without a constant index.
8391 SDValue Idx = I->getOperand(1);
8392 if (!isa<ConstantSDNode>(Idx))
8395 SDValue ExtractedFromVec = I->getOperand(0);
8396 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8397 if (M == VecInMap.end()) {
8398 VT = ExtractedFromVec.getValueType();
8399 // Quit if not 128/256-bit vector.
8400 if (!VT.is128BitVector() && !VT.is256BitVector())
8402 // Quit if not the same type.
8403 if (VecInMap.begin() != VecInMap.end() &&
8404 VT != VecInMap.begin()->first.getValueType())
8406 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8408 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8411 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8412 "Not extracted from 128-/256-bit vector.");
8414 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8415 SmallVector<SDValue, 8> VecIns;
8417 for (DenseMap<SDValue, unsigned>::const_iterator
8418 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8419 // Quit if not all elements are used.
8420 if (I->second != FullMask)
8422 VecIns.push_back(I->first);
8425 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8427 // Cast all vectors into TestVT for PTEST.
8428 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8429 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8431 // If more than one full vectors are evaluated, OR them first before PTEST.
8432 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8433 // Each iteration will OR 2 nodes and append the result until there is only
8434 // 1 node left, i.e. the final OR'd value of all vectors.
8435 SDValue LHS = VecIns[Slot];
8436 SDValue RHS = VecIns[Slot + 1];
8437 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8440 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8441 VecIns.back(), VecIns.back());
8444 /// Emit nodes that will be selected as "test Op0,Op0", or something
8446 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8447 SelectionDAG &DAG) const {
8448 DebugLoc dl = Op.getDebugLoc();
8450 // CF and OF aren't always set the way we want. Determine which
8451 // of these we need.
8452 bool NeedCF = false;
8453 bool NeedOF = false;
8456 case X86::COND_A: case X86::COND_AE:
8457 case X86::COND_B: case X86::COND_BE:
8460 case X86::COND_G: case X86::COND_GE:
8461 case X86::COND_L: case X86::COND_LE:
8462 case X86::COND_O: case X86::COND_NO:
8467 // See if we can use the EFLAGS value from the operand instead of
8468 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8469 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8470 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8471 // Emit a CMP with 0, which is the TEST pattern.
8472 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8473 DAG.getConstant(0, Op.getValueType()));
8475 unsigned Opcode = 0;
8476 unsigned NumOperands = 0;
8478 // Truncate operations may prevent the merge of the SETCC instruction
8479 // and the arithmetic intruction before it. Attempt to truncate the operands
8480 // of the arithmetic instruction and use a reduced bit-width instruction.
8481 bool NeedTruncation = false;
8482 SDValue ArithOp = Op;
8483 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8484 SDValue Arith = Op->getOperand(0);
8485 // Both the trunc and the arithmetic op need to have one user each.
8486 if (Arith->hasOneUse())
8487 switch (Arith.getOpcode()) {
8494 NeedTruncation = true;
8500 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8501 // which may be the result of a CAST. We use the variable 'Op', which is the
8502 // non-casted variable when we check for possible users.
8503 switch (ArithOp.getOpcode()) {
8505 // Due to an isel shortcoming, be conservative if this add is likely to be
8506 // selected as part of a load-modify-store instruction. When the root node
8507 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8508 // uses of other nodes in the match, such as the ADD in this case. This
8509 // leads to the ADD being left around and reselected, with the result being
8510 // two adds in the output. Alas, even if none our users are stores, that
8511 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8512 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8513 // climbing the DAG back to the root, and it doesn't seem to be worth the
8515 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8516 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8517 if (UI->getOpcode() != ISD::CopyToReg &&
8518 UI->getOpcode() != ISD::SETCC &&
8519 UI->getOpcode() != ISD::STORE)
8522 if (ConstantSDNode *C =
8523 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8524 // An add of one will be selected as an INC.
8525 if (C->getAPIntValue() == 1) {
8526 Opcode = X86ISD::INC;
8531 // An add of negative one (subtract of one) will be selected as a DEC.
8532 if (C->getAPIntValue().isAllOnesValue()) {
8533 Opcode = X86ISD::DEC;
8539 // Otherwise use a regular EFLAGS-setting add.
8540 Opcode = X86ISD::ADD;
8544 // If the primary and result isn't used, don't bother using X86ISD::AND,
8545 // because a TEST instruction will be better.
8546 bool NonFlagUse = false;
8547 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8548 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8550 unsigned UOpNo = UI.getOperandNo();
8551 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8552 // Look pass truncate.
8553 UOpNo = User->use_begin().getOperandNo();
8554 User = *User->use_begin();
8557 if (User->getOpcode() != ISD::BRCOND &&
8558 User->getOpcode() != ISD::SETCC &&
8559 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8572 // Due to the ISEL shortcoming noted above, be conservative if this op is
8573 // likely to be selected as part of a load-modify-store instruction.
8574 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8575 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8576 if (UI->getOpcode() == ISD::STORE)
8579 // Otherwise use a regular EFLAGS-setting instruction.
8580 switch (ArithOp.getOpcode()) {
8581 default: llvm_unreachable("unexpected operator!");
8582 case ISD::SUB: Opcode = X86ISD::SUB; break;
8583 case ISD::XOR: Opcode = X86ISD::XOR; break;
8584 case ISD::AND: Opcode = X86ISD::AND; break;
8586 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8587 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8588 if (EFLAGS.getNode())
8591 Opcode = X86ISD::OR;
8605 return SDValue(Op.getNode(), 1);
8611 // If we found that truncation is beneficial, perform the truncation and
8613 if (NeedTruncation) {
8614 EVT VT = Op.getValueType();
8615 SDValue WideVal = Op->getOperand(0);
8616 EVT WideVT = WideVal.getValueType();
8617 unsigned ConvertedOp = 0;
8618 // Use a target machine opcode to prevent further DAGCombine
8619 // optimizations that may separate the arithmetic operations
8620 // from the setcc node.
8621 switch (WideVal.getOpcode()) {
8623 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8624 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8625 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8626 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8627 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8631 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8632 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8633 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8634 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8635 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8641 // Emit a CMP with 0, which is the TEST pattern.
8642 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8643 DAG.getConstant(0, Op.getValueType()));
8645 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8646 SmallVector<SDValue, 4> Ops;
8647 for (unsigned i = 0; i != NumOperands; ++i)
8648 Ops.push_back(Op.getOperand(i));
8650 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8651 DAG.ReplaceAllUsesWith(Op, New);
8652 return SDValue(New.getNode(), 1);
8655 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8657 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8658 SelectionDAG &DAG) const {
8659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8660 if (C->getAPIntValue() == 0)
8661 return EmitTest(Op0, X86CC, DAG);
8663 DebugLoc dl = Op0.getDebugLoc();
8664 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8665 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8666 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8667 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8668 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8670 return SDValue(Sub.getNode(), 1);
8672 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8675 /// Convert a comparison if required by the subtarget.
8676 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8677 SelectionDAG &DAG) const {
8678 // If the subtarget does not support the FUCOMI instruction, floating-point
8679 // comparisons have to be converted.
8680 if (Subtarget->hasCMov() ||
8681 Cmp.getOpcode() != X86ISD::CMP ||
8682 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8683 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8686 // The instruction selector will select an FUCOM instruction instead of
8687 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8688 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8689 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8690 DebugLoc dl = Cmp.getDebugLoc();
8691 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8692 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8693 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8694 DAG.getConstant(8, MVT::i8));
8695 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8696 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8699 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8700 /// if it's possible.
8701 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8702 DebugLoc dl, SelectionDAG &DAG) const {
8703 SDValue Op0 = And.getOperand(0);
8704 SDValue Op1 = And.getOperand(1);
8705 if (Op0.getOpcode() == ISD::TRUNCATE)
8706 Op0 = Op0.getOperand(0);
8707 if (Op1.getOpcode() == ISD::TRUNCATE)
8708 Op1 = Op1.getOperand(0);
8711 if (Op1.getOpcode() == ISD::SHL)
8712 std::swap(Op0, Op1);
8713 if (Op0.getOpcode() == ISD::SHL) {
8714 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8715 if (And00C->getZExtValue() == 1) {
8716 // If we looked past a truncate, check that it's only truncating away
8718 unsigned BitWidth = Op0.getValueSizeInBits();
8719 unsigned AndBitWidth = And.getValueSizeInBits();
8720 if (BitWidth > AndBitWidth) {
8722 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8723 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8727 RHS = Op0.getOperand(1);
8729 } else if (Op1.getOpcode() == ISD::Constant) {
8730 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8731 uint64_t AndRHSVal = AndRHS->getZExtValue();
8732 SDValue AndLHS = Op0;
8734 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8735 LHS = AndLHS.getOperand(0);
8736 RHS = AndLHS.getOperand(1);
8739 // Use BT if the immediate can't be encoded in a TEST instruction.
8740 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8742 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8746 if (LHS.getNode()) {
8747 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8748 // instruction. Since the shift amount is in-range-or-undefined, we know
8749 // that doing a bittest on the i32 value is ok. We extend to i32 because
8750 // the encoding for the i16 version is larger than the i32 version.
8751 // Also promote i16 to i32 for performance / code size reason.
8752 if (LHS.getValueType() == MVT::i8 ||
8753 LHS.getValueType() == MVT::i16)
8754 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8756 // If the operand types disagree, extend the shift amount to match. Since
8757 // BT ignores high bits (like shifts) we can use anyextend.
8758 if (LHS.getValueType() != RHS.getValueType())
8759 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8761 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8762 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8763 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8764 DAG.getConstant(Cond, MVT::i8), BT);
8770 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8772 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8774 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8775 SDValue Op0 = Op.getOperand(0);
8776 SDValue Op1 = Op.getOperand(1);
8777 DebugLoc dl = Op.getDebugLoc();
8778 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8780 // Optimize to BT if possible.
8781 // Lower (X & (1 << N)) == 0 to BT(X, N).
8782 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8783 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8784 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8785 Op1.getOpcode() == ISD::Constant &&
8786 cast<ConstantSDNode>(Op1)->isNullValue() &&
8787 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8788 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8789 if (NewSetCC.getNode())
8793 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8795 if (Op1.getOpcode() == ISD::Constant &&
8796 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8797 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8798 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8800 // If the input is a setcc, then reuse the input setcc or use a new one with
8801 // the inverted condition.
8802 if (Op0.getOpcode() == X86ISD::SETCC) {
8803 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8804 bool Invert = (CC == ISD::SETNE) ^
8805 cast<ConstantSDNode>(Op1)->isNullValue();
8806 if (!Invert) return Op0;
8808 CCode = X86::GetOppositeBranchCondition(CCode);
8809 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8810 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8814 bool isFP = Op1.getValueType().isFloatingPoint();
8815 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8816 if (X86CC == X86::COND_INVALID)
8819 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8820 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8821 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8822 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8825 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8826 // ones, and then concatenate the result back.
8827 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8828 EVT VT = Op.getValueType();
8830 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8831 "Unsupported value type for operation");
8833 unsigned NumElems = VT.getVectorNumElements();
8834 DebugLoc dl = Op.getDebugLoc();
8835 SDValue CC = Op.getOperand(2);
8837 // Extract the LHS vectors
8838 SDValue LHS = Op.getOperand(0);
8839 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8840 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8842 // Extract the RHS vectors
8843 SDValue RHS = Op.getOperand(1);
8844 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8845 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8847 // Issue the operation on the smaller types and concatenate the result back
8848 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8849 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8850 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8851 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8852 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8856 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8858 SDValue Op0 = Op.getOperand(0);
8859 SDValue Op1 = Op.getOperand(1);
8860 SDValue CC = Op.getOperand(2);
8861 EVT VT = Op.getValueType();
8862 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8863 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8864 DebugLoc dl = Op.getDebugLoc();
8868 EVT EltVT = Op0.getValueType().getVectorElementType();
8869 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8875 // SSE Condition code mapping:
8884 switch (SetCCOpcode) {
8885 default: llvm_unreachable("Unexpected SETCC condition");
8887 case ISD::SETEQ: SSECC = 0; break;
8889 case ISD::SETGT: Swap = true; // Fallthrough
8891 case ISD::SETOLT: SSECC = 1; break;
8893 case ISD::SETGE: Swap = true; // Fallthrough
8895 case ISD::SETOLE: SSECC = 2; break;
8896 case ISD::SETUO: SSECC = 3; break;
8898 case ISD::SETNE: SSECC = 4; break;
8899 case ISD::SETULE: Swap = true; // Fallthrough
8900 case ISD::SETUGE: SSECC = 5; break;
8901 case ISD::SETULT: Swap = true; // Fallthrough
8902 case ISD::SETUGT: SSECC = 6; break;
8903 case ISD::SETO: SSECC = 7; break;
8905 case ISD::SETONE: SSECC = 8; break;
8908 std::swap(Op0, Op1);
8910 // In the two special cases we can't handle, emit two comparisons.
8913 unsigned CombineOpc;
8914 if (SetCCOpcode == ISD::SETUEQ) {
8915 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8917 assert(SetCCOpcode == ISD::SETONE);
8918 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8921 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8922 DAG.getConstant(CC0, MVT::i8));
8923 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8924 DAG.getConstant(CC1, MVT::i8));
8925 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8927 // Handle all other FP comparisons here.
8928 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8929 DAG.getConstant(SSECC, MVT::i8));
8932 // Break 256-bit integer vector compare into smaller ones.
8933 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8934 return Lower256IntVSETCC(Op, DAG);
8936 // We are handling one of the integer comparisons here. Since SSE only has
8937 // GT and EQ comparisons for integer, swapping operands and multiple
8938 // operations may be required for some comparisons.
8940 bool Swap = false, Invert = false, FlipSigns = false;
8942 switch (SetCCOpcode) {
8943 default: llvm_unreachable("Unexpected SETCC condition");
8944 case ISD::SETNE: Invert = true;
8945 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8946 case ISD::SETLT: Swap = true;
8947 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8948 case ISD::SETGE: Swap = true;
8949 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8950 case ISD::SETULT: Swap = true;
8951 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8952 case ISD::SETUGE: Swap = true;
8953 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8956 std::swap(Op0, Op1);
8958 // Check that the operation in question is available (most are plain SSE2,
8959 // but PCMPGTQ and PCMPEQQ have different requirements).
8960 if (VT == MVT::v2i64) {
8961 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8963 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8967 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8968 // bits of the inputs before performing those operations.
8970 EVT EltVT = VT.getVectorElementType();
8971 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8973 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8974 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8976 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8977 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8980 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8982 // If the logical-not of the result is required, perform that now.
8984 Result = DAG.getNOT(dl, Result, VT);
8989 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8990 static bool isX86LogicalCmp(SDValue Op) {
8991 unsigned Opc = Op.getNode()->getOpcode();
8992 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8993 Opc == X86ISD::SAHF)
8995 if (Op.getResNo() == 1 &&
8996 (Opc == X86ISD::ADD ||
8997 Opc == X86ISD::SUB ||
8998 Opc == X86ISD::ADC ||
8999 Opc == X86ISD::SBB ||
9000 Opc == X86ISD::SMUL ||
9001 Opc == X86ISD::UMUL ||
9002 Opc == X86ISD::INC ||
9003 Opc == X86ISD::DEC ||
9004 Opc == X86ISD::OR ||
9005 Opc == X86ISD::XOR ||
9006 Opc == X86ISD::AND))
9009 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9015 static bool isZero(SDValue V) {
9016 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9017 return C && C->isNullValue();
9020 static bool isAllOnes(SDValue V) {
9021 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9022 return C && C->isAllOnesValue();
9025 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9026 if (V.getOpcode() != ISD::TRUNCATE)
9029 SDValue VOp0 = V.getOperand(0);
9030 unsigned InBits = VOp0.getValueSizeInBits();
9031 unsigned Bits = V.getValueSizeInBits();
9032 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9035 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9036 bool addTest = true;
9037 SDValue Cond = Op.getOperand(0);
9038 SDValue Op1 = Op.getOperand(1);
9039 SDValue Op2 = Op.getOperand(2);
9040 DebugLoc DL = Op.getDebugLoc();
9043 if (Cond.getOpcode() == ISD::SETCC) {
9044 SDValue NewCond = LowerSETCC(Cond, DAG);
9045 if (NewCond.getNode())
9049 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9050 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9051 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9052 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9053 if (Cond.getOpcode() == X86ISD::SETCC &&
9054 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9055 isZero(Cond.getOperand(1).getOperand(1))) {
9056 SDValue Cmp = Cond.getOperand(1);
9058 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9060 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9061 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9062 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9064 SDValue CmpOp0 = Cmp.getOperand(0);
9065 // Apply further optimizations for special cases
9066 // (select (x != 0), -1, 0) -> neg & sbb
9067 // (select (x == 0), 0, -1) -> neg & sbb
9068 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9069 if (YC->isNullValue() &&
9070 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9071 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9072 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9073 DAG.getConstant(0, CmpOp0.getValueType()),
9075 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9076 DAG.getConstant(X86::COND_B, MVT::i8),
9077 SDValue(Neg.getNode(), 1));
9081 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9082 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9083 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9085 SDValue Res = // Res = 0 or -1.
9086 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9087 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9089 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9090 Res = DAG.getNOT(DL, Res, Res.getValueType());
9092 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9093 if (N2C == 0 || !N2C->isNullValue())
9094 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9099 // Look past (and (setcc_carry (cmp ...)), 1).
9100 if (Cond.getOpcode() == ISD::AND &&
9101 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9102 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9103 if (C && C->getAPIntValue() == 1)
9104 Cond = Cond.getOperand(0);
9107 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9108 // setting operand in place of the X86ISD::SETCC.
9109 unsigned CondOpcode = Cond.getOpcode();
9110 if (CondOpcode == X86ISD::SETCC ||
9111 CondOpcode == X86ISD::SETCC_CARRY) {
9112 CC = Cond.getOperand(0);
9114 SDValue Cmp = Cond.getOperand(1);
9115 unsigned Opc = Cmp.getOpcode();
9116 EVT VT = Op.getValueType();
9118 bool IllegalFPCMov = false;
9119 if (VT.isFloatingPoint() && !VT.isVector() &&
9120 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9121 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9123 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9124 Opc == X86ISD::BT) { // FIXME
9128 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9129 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9130 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9131 Cond.getOperand(0).getValueType() != MVT::i8)) {
9132 SDValue LHS = Cond.getOperand(0);
9133 SDValue RHS = Cond.getOperand(1);
9137 switch (CondOpcode) {
9138 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9139 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9140 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9141 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9142 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9143 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9144 default: llvm_unreachable("unexpected overflowing operator");
9146 if (CondOpcode == ISD::UMULO)
9147 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9150 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9152 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9154 if (CondOpcode == ISD::UMULO)
9155 Cond = X86Op.getValue(2);
9157 Cond = X86Op.getValue(1);
9159 CC = DAG.getConstant(X86Cond, MVT::i8);
9164 // Look pass the truncate if the high bits are known zero.
9165 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9166 Cond = Cond.getOperand(0);
9168 // We know the result of AND is compared against zero. Try to match
9170 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9171 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9172 if (NewSetCC.getNode()) {
9173 CC = NewSetCC.getOperand(0);
9174 Cond = NewSetCC.getOperand(1);
9181 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9182 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9185 // a < b ? -1 : 0 -> RES = ~setcc_carry
9186 // a < b ? 0 : -1 -> RES = setcc_carry
9187 // a >= b ? -1 : 0 -> RES = setcc_carry
9188 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9189 if (Cond.getOpcode() == X86ISD::SUB) {
9190 Cond = ConvertCmpIfNecessary(Cond, DAG);
9191 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9193 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9194 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9195 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9196 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9197 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9198 return DAG.getNOT(DL, Res, Res.getValueType());
9203 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9204 // condition is true.
9205 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9206 SDValue Ops[] = { Op2, Op1, CC, Cond };
9207 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9210 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9211 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9212 // from the AND / OR.
9213 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9214 Opc = Op.getOpcode();
9215 if (Opc != ISD::OR && Opc != ISD::AND)
9217 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9218 Op.getOperand(0).hasOneUse() &&
9219 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9220 Op.getOperand(1).hasOneUse());
9223 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9224 // 1 and that the SETCC node has a single use.
9225 static bool isXor1OfSetCC(SDValue Op) {
9226 if (Op.getOpcode() != ISD::XOR)
9228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9229 if (N1C && N1C->getAPIntValue() == 1) {
9230 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9231 Op.getOperand(0).hasOneUse();
9236 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9237 bool addTest = true;
9238 SDValue Chain = Op.getOperand(0);
9239 SDValue Cond = Op.getOperand(1);
9240 SDValue Dest = Op.getOperand(2);
9241 DebugLoc dl = Op.getDebugLoc();
9243 bool Inverted = false;
9245 if (Cond.getOpcode() == ISD::SETCC) {
9246 // Check for setcc([su]{add,sub,mul}o == 0).
9247 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9248 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9249 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9250 Cond.getOperand(0).getResNo() == 1 &&
9251 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9252 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9253 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9254 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9255 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9256 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9258 Cond = Cond.getOperand(0);
9260 SDValue NewCond = LowerSETCC(Cond, DAG);
9261 if (NewCond.getNode())
9266 // FIXME: LowerXALUO doesn't handle these!!
9267 else if (Cond.getOpcode() == X86ISD::ADD ||
9268 Cond.getOpcode() == X86ISD::SUB ||
9269 Cond.getOpcode() == X86ISD::SMUL ||
9270 Cond.getOpcode() == X86ISD::UMUL)
9271 Cond = LowerXALUO(Cond, DAG);
9274 // Look pass (and (setcc_carry (cmp ...)), 1).
9275 if (Cond.getOpcode() == ISD::AND &&
9276 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9277 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9278 if (C && C->getAPIntValue() == 1)
9279 Cond = Cond.getOperand(0);
9282 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9283 // setting operand in place of the X86ISD::SETCC.
9284 unsigned CondOpcode = Cond.getOpcode();
9285 if (CondOpcode == X86ISD::SETCC ||
9286 CondOpcode == X86ISD::SETCC_CARRY) {
9287 CC = Cond.getOperand(0);
9289 SDValue Cmp = Cond.getOperand(1);
9290 unsigned Opc = Cmp.getOpcode();
9291 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9292 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9296 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9300 // These can only come from an arithmetic instruction with overflow,
9301 // e.g. SADDO, UADDO.
9302 Cond = Cond.getNode()->getOperand(1);
9308 CondOpcode = Cond.getOpcode();
9309 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9310 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9311 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9312 Cond.getOperand(0).getValueType() != MVT::i8)) {
9313 SDValue LHS = Cond.getOperand(0);
9314 SDValue RHS = Cond.getOperand(1);
9318 switch (CondOpcode) {
9319 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9320 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9321 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9322 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9323 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9324 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9325 default: llvm_unreachable("unexpected overflowing operator");
9328 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9329 if (CondOpcode == ISD::UMULO)
9330 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9333 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9335 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9337 if (CondOpcode == ISD::UMULO)
9338 Cond = X86Op.getValue(2);
9340 Cond = X86Op.getValue(1);
9342 CC = DAG.getConstant(X86Cond, MVT::i8);
9346 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9347 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9348 if (CondOpc == ISD::OR) {
9349 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9350 // two branches instead of an explicit OR instruction with a
9352 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9353 isX86LogicalCmp(Cmp)) {
9354 CC = Cond.getOperand(0).getOperand(0);
9355 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9356 Chain, Dest, CC, Cmp);
9357 CC = Cond.getOperand(1).getOperand(0);
9361 } else { // ISD::AND
9362 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9363 // two branches instead of an explicit AND instruction with a
9364 // separate test. However, we only do this if this block doesn't
9365 // have a fall-through edge, because this requires an explicit
9366 // jmp when the condition is false.
9367 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9368 isX86LogicalCmp(Cmp) &&
9369 Op.getNode()->hasOneUse()) {
9370 X86::CondCode CCode =
9371 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9372 CCode = X86::GetOppositeBranchCondition(CCode);
9373 CC = DAG.getConstant(CCode, MVT::i8);
9374 SDNode *User = *Op.getNode()->use_begin();
9375 // Look for an unconditional branch following this conditional branch.
9376 // We need this because we need to reverse the successors in order
9377 // to implement FCMP_OEQ.
9378 if (User->getOpcode() == ISD::BR) {
9379 SDValue FalseBB = User->getOperand(1);
9381 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9382 assert(NewBR == User);
9386 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9387 Chain, Dest, CC, Cmp);
9388 X86::CondCode CCode =
9389 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9390 CCode = X86::GetOppositeBranchCondition(CCode);
9391 CC = DAG.getConstant(CCode, MVT::i8);
9397 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9398 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9399 // It should be transformed during dag combiner except when the condition
9400 // is set by a arithmetics with overflow node.
9401 X86::CondCode CCode =
9402 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9403 CCode = X86::GetOppositeBranchCondition(CCode);
9404 CC = DAG.getConstant(CCode, MVT::i8);
9405 Cond = Cond.getOperand(0).getOperand(1);
9407 } else if (Cond.getOpcode() == ISD::SETCC &&
9408 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9409 // For FCMP_OEQ, we can emit
9410 // two branches instead of an explicit AND instruction with a
9411 // separate test. However, we only do this if this block doesn't
9412 // have a fall-through edge, because this requires an explicit
9413 // jmp when the condition is false.
9414 if (Op.getNode()->hasOneUse()) {
9415 SDNode *User = *Op.getNode()->use_begin();
9416 // Look for an unconditional branch following this conditional branch.
9417 // We need this because we need to reverse the successors in order
9418 // to implement FCMP_OEQ.
9419 if (User->getOpcode() == ISD::BR) {
9420 SDValue FalseBB = User->getOperand(1);
9422 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9423 assert(NewBR == User);
9427 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9428 Cond.getOperand(0), Cond.getOperand(1));
9429 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9430 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9431 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9432 Chain, Dest, CC, Cmp);
9433 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9438 } else if (Cond.getOpcode() == ISD::SETCC &&
9439 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9440 // For FCMP_UNE, we can emit
9441 // two branches instead of an explicit AND instruction with a
9442 // separate test. However, we only do this if this block doesn't
9443 // have a fall-through edge, because this requires an explicit
9444 // jmp when the condition is false.
9445 if (Op.getNode()->hasOneUse()) {
9446 SDNode *User = *Op.getNode()->use_begin();
9447 // Look for an unconditional branch following this conditional branch.
9448 // We need this because we need to reverse the successors in order
9449 // to implement FCMP_UNE.
9450 if (User->getOpcode() == ISD::BR) {
9451 SDValue FalseBB = User->getOperand(1);
9453 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9454 assert(NewBR == User);
9457 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9458 Cond.getOperand(0), Cond.getOperand(1));
9459 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9460 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9461 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9462 Chain, Dest, CC, Cmp);
9463 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9473 // Look pass the truncate if the high bits are known zero.
9474 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9475 Cond = Cond.getOperand(0);
9477 // We know the result of AND is compared against zero. Try to match
9479 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9480 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9481 if (NewSetCC.getNode()) {
9482 CC = NewSetCC.getOperand(0);
9483 Cond = NewSetCC.getOperand(1);
9490 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9491 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9493 Cond = ConvertCmpIfNecessary(Cond, DAG);
9494 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9495 Chain, Dest, CC, Cond);
9499 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9500 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9501 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9502 // that the guard pages used by the OS virtual memory manager are allocated in
9503 // correct sequence.
9505 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9506 SelectionDAG &DAG) const {
9507 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9508 getTargetMachine().Options.EnableSegmentedStacks) &&
9509 "This should be used only on Windows targets or when segmented stacks "
9511 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9512 DebugLoc dl = Op.getDebugLoc();
9515 SDValue Chain = Op.getOperand(0);
9516 SDValue Size = Op.getOperand(1);
9517 // FIXME: Ensure alignment here
9519 bool Is64Bit = Subtarget->is64Bit();
9520 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9522 if (getTargetMachine().Options.EnableSegmentedStacks) {
9523 MachineFunction &MF = DAG.getMachineFunction();
9524 MachineRegisterInfo &MRI = MF.getRegInfo();
9527 // The 64 bit implementation of segmented stacks needs to clobber both r10
9528 // r11. This makes it impossible to use it along with nested parameters.
9529 const Function *F = MF.getFunction();
9531 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9533 if (I->hasNestAttr())
9534 report_fatal_error("Cannot use segmented stacks with functions that "
9535 "have nested arguments.");
9538 const TargetRegisterClass *AddrRegClass =
9539 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9540 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9541 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9542 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9543 DAG.getRegister(Vreg, SPTy));
9544 SDValue Ops1[2] = { Value, Chain };
9545 return DAG.getMergeValues(Ops1, 2, dl);
9548 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9550 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9551 Flag = Chain.getValue(1);
9552 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9554 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9555 Flag = Chain.getValue(1);
9557 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9559 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9560 return DAG.getMergeValues(Ops1, 2, dl);
9564 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9565 MachineFunction &MF = DAG.getMachineFunction();
9566 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9568 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9569 DebugLoc DL = Op.getDebugLoc();
9571 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9572 // vastart just stores the address of the VarArgsFrameIndex slot into the
9573 // memory location argument.
9574 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9576 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9577 MachinePointerInfo(SV), false, false, 0);
9581 // gp_offset (0 - 6 * 8)
9582 // fp_offset (48 - 48 + 8 * 16)
9583 // overflow_arg_area (point to parameters coming in memory).
9585 SmallVector<SDValue, 8> MemOps;
9586 SDValue FIN = Op.getOperand(1);
9588 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9589 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9591 FIN, MachinePointerInfo(SV), false, false, 0);
9592 MemOps.push_back(Store);
9595 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9596 FIN, DAG.getIntPtrConstant(4));
9597 Store = DAG.getStore(Op.getOperand(0), DL,
9598 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9600 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9601 MemOps.push_back(Store);
9603 // Store ptr to overflow_arg_area
9604 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9605 FIN, DAG.getIntPtrConstant(4));
9606 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9608 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9609 MachinePointerInfo(SV, 8),
9611 MemOps.push_back(Store);
9613 // Store ptr to reg_save_area.
9614 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9615 FIN, DAG.getIntPtrConstant(8));
9616 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9618 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9619 MachinePointerInfo(SV, 16), false, false, 0);
9620 MemOps.push_back(Store);
9621 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9622 &MemOps[0], MemOps.size());
9625 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9626 assert(Subtarget->is64Bit() &&
9627 "LowerVAARG only handles 64-bit va_arg!");
9628 assert((Subtarget->isTargetLinux() ||
9629 Subtarget->isTargetDarwin()) &&
9630 "Unhandled target in LowerVAARG");
9631 assert(Op.getNode()->getNumOperands() == 4);
9632 SDValue Chain = Op.getOperand(0);
9633 SDValue SrcPtr = Op.getOperand(1);
9634 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9635 unsigned Align = Op.getConstantOperandVal(3);
9636 DebugLoc dl = Op.getDebugLoc();
9638 EVT ArgVT = Op.getNode()->getValueType(0);
9639 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9640 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9643 // Decide which area this value should be read from.
9644 // TODO: Implement the AMD64 ABI in its entirety. This simple
9645 // selection mechanism works only for the basic types.
9646 if (ArgVT == MVT::f80) {
9647 llvm_unreachable("va_arg for f80 not yet implemented");
9648 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9649 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9650 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9651 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9653 llvm_unreachable("Unhandled argument type in LowerVAARG");
9657 // Sanity Check: Make sure using fp_offset makes sense.
9658 assert(!getTargetMachine().Options.UseSoftFloat &&
9659 !(DAG.getMachineFunction()
9660 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9661 Subtarget->hasSSE1());
9664 // Insert VAARG_64 node into the DAG
9665 // VAARG_64 returns two values: Variable Argument Address, Chain
9666 SmallVector<SDValue, 11> InstOps;
9667 InstOps.push_back(Chain);
9668 InstOps.push_back(SrcPtr);
9669 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9670 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9671 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9672 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9673 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9674 VTs, &InstOps[0], InstOps.size(),
9676 MachinePointerInfo(SV),
9681 Chain = VAARG.getValue(1);
9683 // Load the next argument and return it
9684 return DAG.getLoad(ArgVT, dl,
9687 MachinePointerInfo(),
9688 false, false, false, 0);
9691 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9692 SelectionDAG &DAG) {
9693 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9694 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9695 SDValue Chain = Op.getOperand(0);
9696 SDValue DstPtr = Op.getOperand(1);
9697 SDValue SrcPtr = Op.getOperand(2);
9698 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9699 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9700 DebugLoc DL = Op.getDebugLoc();
9702 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9703 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9705 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9708 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9709 // may or may not be a constant. Takes immediate version of shift as input.
9710 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9711 SDValue SrcOp, SDValue ShAmt,
9712 SelectionDAG &DAG) {
9713 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9715 if (isa<ConstantSDNode>(ShAmt)) {
9716 // Constant may be a TargetConstant. Use a regular constant.
9717 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9719 default: llvm_unreachable("Unknown target vector shift node");
9723 return DAG.getNode(Opc, dl, VT, SrcOp,
9724 DAG.getConstant(ShiftAmt, MVT::i32));
9728 // Change opcode to non-immediate version
9730 default: llvm_unreachable("Unknown target vector shift node");
9731 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9732 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9733 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9736 // Need to build a vector containing shift amount
9737 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9740 ShOps[1] = DAG.getConstant(0, MVT::i32);
9741 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9742 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9744 // The return type has to be a 128-bit type with the same element
9745 // type as the input type.
9746 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9747 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9749 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9750 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9753 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9754 DebugLoc dl = Op.getDebugLoc();
9755 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9757 default: return SDValue(); // Don't custom lower most intrinsics.
9758 // Comparison intrinsics.
9759 case Intrinsic::x86_sse_comieq_ss:
9760 case Intrinsic::x86_sse_comilt_ss:
9761 case Intrinsic::x86_sse_comile_ss:
9762 case Intrinsic::x86_sse_comigt_ss:
9763 case Intrinsic::x86_sse_comige_ss:
9764 case Intrinsic::x86_sse_comineq_ss:
9765 case Intrinsic::x86_sse_ucomieq_ss:
9766 case Intrinsic::x86_sse_ucomilt_ss:
9767 case Intrinsic::x86_sse_ucomile_ss:
9768 case Intrinsic::x86_sse_ucomigt_ss:
9769 case Intrinsic::x86_sse_ucomige_ss:
9770 case Intrinsic::x86_sse_ucomineq_ss:
9771 case Intrinsic::x86_sse2_comieq_sd:
9772 case Intrinsic::x86_sse2_comilt_sd:
9773 case Intrinsic::x86_sse2_comile_sd:
9774 case Intrinsic::x86_sse2_comigt_sd:
9775 case Intrinsic::x86_sse2_comige_sd:
9776 case Intrinsic::x86_sse2_comineq_sd:
9777 case Intrinsic::x86_sse2_ucomieq_sd:
9778 case Intrinsic::x86_sse2_ucomilt_sd:
9779 case Intrinsic::x86_sse2_ucomile_sd:
9780 case Intrinsic::x86_sse2_ucomigt_sd:
9781 case Intrinsic::x86_sse2_ucomige_sd:
9782 case Intrinsic::x86_sse2_ucomineq_sd: {
9786 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9787 case Intrinsic::x86_sse_comieq_ss:
9788 case Intrinsic::x86_sse2_comieq_sd:
9792 case Intrinsic::x86_sse_comilt_ss:
9793 case Intrinsic::x86_sse2_comilt_sd:
9797 case Intrinsic::x86_sse_comile_ss:
9798 case Intrinsic::x86_sse2_comile_sd:
9802 case Intrinsic::x86_sse_comigt_ss:
9803 case Intrinsic::x86_sse2_comigt_sd:
9807 case Intrinsic::x86_sse_comige_ss:
9808 case Intrinsic::x86_sse2_comige_sd:
9812 case Intrinsic::x86_sse_comineq_ss:
9813 case Intrinsic::x86_sse2_comineq_sd:
9817 case Intrinsic::x86_sse_ucomieq_ss:
9818 case Intrinsic::x86_sse2_ucomieq_sd:
9819 Opc = X86ISD::UCOMI;
9822 case Intrinsic::x86_sse_ucomilt_ss:
9823 case Intrinsic::x86_sse2_ucomilt_sd:
9824 Opc = X86ISD::UCOMI;
9827 case Intrinsic::x86_sse_ucomile_ss:
9828 case Intrinsic::x86_sse2_ucomile_sd:
9829 Opc = X86ISD::UCOMI;
9832 case Intrinsic::x86_sse_ucomigt_ss:
9833 case Intrinsic::x86_sse2_ucomigt_sd:
9834 Opc = X86ISD::UCOMI;
9837 case Intrinsic::x86_sse_ucomige_ss:
9838 case Intrinsic::x86_sse2_ucomige_sd:
9839 Opc = X86ISD::UCOMI;
9842 case Intrinsic::x86_sse_ucomineq_ss:
9843 case Intrinsic::x86_sse2_ucomineq_sd:
9844 Opc = X86ISD::UCOMI;
9849 SDValue LHS = Op.getOperand(1);
9850 SDValue RHS = Op.getOperand(2);
9851 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9852 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9853 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9854 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9855 DAG.getConstant(X86CC, MVT::i8), Cond);
9856 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9859 // Arithmetic intrinsics.
9860 case Intrinsic::x86_sse2_pmulu_dq:
9861 case Intrinsic::x86_avx2_pmulu_dq:
9862 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9863 Op.getOperand(1), Op.getOperand(2));
9865 // SSE3/AVX horizontal add/sub intrinsics
9866 case Intrinsic::x86_sse3_hadd_ps:
9867 case Intrinsic::x86_sse3_hadd_pd:
9868 case Intrinsic::x86_avx_hadd_ps_256:
9869 case Intrinsic::x86_avx_hadd_pd_256:
9870 case Intrinsic::x86_sse3_hsub_ps:
9871 case Intrinsic::x86_sse3_hsub_pd:
9872 case Intrinsic::x86_avx_hsub_ps_256:
9873 case Intrinsic::x86_avx_hsub_pd_256:
9874 case Intrinsic::x86_ssse3_phadd_w_128:
9875 case Intrinsic::x86_ssse3_phadd_d_128:
9876 case Intrinsic::x86_avx2_phadd_w:
9877 case Intrinsic::x86_avx2_phadd_d:
9878 case Intrinsic::x86_ssse3_phsub_w_128:
9879 case Intrinsic::x86_ssse3_phsub_d_128:
9880 case Intrinsic::x86_avx2_phsub_w:
9881 case Intrinsic::x86_avx2_phsub_d: {
9884 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9885 case Intrinsic::x86_sse3_hadd_ps:
9886 case Intrinsic::x86_sse3_hadd_pd:
9887 case Intrinsic::x86_avx_hadd_ps_256:
9888 case Intrinsic::x86_avx_hadd_pd_256:
9889 Opcode = X86ISD::FHADD;
9891 case Intrinsic::x86_sse3_hsub_ps:
9892 case Intrinsic::x86_sse3_hsub_pd:
9893 case Intrinsic::x86_avx_hsub_ps_256:
9894 case Intrinsic::x86_avx_hsub_pd_256:
9895 Opcode = X86ISD::FHSUB;
9897 case Intrinsic::x86_ssse3_phadd_w_128:
9898 case Intrinsic::x86_ssse3_phadd_d_128:
9899 case Intrinsic::x86_avx2_phadd_w:
9900 case Intrinsic::x86_avx2_phadd_d:
9901 Opcode = X86ISD::HADD;
9903 case Intrinsic::x86_ssse3_phsub_w_128:
9904 case Intrinsic::x86_ssse3_phsub_d_128:
9905 case Intrinsic::x86_avx2_phsub_w:
9906 case Intrinsic::x86_avx2_phsub_d:
9907 Opcode = X86ISD::HSUB;
9910 return DAG.getNode(Opcode, dl, Op.getValueType(),
9911 Op.getOperand(1), Op.getOperand(2));
9914 // AVX2 variable shift intrinsics
9915 case Intrinsic::x86_avx2_psllv_d:
9916 case Intrinsic::x86_avx2_psllv_q:
9917 case Intrinsic::x86_avx2_psllv_d_256:
9918 case Intrinsic::x86_avx2_psllv_q_256:
9919 case Intrinsic::x86_avx2_psrlv_d:
9920 case Intrinsic::x86_avx2_psrlv_q:
9921 case Intrinsic::x86_avx2_psrlv_d_256:
9922 case Intrinsic::x86_avx2_psrlv_q_256:
9923 case Intrinsic::x86_avx2_psrav_d:
9924 case Intrinsic::x86_avx2_psrav_d_256: {
9927 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9928 case Intrinsic::x86_avx2_psllv_d:
9929 case Intrinsic::x86_avx2_psllv_q:
9930 case Intrinsic::x86_avx2_psllv_d_256:
9931 case Intrinsic::x86_avx2_psllv_q_256:
9934 case Intrinsic::x86_avx2_psrlv_d:
9935 case Intrinsic::x86_avx2_psrlv_q:
9936 case Intrinsic::x86_avx2_psrlv_d_256:
9937 case Intrinsic::x86_avx2_psrlv_q_256:
9940 case Intrinsic::x86_avx2_psrav_d:
9941 case Intrinsic::x86_avx2_psrav_d_256:
9945 return DAG.getNode(Opcode, dl, Op.getValueType(),
9946 Op.getOperand(1), Op.getOperand(2));
9949 case Intrinsic::x86_ssse3_pshuf_b_128:
9950 case Intrinsic::x86_avx2_pshuf_b:
9951 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9952 Op.getOperand(1), Op.getOperand(2));
9954 case Intrinsic::x86_ssse3_psign_b_128:
9955 case Intrinsic::x86_ssse3_psign_w_128:
9956 case Intrinsic::x86_ssse3_psign_d_128:
9957 case Intrinsic::x86_avx2_psign_b:
9958 case Intrinsic::x86_avx2_psign_w:
9959 case Intrinsic::x86_avx2_psign_d:
9960 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9961 Op.getOperand(1), Op.getOperand(2));
9963 case Intrinsic::x86_sse41_insertps:
9964 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9965 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9967 case Intrinsic::x86_avx_vperm2f128_ps_256:
9968 case Intrinsic::x86_avx_vperm2f128_pd_256:
9969 case Intrinsic::x86_avx_vperm2f128_si_256:
9970 case Intrinsic::x86_avx2_vperm2i128:
9971 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9972 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9974 case Intrinsic::x86_avx2_permd:
9975 case Intrinsic::x86_avx2_permps:
9976 // Operands intentionally swapped. Mask is last operand to intrinsic,
9977 // but second operand for node/intruction.
9978 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9979 Op.getOperand(2), Op.getOperand(1));
9981 // ptest and testp intrinsics. The intrinsic these come from are designed to
9982 // return an integer value, not just an instruction so lower it to the ptest
9983 // or testp pattern and a setcc for the result.
9984 case Intrinsic::x86_sse41_ptestz:
9985 case Intrinsic::x86_sse41_ptestc:
9986 case Intrinsic::x86_sse41_ptestnzc:
9987 case Intrinsic::x86_avx_ptestz_256:
9988 case Intrinsic::x86_avx_ptestc_256:
9989 case Intrinsic::x86_avx_ptestnzc_256:
9990 case Intrinsic::x86_avx_vtestz_ps:
9991 case Intrinsic::x86_avx_vtestc_ps:
9992 case Intrinsic::x86_avx_vtestnzc_ps:
9993 case Intrinsic::x86_avx_vtestz_pd:
9994 case Intrinsic::x86_avx_vtestc_pd:
9995 case Intrinsic::x86_avx_vtestnzc_pd:
9996 case Intrinsic::x86_avx_vtestz_ps_256:
9997 case Intrinsic::x86_avx_vtestc_ps_256:
9998 case Intrinsic::x86_avx_vtestnzc_ps_256:
9999 case Intrinsic::x86_avx_vtestz_pd_256:
10000 case Intrinsic::x86_avx_vtestc_pd_256:
10001 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10002 bool IsTestPacked = false;
10005 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10006 case Intrinsic::x86_avx_vtestz_ps:
10007 case Intrinsic::x86_avx_vtestz_pd:
10008 case Intrinsic::x86_avx_vtestz_ps_256:
10009 case Intrinsic::x86_avx_vtestz_pd_256:
10010 IsTestPacked = true; // Fallthrough
10011 case Intrinsic::x86_sse41_ptestz:
10012 case Intrinsic::x86_avx_ptestz_256:
10014 X86CC = X86::COND_E;
10016 case Intrinsic::x86_avx_vtestc_ps:
10017 case Intrinsic::x86_avx_vtestc_pd:
10018 case Intrinsic::x86_avx_vtestc_ps_256:
10019 case Intrinsic::x86_avx_vtestc_pd_256:
10020 IsTestPacked = true; // Fallthrough
10021 case Intrinsic::x86_sse41_ptestc:
10022 case Intrinsic::x86_avx_ptestc_256:
10024 X86CC = X86::COND_B;
10026 case Intrinsic::x86_avx_vtestnzc_ps:
10027 case Intrinsic::x86_avx_vtestnzc_pd:
10028 case Intrinsic::x86_avx_vtestnzc_ps_256:
10029 case Intrinsic::x86_avx_vtestnzc_pd_256:
10030 IsTestPacked = true; // Fallthrough
10031 case Intrinsic::x86_sse41_ptestnzc:
10032 case Intrinsic::x86_avx_ptestnzc_256:
10034 X86CC = X86::COND_A;
10038 SDValue LHS = Op.getOperand(1);
10039 SDValue RHS = Op.getOperand(2);
10040 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10041 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10042 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10043 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10044 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10047 // SSE/AVX shift intrinsics
10048 case Intrinsic::x86_sse2_psll_w:
10049 case Intrinsic::x86_sse2_psll_d:
10050 case Intrinsic::x86_sse2_psll_q:
10051 case Intrinsic::x86_avx2_psll_w:
10052 case Intrinsic::x86_avx2_psll_d:
10053 case Intrinsic::x86_avx2_psll_q:
10054 case Intrinsic::x86_sse2_psrl_w:
10055 case Intrinsic::x86_sse2_psrl_d:
10056 case Intrinsic::x86_sse2_psrl_q:
10057 case Intrinsic::x86_avx2_psrl_w:
10058 case Intrinsic::x86_avx2_psrl_d:
10059 case Intrinsic::x86_avx2_psrl_q:
10060 case Intrinsic::x86_sse2_psra_w:
10061 case Intrinsic::x86_sse2_psra_d:
10062 case Intrinsic::x86_avx2_psra_w:
10063 case Intrinsic::x86_avx2_psra_d: {
10066 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10067 case Intrinsic::x86_sse2_psll_w:
10068 case Intrinsic::x86_sse2_psll_d:
10069 case Intrinsic::x86_sse2_psll_q:
10070 case Intrinsic::x86_avx2_psll_w:
10071 case Intrinsic::x86_avx2_psll_d:
10072 case Intrinsic::x86_avx2_psll_q:
10073 Opcode = X86ISD::VSHL;
10075 case Intrinsic::x86_sse2_psrl_w:
10076 case Intrinsic::x86_sse2_psrl_d:
10077 case Intrinsic::x86_sse2_psrl_q:
10078 case Intrinsic::x86_avx2_psrl_w:
10079 case Intrinsic::x86_avx2_psrl_d:
10080 case Intrinsic::x86_avx2_psrl_q:
10081 Opcode = X86ISD::VSRL;
10083 case Intrinsic::x86_sse2_psra_w:
10084 case Intrinsic::x86_sse2_psra_d:
10085 case Intrinsic::x86_avx2_psra_w:
10086 case Intrinsic::x86_avx2_psra_d:
10087 Opcode = X86ISD::VSRA;
10090 return DAG.getNode(Opcode, dl, Op.getValueType(),
10091 Op.getOperand(1), Op.getOperand(2));
10094 // SSE/AVX immediate shift intrinsics
10095 case Intrinsic::x86_sse2_pslli_w:
10096 case Intrinsic::x86_sse2_pslli_d:
10097 case Intrinsic::x86_sse2_pslli_q:
10098 case Intrinsic::x86_avx2_pslli_w:
10099 case Intrinsic::x86_avx2_pslli_d:
10100 case Intrinsic::x86_avx2_pslli_q:
10101 case Intrinsic::x86_sse2_psrli_w:
10102 case Intrinsic::x86_sse2_psrli_d:
10103 case Intrinsic::x86_sse2_psrli_q:
10104 case Intrinsic::x86_avx2_psrli_w:
10105 case Intrinsic::x86_avx2_psrli_d:
10106 case Intrinsic::x86_avx2_psrli_q:
10107 case Intrinsic::x86_sse2_psrai_w:
10108 case Intrinsic::x86_sse2_psrai_d:
10109 case Intrinsic::x86_avx2_psrai_w:
10110 case Intrinsic::x86_avx2_psrai_d: {
10113 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10114 case Intrinsic::x86_sse2_pslli_w:
10115 case Intrinsic::x86_sse2_pslli_d:
10116 case Intrinsic::x86_sse2_pslli_q:
10117 case Intrinsic::x86_avx2_pslli_w:
10118 case Intrinsic::x86_avx2_pslli_d:
10119 case Intrinsic::x86_avx2_pslli_q:
10120 Opcode = X86ISD::VSHLI;
10122 case Intrinsic::x86_sse2_psrli_w:
10123 case Intrinsic::x86_sse2_psrli_d:
10124 case Intrinsic::x86_sse2_psrli_q:
10125 case Intrinsic::x86_avx2_psrli_w:
10126 case Intrinsic::x86_avx2_psrli_d:
10127 case Intrinsic::x86_avx2_psrli_q:
10128 Opcode = X86ISD::VSRLI;
10130 case Intrinsic::x86_sse2_psrai_w:
10131 case Intrinsic::x86_sse2_psrai_d:
10132 case Intrinsic::x86_avx2_psrai_w:
10133 case Intrinsic::x86_avx2_psrai_d:
10134 Opcode = X86ISD::VSRAI;
10137 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10138 Op.getOperand(1), Op.getOperand(2), DAG);
10141 case Intrinsic::x86_sse42_pcmpistria128:
10142 case Intrinsic::x86_sse42_pcmpestria128:
10143 case Intrinsic::x86_sse42_pcmpistric128:
10144 case Intrinsic::x86_sse42_pcmpestric128:
10145 case Intrinsic::x86_sse42_pcmpistrio128:
10146 case Intrinsic::x86_sse42_pcmpestrio128:
10147 case Intrinsic::x86_sse42_pcmpistris128:
10148 case Intrinsic::x86_sse42_pcmpestris128:
10149 case Intrinsic::x86_sse42_pcmpistriz128:
10150 case Intrinsic::x86_sse42_pcmpestriz128: {
10154 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10155 case Intrinsic::x86_sse42_pcmpistria128:
10156 Opcode = X86ISD::PCMPISTRI;
10157 X86CC = X86::COND_A;
10159 case Intrinsic::x86_sse42_pcmpestria128:
10160 Opcode = X86ISD::PCMPESTRI;
10161 X86CC = X86::COND_A;
10163 case Intrinsic::x86_sse42_pcmpistric128:
10164 Opcode = X86ISD::PCMPISTRI;
10165 X86CC = X86::COND_B;
10167 case Intrinsic::x86_sse42_pcmpestric128:
10168 Opcode = X86ISD::PCMPESTRI;
10169 X86CC = X86::COND_B;
10171 case Intrinsic::x86_sse42_pcmpistrio128:
10172 Opcode = X86ISD::PCMPISTRI;
10173 X86CC = X86::COND_O;
10175 case Intrinsic::x86_sse42_pcmpestrio128:
10176 Opcode = X86ISD::PCMPESTRI;
10177 X86CC = X86::COND_O;
10179 case Intrinsic::x86_sse42_pcmpistris128:
10180 Opcode = X86ISD::PCMPISTRI;
10181 X86CC = X86::COND_S;
10183 case Intrinsic::x86_sse42_pcmpestris128:
10184 Opcode = X86ISD::PCMPESTRI;
10185 X86CC = X86::COND_S;
10187 case Intrinsic::x86_sse42_pcmpistriz128:
10188 Opcode = X86ISD::PCMPISTRI;
10189 X86CC = X86::COND_E;
10191 case Intrinsic::x86_sse42_pcmpestriz128:
10192 Opcode = X86ISD::PCMPESTRI;
10193 X86CC = X86::COND_E;
10196 SmallVector<SDValue, 5> NewOps;
10197 NewOps.append(Op->op_begin()+1, Op->op_end());
10198 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10199 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10200 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10201 DAG.getConstant(X86CC, MVT::i8),
10202 SDValue(PCMP.getNode(), 1));
10203 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10206 case Intrinsic::x86_sse42_pcmpistri128:
10207 case Intrinsic::x86_sse42_pcmpestri128: {
10209 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10210 Opcode = X86ISD::PCMPISTRI;
10212 Opcode = X86ISD::PCMPESTRI;
10214 SmallVector<SDValue, 5> NewOps;
10215 NewOps.append(Op->op_begin()+1, Op->op_end());
10216 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10217 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10219 case Intrinsic::x86_fma_vfmadd_ps:
10220 case Intrinsic::x86_fma_vfmadd_pd:
10221 case Intrinsic::x86_fma_vfmsub_ps:
10222 case Intrinsic::x86_fma_vfmsub_pd:
10223 case Intrinsic::x86_fma_vfnmadd_ps:
10224 case Intrinsic::x86_fma_vfnmadd_pd:
10225 case Intrinsic::x86_fma_vfnmsub_ps:
10226 case Intrinsic::x86_fma_vfnmsub_pd:
10227 case Intrinsic::x86_fma_vfmaddsub_ps:
10228 case Intrinsic::x86_fma_vfmaddsub_pd:
10229 case Intrinsic::x86_fma_vfmsubadd_ps:
10230 case Intrinsic::x86_fma_vfmsubadd_pd:
10231 case Intrinsic::x86_fma_vfmadd_ps_256:
10232 case Intrinsic::x86_fma_vfmadd_pd_256:
10233 case Intrinsic::x86_fma_vfmsub_ps_256:
10234 case Intrinsic::x86_fma_vfmsub_pd_256:
10235 case Intrinsic::x86_fma_vfnmadd_ps_256:
10236 case Intrinsic::x86_fma_vfnmadd_pd_256:
10237 case Intrinsic::x86_fma_vfnmsub_ps_256:
10238 case Intrinsic::x86_fma_vfnmsub_pd_256:
10239 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10240 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10241 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10242 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10245 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10246 case Intrinsic::x86_fma_vfmadd_ps:
10247 case Intrinsic::x86_fma_vfmadd_pd:
10248 case Intrinsic::x86_fma_vfmadd_ps_256:
10249 case Intrinsic::x86_fma_vfmadd_pd_256:
10250 Opc = X86ISD::FMADD;
10252 case Intrinsic::x86_fma_vfmsub_ps:
10253 case Intrinsic::x86_fma_vfmsub_pd:
10254 case Intrinsic::x86_fma_vfmsub_ps_256:
10255 case Intrinsic::x86_fma_vfmsub_pd_256:
10256 Opc = X86ISD::FMSUB;
10258 case Intrinsic::x86_fma_vfnmadd_ps:
10259 case Intrinsic::x86_fma_vfnmadd_pd:
10260 case Intrinsic::x86_fma_vfnmadd_ps_256:
10261 case Intrinsic::x86_fma_vfnmadd_pd_256:
10262 Opc = X86ISD::FNMADD;
10264 case Intrinsic::x86_fma_vfnmsub_ps:
10265 case Intrinsic::x86_fma_vfnmsub_pd:
10266 case Intrinsic::x86_fma_vfnmsub_ps_256:
10267 case Intrinsic::x86_fma_vfnmsub_pd_256:
10268 Opc = X86ISD::FNMSUB;
10270 case Intrinsic::x86_fma_vfmaddsub_ps:
10271 case Intrinsic::x86_fma_vfmaddsub_pd:
10272 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10273 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10274 Opc = X86ISD::FMADDSUB;
10276 case Intrinsic::x86_fma_vfmsubadd_ps:
10277 case Intrinsic::x86_fma_vfmsubadd_pd:
10278 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10279 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10280 Opc = X86ISD::FMSUBADD;
10284 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10285 Op.getOperand(2), Op.getOperand(3));
10290 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10291 DebugLoc dl = Op.getDebugLoc();
10292 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10294 default: return SDValue(); // Don't custom lower most intrinsics.
10296 // RDRAND intrinsics.
10297 case Intrinsic::x86_rdrand_16:
10298 case Intrinsic::x86_rdrand_32:
10299 case Intrinsic::x86_rdrand_64: {
10300 // Emit the node with the right value type.
10301 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10302 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10304 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10305 // return the value from Rand, which is always 0, casted to i32.
10306 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10307 DAG.getConstant(1, Op->getValueType(1)),
10308 DAG.getConstant(X86::COND_B, MVT::i32),
10309 SDValue(Result.getNode(), 1) };
10310 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10311 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10314 // Return { result, isValid, chain }.
10315 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10316 SDValue(Result.getNode(), 2));
10321 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10322 SelectionDAG &DAG) const {
10323 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10324 MFI->setReturnAddressIsTaken(true);
10326 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10327 DebugLoc dl = Op.getDebugLoc();
10330 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10332 DAG.getConstant(TD->getPointerSize(),
10333 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10334 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10335 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10336 FrameAddr, Offset),
10337 MachinePointerInfo(), false, false, false, 0);
10340 // Just load the return address.
10341 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10342 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10343 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10346 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10347 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10348 MFI->setFrameAddressIsTaken(true);
10350 EVT VT = Op.getValueType();
10351 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10352 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10353 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10354 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10356 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10357 MachinePointerInfo(),
10358 false, false, false, 0);
10362 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10363 SelectionDAG &DAG) const {
10364 return DAG.getIntPtrConstant(2*TD->getPointerSize());
10367 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10368 SDValue Chain = Op.getOperand(0);
10369 SDValue Offset = Op.getOperand(1);
10370 SDValue Handler = Op.getOperand(2);
10371 DebugLoc dl = Op.getDebugLoc();
10373 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10374 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10376 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10378 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10379 DAG.getIntPtrConstant(TD->getPointerSize()));
10380 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10381 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10383 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10385 return DAG.getNode(X86ISD::EH_RETURN, dl,
10387 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10390 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10391 return Op.getOperand(0);
10394 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10395 SelectionDAG &DAG) const {
10396 SDValue Root = Op.getOperand(0);
10397 SDValue Trmp = Op.getOperand(1); // trampoline
10398 SDValue FPtr = Op.getOperand(2); // nested function
10399 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10400 DebugLoc dl = Op.getDebugLoc();
10402 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10404 if (Subtarget->is64Bit()) {
10405 SDValue OutChains[6];
10407 // Large code-model.
10408 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10409 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10411 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10412 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10414 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10416 // Load the pointer to the nested function into R11.
10417 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10418 SDValue Addr = Trmp;
10419 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10420 Addr, MachinePointerInfo(TrmpAddr),
10423 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10424 DAG.getConstant(2, MVT::i64));
10425 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10426 MachinePointerInfo(TrmpAddr, 2),
10429 // Load the 'nest' parameter value into R10.
10430 // R10 is specified in X86CallingConv.td
10431 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10432 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10433 DAG.getConstant(10, MVT::i64));
10434 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10435 Addr, MachinePointerInfo(TrmpAddr, 10),
10438 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10439 DAG.getConstant(12, MVT::i64));
10440 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10441 MachinePointerInfo(TrmpAddr, 12),
10444 // Jump to the nested function.
10445 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10446 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10447 DAG.getConstant(20, MVT::i64));
10448 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10449 Addr, MachinePointerInfo(TrmpAddr, 20),
10452 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10453 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10454 DAG.getConstant(22, MVT::i64));
10455 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10456 MachinePointerInfo(TrmpAddr, 22),
10459 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10461 const Function *Func =
10462 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10463 CallingConv::ID CC = Func->getCallingConv();
10468 llvm_unreachable("Unsupported calling convention");
10469 case CallingConv::C:
10470 case CallingConv::X86_StdCall: {
10471 // Pass 'nest' parameter in ECX.
10472 // Must be kept in sync with X86CallingConv.td
10473 NestReg = X86::ECX;
10475 // Check that ECX wasn't needed by an 'inreg' parameter.
10476 FunctionType *FTy = Func->getFunctionType();
10477 const AttrListPtr &Attrs = Func->getAttributes();
10479 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10480 unsigned InRegCount = 0;
10483 for (FunctionType::param_iterator I = FTy->param_begin(),
10484 E = FTy->param_end(); I != E; ++I, ++Idx)
10485 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10486 // FIXME: should only count parameters that are lowered to integers.
10487 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10489 if (InRegCount > 2) {
10490 report_fatal_error("Nest register in use - reduce number of inreg"
10496 case CallingConv::X86_FastCall:
10497 case CallingConv::X86_ThisCall:
10498 case CallingConv::Fast:
10499 // Pass 'nest' parameter in EAX.
10500 // Must be kept in sync with X86CallingConv.td
10501 NestReg = X86::EAX;
10505 SDValue OutChains[4];
10506 SDValue Addr, Disp;
10508 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10509 DAG.getConstant(10, MVT::i32));
10510 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10512 // This is storing the opcode for MOV32ri.
10513 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10514 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10515 OutChains[0] = DAG.getStore(Root, dl,
10516 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10517 Trmp, MachinePointerInfo(TrmpAddr),
10520 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10521 DAG.getConstant(1, MVT::i32));
10522 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10523 MachinePointerInfo(TrmpAddr, 1),
10526 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10527 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10528 DAG.getConstant(5, MVT::i32));
10529 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10530 MachinePointerInfo(TrmpAddr, 5),
10533 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10534 DAG.getConstant(6, MVT::i32));
10535 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10536 MachinePointerInfo(TrmpAddr, 6),
10539 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10543 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10544 SelectionDAG &DAG) const {
10546 The rounding mode is in bits 11:10 of FPSR, and has the following
10548 00 Round to nearest
10553 FLT_ROUNDS, on the other hand, expects the following:
10560 To perform the conversion, we do:
10561 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10564 MachineFunction &MF = DAG.getMachineFunction();
10565 const TargetMachine &TM = MF.getTarget();
10566 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10567 unsigned StackAlignment = TFI.getStackAlignment();
10568 EVT VT = Op.getValueType();
10569 DebugLoc DL = Op.getDebugLoc();
10571 // Save FP Control Word to stack slot
10572 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10573 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10576 MachineMemOperand *MMO =
10577 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10578 MachineMemOperand::MOStore, 2, 2);
10580 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10581 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10582 DAG.getVTList(MVT::Other),
10583 Ops, 2, MVT::i16, MMO);
10585 // Load FP Control Word from stack slot
10586 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10587 MachinePointerInfo(), false, false, false, 0);
10589 // Transform as necessary
10591 DAG.getNode(ISD::SRL, DL, MVT::i16,
10592 DAG.getNode(ISD::AND, DL, MVT::i16,
10593 CWD, DAG.getConstant(0x800, MVT::i16)),
10594 DAG.getConstant(11, MVT::i8));
10596 DAG.getNode(ISD::SRL, DL, MVT::i16,
10597 DAG.getNode(ISD::AND, DL, MVT::i16,
10598 CWD, DAG.getConstant(0x400, MVT::i16)),
10599 DAG.getConstant(9, MVT::i8));
10602 DAG.getNode(ISD::AND, DL, MVT::i16,
10603 DAG.getNode(ISD::ADD, DL, MVT::i16,
10604 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10605 DAG.getConstant(1, MVT::i16)),
10606 DAG.getConstant(3, MVT::i16));
10609 return DAG.getNode((VT.getSizeInBits() < 16 ?
10610 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10613 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10614 EVT VT = Op.getValueType();
10616 unsigned NumBits = VT.getSizeInBits();
10617 DebugLoc dl = Op.getDebugLoc();
10619 Op = Op.getOperand(0);
10620 if (VT == MVT::i8) {
10621 // Zero extend to i32 since there is not an i8 bsr.
10623 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10626 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10627 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10628 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10630 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10633 DAG.getConstant(NumBits+NumBits-1, OpVT),
10634 DAG.getConstant(X86::COND_E, MVT::i8),
10637 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10639 // Finally xor with NumBits-1.
10640 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10643 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10647 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10648 EVT VT = Op.getValueType();
10650 unsigned NumBits = VT.getSizeInBits();
10651 DebugLoc dl = Op.getDebugLoc();
10653 Op = Op.getOperand(0);
10654 if (VT == MVT::i8) {
10655 // Zero extend to i32 since there is not an i8 bsr.
10657 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10660 // Issue a bsr (scan bits in reverse).
10661 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10662 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10664 // And xor with NumBits-1.
10665 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10668 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10672 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10673 EVT VT = Op.getValueType();
10674 unsigned NumBits = VT.getSizeInBits();
10675 DebugLoc dl = Op.getDebugLoc();
10676 Op = Op.getOperand(0);
10678 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10679 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10680 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10682 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10685 DAG.getConstant(NumBits, VT),
10686 DAG.getConstant(X86::COND_E, MVT::i8),
10689 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10692 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10693 // ones, and then concatenate the result back.
10694 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10695 EVT VT = Op.getValueType();
10697 assert(VT.is256BitVector() && VT.isInteger() &&
10698 "Unsupported value type for operation");
10700 unsigned NumElems = VT.getVectorNumElements();
10701 DebugLoc dl = Op.getDebugLoc();
10703 // Extract the LHS vectors
10704 SDValue LHS = Op.getOperand(0);
10705 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10706 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10708 // Extract the RHS vectors
10709 SDValue RHS = Op.getOperand(1);
10710 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10711 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10713 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10714 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10716 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10717 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10718 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10721 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10722 assert(Op.getValueType().is256BitVector() &&
10723 Op.getValueType().isInteger() &&
10724 "Only handle AVX 256-bit vector integer operation");
10725 return Lower256IntArith(Op, DAG);
10728 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10729 assert(Op.getValueType().is256BitVector() &&
10730 Op.getValueType().isInteger() &&
10731 "Only handle AVX 256-bit vector integer operation");
10732 return Lower256IntArith(Op, DAG);
10735 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10736 SelectionDAG &DAG) {
10737 EVT VT = Op.getValueType();
10739 // Decompose 256-bit ops into smaller 128-bit ops.
10740 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10741 return Lower256IntArith(Op, DAG);
10743 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10744 "Only know how to lower V2I64/V4I64 multiply");
10746 DebugLoc dl = Op.getDebugLoc();
10748 // Ahi = psrlqi(a, 32);
10749 // Bhi = psrlqi(b, 32);
10751 // AloBlo = pmuludq(a, b);
10752 // AloBhi = pmuludq(a, Bhi);
10753 // AhiBlo = pmuludq(Ahi, b);
10755 // AloBhi = psllqi(AloBhi, 32);
10756 // AhiBlo = psllqi(AhiBlo, 32);
10757 // return AloBlo + AloBhi + AhiBlo;
10759 SDValue A = Op.getOperand(0);
10760 SDValue B = Op.getOperand(1);
10762 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10764 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10765 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10767 // Bit cast to 32-bit vectors for MULUDQ
10768 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10769 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10770 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10771 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10772 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10774 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10775 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10776 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10778 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10779 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10781 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10782 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10785 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10787 EVT VT = Op.getValueType();
10788 DebugLoc dl = Op.getDebugLoc();
10789 SDValue R = Op.getOperand(0);
10790 SDValue Amt = Op.getOperand(1);
10791 LLVMContext *Context = DAG.getContext();
10793 if (!Subtarget->hasSSE2())
10796 // Optimize shl/srl/sra with constant shift amount.
10797 if (isSplatVector(Amt.getNode())) {
10798 SDValue SclrAmt = Amt->getOperand(0);
10799 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10800 uint64_t ShiftAmt = C->getZExtValue();
10802 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10803 (Subtarget->hasAVX2() &&
10804 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10805 if (Op.getOpcode() == ISD::SHL)
10806 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10807 DAG.getConstant(ShiftAmt, MVT::i32));
10808 if (Op.getOpcode() == ISD::SRL)
10809 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10810 DAG.getConstant(ShiftAmt, MVT::i32));
10811 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10812 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10813 DAG.getConstant(ShiftAmt, MVT::i32));
10816 if (VT == MVT::v16i8) {
10817 if (Op.getOpcode() == ISD::SHL) {
10818 // Make a large shift.
10819 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10820 DAG.getConstant(ShiftAmt, MVT::i32));
10821 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10822 // Zero out the rightmost bits.
10823 SmallVector<SDValue, 16> V(16,
10824 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10826 return DAG.getNode(ISD::AND, dl, VT, SHL,
10827 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10829 if (Op.getOpcode() == ISD::SRL) {
10830 // Make a large shift.
10831 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10832 DAG.getConstant(ShiftAmt, MVT::i32));
10833 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10834 // Zero out the leftmost bits.
10835 SmallVector<SDValue, 16> V(16,
10836 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10838 return DAG.getNode(ISD::AND, dl, VT, SRL,
10839 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10841 if (Op.getOpcode() == ISD::SRA) {
10842 if (ShiftAmt == 7) {
10843 // R s>> 7 === R s< 0
10844 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10845 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10848 // R s>> a === ((R u>> a) ^ m) - m
10849 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10850 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10852 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10853 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10854 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10857 llvm_unreachable("Unknown shift opcode.");
10860 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10861 if (Op.getOpcode() == ISD::SHL) {
10862 // Make a large shift.
10863 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10864 DAG.getConstant(ShiftAmt, MVT::i32));
10865 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10866 // Zero out the rightmost bits.
10867 SmallVector<SDValue, 32> V(32,
10868 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10870 return DAG.getNode(ISD::AND, dl, VT, SHL,
10871 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10873 if (Op.getOpcode() == ISD::SRL) {
10874 // Make a large shift.
10875 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10876 DAG.getConstant(ShiftAmt, MVT::i32));
10877 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10878 // Zero out the leftmost bits.
10879 SmallVector<SDValue, 32> V(32,
10880 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10882 return DAG.getNode(ISD::AND, dl, VT, SRL,
10883 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10885 if (Op.getOpcode() == ISD::SRA) {
10886 if (ShiftAmt == 7) {
10887 // R s>> 7 === R s< 0
10888 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10889 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10892 // R s>> a === ((R u>> a) ^ m) - m
10893 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10894 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10896 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10897 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10898 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10901 llvm_unreachable("Unknown shift opcode.");
10906 // Lower SHL with variable shift amount.
10907 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10908 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10909 DAG.getConstant(23, MVT::i32));
10911 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10912 Constant *C = ConstantDataVector::get(*Context, CV);
10913 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10914 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10915 MachinePointerInfo::getConstantPool(),
10916 false, false, false, 16);
10918 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10919 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10920 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10921 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10923 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10924 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10927 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10928 DAG.getConstant(5, MVT::i32));
10929 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10931 // Turn 'a' into a mask suitable for VSELECT
10932 SDValue VSelM = DAG.getConstant(0x80, VT);
10933 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10934 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10936 SDValue CM1 = DAG.getConstant(0x0f, VT);
10937 SDValue CM2 = DAG.getConstant(0x3f, VT);
10939 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10940 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10941 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10942 DAG.getConstant(4, MVT::i32), DAG);
10943 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10944 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10947 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10948 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10949 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10951 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10952 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10953 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10954 DAG.getConstant(2, MVT::i32), DAG);
10955 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10956 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10959 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10960 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10961 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10963 // return VSELECT(r, r+r, a);
10964 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10965 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10969 // Decompose 256-bit shifts into smaller 128-bit shifts.
10970 if (VT.is256BitVector()) {
10971 unsigned NumElems = VT.getVectorNumElements();
10972 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10973 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10975 // Extract the two vectors
10976 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10977 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10979 // Recreate the shift amount vectors
10980 SDValue Amt1, Amt2;
10981 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10982 // Constant shift amount
10983 SmallVector<SDValue, 4> Amt1Csts;
10984 SmallVector<SDValue, 4> Amt2Csts;
10985 for (unsigned i = 0; i != NumElems/2; ++i)
10986 Amt1Csts.push_back(Amt->getOperand(i));
10987 for (unsigned i = NumElems/2; i != NumElems; ++i)
10988 Amt2Csts.push_back(Amt->getOperand(i));
10990 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10991 &Amt1Csts[0], NumElems/2);
10992 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10993 &Amt2Csts[0], NumElems/2);
10995 // Variable shift amount
10996 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10997 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11000 // Issue new vector shifts for the smaller types
11001 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11002 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11004 // Concatenate the result back
11005 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11011 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11012 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11013 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11014 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11015 // has only one use.
11016 SDNode *N = Op.getNode();
11017 SDValue LHS = N->getOperand(0);
11018 SDValue RHS = N->getOperand(1);
11019 unsigned BaseOp = 0;
11021 DebugLoc DL = Op.getDebugLoc();
11022 switch (Op.getOpcode()) {
11023 default: llvm_unreachable("Unknown ovf instruction!");
11025 // A subtract of one will be selected as a INC. Note that INC doesn't
11026 // set CF, so we can't do this for UADDO.
11027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11029 BaseOp = X86ISD::INC;
11030 Cond = X86::COND_O;
11033 BaseOp = X86ISD::ADD;
11034 Cond = X86::COND_O;
11037 BaseOp = X86ISD::ADD;
11038 Cond = X86::COND_B;
11041 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11042 // set CF, so we can't do this for USUBO.
11043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11045 BaseOp = X86ISD::DEC;
11046 Cond = X86::COND_O;
11049 BaseOp = X86ISD::SUB;
11050 Cond = X86::COND_O;
11053 BaseOp = X86ISD::SUB;
11054 Cond = X86::COND_B;
11057 BaseOp = X86ISD::SMUL;
11058 Cond = X86::COND_O;
11060 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11061 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11063 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11066 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11067 DAG.getConstant(X86::COND_O, MVT::i32),
11068 SDValue(Sum.getNode(), 2));
11070 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11074 // Also sets EFLAGS.
11075 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11076 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11079 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11080 DAG.getConstant(Cond, MVT::i32),
11081 SDValue(Sum.getNode(), 1));
11083 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11086 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11087 SelectionDAG &DAG) const {
11088 DebugLoc dl = Op.getDebugLoc();
11089 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11090 EVT VT = Op.getValueType();
11092 if (!Subtarget->hasSSE2() || !VT.isVector())
11095 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11096 ExtraVT.getScalarType().getSizeInBits();
11097 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11099 switch (VT.getSimpleVT().SimpleTy) {
11100 default: return SDValue();
11103 if (!Subtarget->hasAVX())
11105 if (!Subtarget->hasAVX2()) {
11106 // needs to be split
11107 unsigned NumElems = VT.getVectorNumElements();
11109 // Extract the LHS vectors
11110 SDValue LHS = Op.getOperand(0);
11111 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11112 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11114 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11115 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11117 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11118 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11119 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11121 SDValue Extra = DAG.getValueType(ExtraVT);
11123 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11124 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11126 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11131 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11132 Op.getOperand(0), ShAmt, DAG);
11133 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11139 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11140 SelectionDAG &DAG) {
11141 DebugLoc dl = Op.getDebugLoc();
11143 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11144 // There isn't any reason to disable it if the target processor supports it.
11145 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11146 SDValue Chain = Op.getOperand(0);
11147 SDValue Zero = DAG.getConstant(0, MVT::i32);
11149 DAG.getRegister(X86::ESP, MVT::i32), // Base
11150 DAG.getTargetConstant(1, MVT::i8), // Scale
11151 DAG.getRegister(0, MVT::i32), // Index
11152 DAG.getTargetConstant(0, MVT::i32), // Disp
11153 DAG.getRegister(0, MVT::i32), // Segment.
11158 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11159 array_lengthof(Ops));
11160 return SDValue(Res, 0);
11163 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11165 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11167 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11168 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11169 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11170 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11172 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11173 if (!Op1 && !Op2 && !Op3 && Op4)
11174 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11176 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11177 if (Op1 && !Op2 && !Op3 && !Op4)
11178 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11180 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11182 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11185 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11186 SelectionDAG &DAG) {
11187 DebugLoc dl = Op.getDebugLoc();
11188 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11189 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11190 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11191 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11193 // The only fence that needs an instruction is a sequentially-consistent
11194 // cross-thread fence.
11195 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11196 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11197 // no-sse2). There isn't any reason to disable it if the target processor
11199 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11200 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11202 SDValue Chain = Op.getOperand(0);
11203 SDValue Zero = DAG.getConstant(0, MVT::i32);
11205 DAG.getRegister(X86::ESP, MVT::i32), // Base
11206 DAG.getTargetConstant(1, MVT::i8), // Scale
11207 DAG.getRegister(0, MVT::i32), // Index
11208 DAG.getTargetConstant(0, MVT::i32), // Disp
11209 DAG.getRegister(0, MVT::i32), // Segment.
11214 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11215 array_lengthof(Ops));
11216 return SDValue(Res, 0);
11219 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11220 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11224 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11225 SelectionDAG &DAG) {
11226 EVT T = Op.getValueType();
11227 DebugLoc DL = Op.getDebugLoc();
11230 switch(T.getSimpleVT().SimpleTy) {
11231 default: llvm_unreachable("Invalid value type!");
11232 case MVT::i8: Reg = X86::AL; size = 1; break;
11233 case MVT::i16: Reg = X86::AX; size = 2; break;
11234 case MVT::i32: Reg = X86::EAX; size = 4; break;
11236 assert(Subtarget->is64Bit() && "Node not type legal!");
11237 Reg = X86::RAX; size = 8;
11240 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11241 Op.getOperand(2), SDValue());
11242 SDValue Ops[] = { cpIn.getValue(0),
11245 DAG.getTargetConstant(size, MVT::i8),
11246 cpIn.getValue(1) };
11247 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11248 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11249 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11252 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11256 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11257 SelectionDAG &DAG) {
11258 assert(Subtarget->is64Bit() && "Result not type legalized?");
11259 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11260 SDValue TheChain = Op.getOperand(0);
11261 DebugLoc dl = Op.getDebugLoc();
11262 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11263 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11264 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11266 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11267 DAG.getConstant(32, MVT::i8));
11269 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11272 return DAG.getMergeValues(Ops, 2, dl);
11275 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11276 EVT SrcVT = Op.getOperand(0).getValueType();
11277 EVT DstVT = Op.getValueType();
11278 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11279 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11280 assert((DstVT == MVT::i64 ||
11281 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11282 "Unexpected custom BITCAST");
11283 // i64 <=> MMX conversions are Legal.
11284 if (SrcVT==MVT::i64 && DstVT.isVector())
11286 if (DstVT==MVT::i64 && SrcVT.isVector())
11288 // MMX <=> MMX conversions are Legal.
11289 if (SrcVT.isVector() && DstVT.isVector())
11291 // All other conversions need to be expanded.
11295 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11296 SDNode *Node = Op.getNode();
11297 DebugLoc dl = Node->getDebugLoc();
11298 EVT T = Node->getValueType(0);
11299 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11300 DAG.getConstant(0, T), Node->getOperand(2));
11301 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11302 cast<AtomicSDNode>(Node)->getMemoryVT(),
11303 Node->getOperand(0),
11304 Node->getOperand(1), negOp,
11305 cast<AtomicSDNode>(Node)->getSrcValue(),
11306 cast<AtomicSDNode>(Node)->getAlignment(),
11307 cast<AtomicSDNode>(Node)->getOrdering(),
11308 cast<AtomicSDNode>(Node)->getSynchScope());
11311 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11312 SDNode *Node = Op.getNode();
11313 DebugLoc dl = Node->getDebugLoc();
11314 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11316 // Convert seq_cst store -> xchg
11317 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11318 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11319 // (The only way to get a 16-byte store is cmpxchg16b)
11320 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11321 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11322 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11323 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11324 cast<AtomicSDNode>(Node)->getMemoryVT(),
11325 Node->getOperand(0),
11326 Node->getOperand(1), Node->getOperand(2),
11327 cast<AtomicSDNode>(Node)->getMemOperand(),
11328 cast<AtomicSDNode>(Node)->getOrdering(),
11329 cast<AtomicSDNode>(Node)->getSynchScope());
11330 return Swap.getValue(1);
11332 // Other atomic stores have a simple pattern.
11336 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11337 EVT VT = Op.getNode()->getValueType(0);
11339 // Let legalize expand this if it isn't a legal type yet.
11340 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11343 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11346 bool ExtraOp = false;
11347 switch (Op.getOpcode()) {
11348 default: llvm_unreachable("Invalid code");
11349 case ISD::ADDC: Opc = X86ISD::ADD; break;
11350 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11351 case ISD::SUBC: Opc = X86ISD::SUB; break;
11352 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11356 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11358 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11359 Op.getOperand(1), Op.getOperand(2));
11362 /// LowerOperation - Provide custom lowering hooks for some operations.
11364 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11365 switch (Op.getOpcode()) {
11366 default: llvm_unreachable("Should not custom lower this!");
11367 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11368 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11369 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11370 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11371 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11372 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11373 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11374 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11375 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11376 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11377 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11378 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11379 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11380 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11381 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11382 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11383 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11384 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11385 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11386 case ISD::SHL_PARTS:
11387 case ISD::SRA_PARTS:
11388 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11389 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11390 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11391 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11392 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11393 case ISD::FABS: return LowerFABS(Op, DAG);
11394 case ISD::FNEG: return LowerFNEG(Op, DAG);
11395 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11396 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11397 case ISD::SETCC: return LowerSETCC(Op, DAG);
11398 case ISD::SELECT: return LowerSELECT(Op, DAG);
11399 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11400 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11401 case ISD::VASTART: return LowerVASTART(Op, DAG);
11402 case ISD::VAARG: return LowerVAARG(Op, DAG);
11403 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11404 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11405 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11406 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11407 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11408 case ISD::FRAME_TO_ARGS_OFFSET:
11409 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11410 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11411 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11412 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11413 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11414 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11415 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11416 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11417 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11418 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11421 case ISD::SHL: return LowerShift(Op, DAG);
11427 case ISD::UMULO: return LowerXALUO(Op, DAG);
11428 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11429 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11433 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11434 case ISD::ADD: return LowerADD(Op, DAG);
11435 case ISD::SUB: return LowerSUB(Op, DAG);
11439 static void ReplaceATOMIC_LOAD(SDNode *Node,
11440 SmallVectorImpl<SDValue> &Results,
11441 SelectionDAG &DAG) {
11442 DebugLoc dl = Node->getDebugLoc();
11443 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11445 // Convert wide load -> cmpxchg8b/cmpxchg16b
11446 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11447 // (The only way to get a 16-byte load is cmpxchg16b)
11448 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11449 SDValue Zero = DAG.getConstant(0, VT);
11450 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11451 Node->getOperand(0),
11452 Node->getOperand(1), Zero, Zero,
11453 cast<AtomicSDNode>(Node)->getMemOperand(),
11454 cast<AtomicSDNode>(Node)->getOrdering(),
11455 cast<AtomicSDNode>(Node)->getSynchScope());
11456 Results.push_back(Swap.getValue(0));
11457 Results.push_back(Swap.getValue(1));
11461 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11462 SelectionDAG &DAG, unsigned NewOp) {
11463 DebugLoc dl = Node->getDebugLoc();
11464 assert (Node->getValueType(0) == MVT::i64 &&
11465 "Only know how to expand i64 atomics");
11467 SDValue Chain = Node->getOperand(0);
11468 SDValue In1 = Node->getOperand(1);
11469 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11470 Node->getOperand(2), DAG.getIntPtrConstant(0));
11471 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11472 Node->getOperand(2), DAG.getIntPtrConstant(1));
11473 SDValue Ops[] = { Chain, In1, In2L, In2H };
11474 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11476 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11477 cast<MemSDNode>(Node)->getMemOperand());
11478 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11479 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11480 Results.push_back(Result.getValue(2));
11483 /// ReplaceNodeResults - Replace a node with an illegal result type
11484 /// with a new node built out of custom code.
11485 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11486 SmallVectorImpl<SDValue>&Results,
11487 SelectionDAG &DAG) const {
11488 DebugLoc dl = N->getDebugLoc();
11489 switch (N->getOpcode()) {
11491 llvm_unreachable("Do not know how to custom type legalize this operation!");
11492 case ISD::SIGN_EXTEND_INREG:
11497 // We don't want to expand or promote these.
11499 case ISD::FP_TO_SINT:
11500 case ISD::FP_TO_UINT: {
11501 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11503 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11506 std::pair<SDValue,SDValue> Vals =
11507 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11508 SDValue FIST = Vals.first, StackSlot = Vals.second;
11509 if (FIST.getNode() != 0) {
11510 EVT VT = N->getValueType(0);
11511 // Return a load from the stack slot.
11512 if (StackSlot.getNode() != 0)
11513 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11514 MachinePointerInfo(),
11515 false, false, false, 0));
11517 Results.push_back(FIST);
11521 case ISD::READCYCLECOUNTER: {
11522 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11523 SDValue TheChain = N->getOperand(0);
11524 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11525 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11527 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11529 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11530 SDValue Ops[] = { eax, edx };
11531 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11532 Results.push_back(edx.getValue(1));
11535 case ISD::ATOMIC_CMP_SWAP: {
11536 EVT T = N->getValueType(0);
11537 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11538 bool Regs64bit = T == MVT::i128;
11539 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11540 SDValue cpInL, cpInH;
11541 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11542 DAG.getConstant(0, HalfT));
11543 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11544 DAG.getConstant(1, HalfT));
11545 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11546 Regs64bit ? X86::RAX : X86::EAX,
11548 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11549 Regs64bit ? X86::RDX : X86::EDX,
11550 cpInH, cpInL.getValue(1));
11551 SDValue swapInL, swapInH;
11552 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11553 DAG.getConstant(0, HalfT));
11554 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11555 DAG.getConstant(1, HalfT));
11556 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11557 Regs64bit ? X86::RBX : X86::EBX,
11558 swapInL, cpInH.getValue(1));
11559 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11560 Regs64bit ? X86::RCX : X86::ECX,
11561 swapInH, swapInL.getValue(1));
11562 SDValue Ops[] = { swapInH.getValue(0),
11564 swapInH.getValue(1) };
11565 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11566 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11567 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11568 X86ISD::LCMPXCHG8_DAG;
11569 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11571 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11572 Regs64bit ? X86::RAX : X86::EAX,
11573 HalfT, Result.getValue(1));
11574 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11575 Regs64bit ? X86::RDX : X86::EDX,
11576 HalfT, cpOutL.getValue(2));
11577 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11578 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11579 Results.push_back(cpOutH.getValue(1));
11582 case ISD::ATOMIC_LOAD_ADD:
11583 case ISD::ATOMIC_LOAD_AND:
11584 case ISD::ATOMIC_LOAD_NAND:
11585 case ISD::ATOMIC_LOAD_OR:
11586 case ISD::ATOMIC_LOAD_SUB:
11587 case ISD::ATOMIC_LOAD_XOR:
11588 case ISD::ATOMIC_SWAP: {
11590 switch (N->getOpcode()) {
11591 default: llvm_unreachable("Unexpected opcode");
11592 case ISD::ATOMIC_LOAD_ADD:
11593 Opc = X86ISD::ATOMADD64_DAG;
11595 case ISD::ATOMIC_LOAD_AND:
11596 Opc = X86ISD::ATOMAND64_DAG;
11598 case ISD::ATOMIC_LOAD_NAND:
11599 Opc = X86ISD::ATOMNAND64_DAG;
11601 case ISD::ATOMIC_LOAD_OR:
11602 Opc = X86ISD::ATOMOR64_DAG;
11604 case ISD::ATOMIC_LOAD_SUB:
11605 Opc = X86ISD::ATOMSUB64_DAG;
11607 case ISD::ATOMIC_LOAD_XOR:
11608 Opc = X86ISD::ATOMXOR64_DAG;
11610 case ISD::ATOMIC_SWAP:
11611 Opc = X86ISD::ATOMSWAP64_DAG;
11614 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11617 case ISD::ATOMIC_LOAD:
11618 ReplaceATOMIC_LOAD(N, Results, DAG);
11622 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11624 default: return NULL;
11625 case X86ISD::BSF: return "X86ISD::BSF";
11626 case X86ISD::BSR: return "X86ISD::BSR";
11627 case X86ISD::SHLD: return "X86ISD::SHLD";
11628 case X86ISD::SHRD: return "X86ISD::SHRD";
11629 case X86ISD::FAND: return "X86ISD::FAND";
11630 case X86ISD::FOR: return "X86ISD::FOR";
11631 case X86ISD::FXOR: return "X86ISD::FXOR";
11632 case X86ISD::FSRL: return "X86ISD::FSRL";
11633 case X86ISD::FILD: return "X86ISD::FILD";
11634 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11635 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11636 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11637 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11638 case X86ISD::FLD: return "X86ISD::FLD";
11639 case X86ISD::FST: return "X86ISD::FST";
11640 case X86ISD::CALL: return "X86ISD::CALL";
11641 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11642 case X86ISD::BT: return "X86ISD::BT";
11643 case X86ISD::CMP: return "X86ISD::CMP";
11644 case X86ISD::COMI: return "X86ISD::COMI";
11645 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11646 case X86ISD::SETCC: return "X86ISD::SETCC";
11647 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11648 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11649 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11650 case X86ISD::CMOV: return "X86ISD::CMOV";
11651 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11652 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11653 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11654 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11655 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11656 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11657 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11658 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11659 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11660 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11661 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11662 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11663 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11664 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11665 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11666 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11667 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11668 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11669 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11670 case X86ISD::HADD: return "X86ISD::HADD";
11671 case X86ISD::HSUB: return "X86ISD::HSUB";
11672 case X86ISD::FHADD: return "X86ISD::FHADD";
11673 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11674 case X86ISD::FMAX: return "X86ISD::FMAX";
11675 case X86ISD::FMIN: return "X86ISD::FMIN";
11676 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11677 case X86ISD::FMINC: return "X86ISD::FMINC";
11678 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11679 case X86ISD::FRCP: return "X86ISD::FRCP";
11680 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11681 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11682 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11683 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11684 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11685 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11686 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11687 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11688 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11689 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11690 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11691 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11692 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11693 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11694 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11695 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11696 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11697 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11698 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11699 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11700 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11701 case X86ISD::VSHL: return "X86ISD::VSHL";
11702 case X86ISD::VSRL: return "X86ISD::VSRL";
11703 case X86ISD::VSRA: return "X86ISD::VSRA";
11704 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11705 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11706 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11707 case X86ISD::CMPP: return "X86ISD::CMPP";
11708 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11709 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11710 case X86ISD::ADD: return "X86ISD::ADD";
11711 case X86ISD::SUB: return "X86ISD::SUB";
11712 case X86ISD::ADC: return "X86ISD::ADC";
11713 case X86ISD::SBB: return "X86ISD::SBB";
11714 case X86ISD::SMUL: return "X86ISD::SMUL";
11715 case X86ISD::UMUL: return "X86ISD::UMUL";
11716 case X86ISD::INC: return "X86ISD::INC";
11717 case X86ISD::DEC: return "X86ISD::DEC";
11718 case X86ISD::OR: return "X86ISD::OR";
11719 case X86ISD::XOR: return "X86ISD::XOR";
11720 case X86ISD::AND: return "X86ISD::AND";
11721 case X86ISD::ANDN: return "X86ISD::ANDN";
11722 case X86ISD::BLSI: return "X86ISD::BLSI";
11723 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11724 case X86ISD::BLSR: return "X86ISD::BLSR";
11725 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11726 case X86ISD::PTEST: return "X86ISD::PTEST";
11727 case X86ISD::TESTP: return "X86ISD::TESTP";
11728 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11729 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11730 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11731 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11732 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11733 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11734 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11735 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11736 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11737 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11738 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11739 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11740 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11741 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11742 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11743 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11744 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11745 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11746 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11747 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11748 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11749 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11750 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11751 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11752 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11753 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11754 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11755 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11756 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11757 case X86ISD::SAHF: return "X86ISD::SAHF";
11758 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11759 case X86ISD::FMADD: return "X86ISD::FMADD";
11760 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11761 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11762 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11763 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11764 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11768 // isLegalAddressingMode - Return true if the addressing mode represented
11769 // by AM is legal for this target, for a load/store of the specified type.
11770 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11772 // X86 supports extremely general addressing modes.
11773 CodeModel::Model M = getTargetMachine().getCodeModel();
11774 Reloc::Model R = getTargetMachine().getRelocationModel();
11776 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11777 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11782 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11784 // If a reference to this global requires an extra load, we can't fold it.
11785 if (isGlobalStubReference(GVFlags))
11788 // If BaseGV requires a register for the PIC base, we cannot also have a
11789 // BaseReg specified.
11790 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11793 // If lower 4G is not available, then we must use rip-relative addressing.
11794 if ((M != CodeModel::Small || R != Reloc::Static) &&
11795 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11799 switch (AM.Scale) {
11805 // These scales always work.
11810 // These scales are formed with basereg+scalereg. Only accept if there is
11815 default: // Other stuff never works.
11823 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11824 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11826 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11827 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11828 if (NumBits1 <= NumBits2)
11833 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11834 return Imm == (int32_t)Imm;
11837 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11838 // Can also use sub to handle negated immediates.
11839 return Imm == (int32_t)Imm;
11842 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11843 if (!VT1.isInteger() || !VT2.isInteger())
11845 unsigned NumBits1 = VT1.getSizeInBits();
11846 unsigned NumBits2 = VT2.getSizeInBits();
11847 if (NumBits1 <= NumBits2)
11852 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11853 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11854 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11857 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11858 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11859 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11862 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11863 // i16 instructions are longer (0x66 prefix) and potentially slower.
11864 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11867 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11868 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11869 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11870 /// are assumed to be legal.
11872 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11874 // Very little shuffling can be done for 64-bit vectors right now.
11875 if (VT.getSizeInBits() == 64)
11878 // FIXME: pshufb, blends, shifts.
11879 return (VT.getVectorNumElements() == 2 ||
11880 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11881 isMOVLMask(M, VT) ||
11882 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11883 isPSHUFDMask(M, VT) ||
11884 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11885 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11886 isPALIGNRMask(M, VT, Subtarget) ||
11887 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11888 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11889 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11890 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11894 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11896 unsigned NumElts = VT.getVectorNumElements();
11897 // FIXME: This collection of masks seems suspect.
11900 if (NumElts == 4 && VT.is128BitVector()) {
11901 return (isMOVLMask(Mask, VT) ||
11902 isCommutedMOVLMask(Mask, VT, true) ||
11903 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11904 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11909 //===----------------------------------------------------------------------===//
11910 // X86 Scheduler Hooks
11911 //===----------------------------------------------------------------------===//
11913 // private utility function
11915 // Get CMPXCHG opcode for the specified data type.
11916 static unsigned getCmpXChgOpcode(EVT VT) {
11917 switch (VT.getSimpleVT().SimpleTy) {
11918 case MVT::i8: return X86::LCMPXCHG8;
11919 case MVT::i16: return X86::LCMPXCHG16;
11920 case MVT::i32: return X86::LCMPXCHG32;
11921 case MVT::i64: return X86::LCMPXCHG64;
11925 llvm_unreachable("Invalid operand size!");
11928 // Get LOAD opcode for the specified data type.
11929 static unsigned getLoadOpcode(EVT VT) {
11930 switch (VT.getSimpleVT().SimpleTy) {
11931 case MVT::i8: return X86::MOV8rm;
11932 case MVT::i16: return X86::MOV16rm;
11933 case MVT::i32: return X86::MOV32rm;
11934 case MVT::i64: return X86::MOV64rm;
11938 llvm_unreachable("Invalid operand size!");
11941 // Get opcode of the non-atomic one from the specified atomic instruction.
11942 static unsigned getNonAtomicOpcode(unsigned Opc) {
11944 case X86::ATOMAND8: return X86::AND8rr;
11945 case X86::ATOMAND16: return X86::AND16rr;
11946 case X86::ATOMAND32: return X86::AND32rr;
11947 case X86::ATOMAND64: return X86::AND64rr;
11948 case X86::ATOMOR8: return X86::OR8rr;
11949 case X86::ATOMOR16: return X86::OR16rr;
11950 case X86::ATOMOR32: return X86::OR32rr;
11951 case X86::ATOMOR64: return X86::OR64rr;
11952 case X86::ATOMXOR8: return X86::XOR8rr;
11953 case X86::ATOMXOR16: return X86::XOR16rr;
11954 case X86::ATOMXOR32: return X86::XOR32rr;
11955 case X86::ATOMXOR64: return X86::XOR64rr;
11957 llvm_unreachable("Unhandled atomic-load-op opcode!");
11960 // Get opcode of the non-atomic one from the specified atomic instruction with
11962 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11963 unsigned &ExtraOpc) {
11965 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
11966 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
11967 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
11968 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
11969 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
11970 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
11971 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
11972 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
11973 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
11974 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
11975 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
11976 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
11977 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
11978 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
11979 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
11980 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
11982 llvm_unreachable("Unhandled atomic-load-op opcode!");
11985 // Get opcode of the non-atomic one from the specified atomic instruction for
11986 // 64-bit data type on 32-bit target.
11987 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
11989 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
11990 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
11991 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
11992 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
11993 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
11994 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
11996 llvm_unreachable("Unhandled atomic-load-op opcode!");
11999 // Get opcode of the non-atomic one from the specified atomic instruction for
12000 // 64-bit data type on 32-bit target with extra opcode.
12001 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12003 unsigned &ExtraOpc) {
12005 case X86::ATOMNAND6432:
12006 ExtraOpc = X86::NOT32r;
12007 HiOpc = X86::AND32rr;
12008 return X86::AND32rr;
12010 llvm_unreachable("Unhandled atomic-load-op opcode!");
12013 // Get pseudo CMOV opcode from the specified data type.
12014 static unsigned getPseudoCMOVOpc(EVT VT) {
12015 switch (VT.getSimpleVT().SimpleTy) {
12016 case MVT::i16: return X86::CMOV_GR16;
12017 case MVT::i32: return X86::CMOV_GR32;
12021 llvm_unreachable("Unknown CMOV opcode!");
12024 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12025 // They will be translated into a spin-loop or compare-exchange loop from
12028 // dst = atomic-fetch-op MI.addr, MI.val
12034 // EAX = LOAD MI.addr
12036 // t1 = OP MI.val, EAX
12037 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12042 MachineBasicBlock *
12043 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12044 MachineBasicBlock *MBB) const {
12045 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12046 DebugLoc DL = MI->getDebugLoc();
12048 MachineFunction *MF = MBB->getParent();
12049 MachineRegisterInfo &MRI = MF->getRegInfo();
12051 const BasicBlock *BB = MBB->getBasicBlock();
12052 MachineFunction::iterator I = MBB;
12055 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12056 "Unexpected number of operands");
12058 assert(MI->hasOneMemOperand() &&
12059 "Expected atomic-load-op to have one memoperand");
12061 // Memory Reference
12062 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12063 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12065 unsigned DstReg, SrcReg;
12066 unsigned MemOpndSlot;
12068 unsigned CurOp = 0;
12070 DstReg = MI->getOperand(CurOp++).getReg();
12071 MemOpndSlot = CurOp;
12072 CurOp += X86::AddrNumOperands;
12073 SrcReg = MI->getOperand(CurOp++).getReg();
12075 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12076 EVT VT = *RC->vt_begin();
12077 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12079 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12080 unsigned LOADOpc = getLoadOpcode(VT);
12082 // For the atomic load-arith operator, we generate
12085 // EAX = LOAD [MI.addr]
12087 // t1 = OP MI.val, EAX
12088 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12092 MachineBasicBlock *thisMBB = MBB;
12093 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12094 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12095 MF->insert(I, mainMBB);
12096 MF->insert(I, sinkMBB);
12098 MachineInstrBuilder MIB;
12100 // Transfer the remainder of BB and its successor edges to sinkMBB.
12101 sinkMBB->splice(sinkMBB->begin(), MBB,
12102 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12103 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12106 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12107 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12108 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12109 MIB.setMemRefs(MMOBegin, MMOEnd);
12111 thisMBB->addSuccessor(mainMBB);
12114 MachineBasicBlock *origMainMBB = mainMBB;
12115 mainMBB->addLiveIn(AccPhyReg);
12117 // Copy AccPhyReg as it is used more than once.
12118 unsigned AccReg = MRI.createVirtualRegister(RC);
12119 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12120 .addReg(AccPhyReg);
12122 unsigned t1 = MRI.createVirtualRegister(RC);
12123 unsigned Opc = MI->getOpcode();
12126 llvm_unreachable("Unhandled atomic-load-op opcode!");
12127 case X86::ATOMAND8:
12128 case X86::ATOMAND16:
12129 case X86::ATOMAND32:
12130 case X86::ATOMAND64:
12132 case X86::ATOMOR16:
12133 case X86::ATOMOR32:
12134 case X86::ATOMOR64:
12135 case X86::ATOMXOR8:
12136 case X86::ATOMXOR16:
12137 case X86::ATOMXOR32:
12138 case X86::ATOMXOR64: {
12139 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12140 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12144 case X86::ATOMNAND8:
12145 case X86::ATOMNAND16:
12146 case X86::ATOMNAND32:
12147 case X86::ATOMNAND64: {
12148 unsigned t2 = MRI.createVirtualRegister(RC);
12150 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12151 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12153 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12156 case X86::ATOMMAX16:
12157 case X86::ATOMMAX32:
12158 case X86::ATOMMAX64:
12159 case X86::ATOMMIN16:
12160 case X86::ATOMMIN32:
12161 case X86::ATOMMIN64:
12162 case X86::ATOMUMAX16:
12163 case X86::ATOMUMAX32:
12164 case X86::ATOMUMAX64:
12165 case X86::ATOMUMIN16:
12166 case X86::ATOMUMIN32:
12167 case X86::ATOMUMIN64: {
12169 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12171 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12175 if (Subtarget->hasCMov()) {
12177 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12181 // Use pseudo select and lower them.
12182 assert((VT == MVT::i16 || VT == MVT::i32) &&
12183 "Invalid atomic-load-op transformation!");
12184 unsigned SelOpc = getPseudoCMOVOpc(VT);
12185 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12186 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12187 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12188 .addReg(SrcReg).addReg(AccReg)
12190 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12196 // Copy AccPhyReg back from virtual register.
12197 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12200 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12201 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12202 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12204 MIB.setMemRefs(MMOBegin, MMOEnd);
12206 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12208 mainMBB->addSuccessor(origMainMBB);
12209 mainMBB->addSuccessor(sinkMBB);
12212 sinkMBB->addLiveIn(AccPhyReg);
12214 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12215 TII->get(TargetOpcode::COPY), DstReg)
12216 .addReg(AccPhyReg);
12218 MI->eraseFromParent();
12222 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12223 // instructions. They will be translated into a spin-loop or compare-exchange
12227 // dst = atomic-fetch-op MI.addr, MI.val
12233 // EAX = LOAD [MI.addr + 0]
12234 // EDX = LOAD [MI.addr + 4]
12236 // EBX = OP MI.val.lo, EAX
12237 // ECX = OP MI.val.hi, EDX
12238 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12243 MachineBasicBlock *
12244 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12245 MachineBasicBlock *MBB) const {
12246 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12247 DebugLoc DL = MI->getDebugLoc();
12249 MachineFunction *MF = MBB->getParent();
12250 MachineRegisterInfo &MRI = MF->getRegInfo();
12252 const BasicBlock *BB = MBB->getBasicBlock();
12253 MachineFunction::iterator I = MBB;
12256 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12257 "Unexpected number of operands");
12259 assert(MI->hasOneMemOperand() &&
12260 "Expected atomic-load-op32 to have one memoperand");
12262 // Memory Reference
12263 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12264 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12266 unsigned DstLoReg, DstHiReg;
12267 unsigned SrcLoReg, SrcHiReg;
12268 unsigned MemOpndSlot;
12270 unsigned CurOp = 0;
12272 DstLoReg = MI->getOperand(CurOp++).getReg();
12273 DstHiReg = MI->getOperand(CurOp++).getReg();
12274 MemOpndSlot = CurOp;
12275 CurOp += X86::AddrNumOperands;
12276 SrcLoReg = MI->getOperand(CurOp++).getReg();
12277 SrcHiReg = MI->getOperand(CurOp++).getReg();
12279 const TargetRegisterClass *RC = &X86::GR32RegClass;
12281 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12282 unsigned LOADOpc = X86::MOV32rm;
12284 // For the atomic load-arith operator, we generate
12287 // EAX = LOAD [MI.addr + 0]
12288 // EDX = LOAD [MI.addr + 4]
12290 // EBX = OP MI.vallo, EAX
12291 // ECX = OP MI.valhi, EDX
12292 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12296 MachineBasicBlock *thisMBB = MBB;
12297 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12298 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12299 MF->insert(I, mainMBB);
12300 MF->insert(I, sinkMBB);
12302 MachineInstrBuilder MIB;
12304 // Transfer the remainder of BB and its successor edges to sinkMBB.
12305 sinkMBB->splice(sinkMBB->begin(), MBB,
12306 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12307 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12311 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12312 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12313 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12314 MIB.setMemRefs(MMOBegin, MMOEnd);
12316 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12317 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12318 if (i == X86::AddrDisp)
12319 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12321 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12323 MIB.setMemRefs(MMOBegin, MMOEnd);
12325 thisMBB->addSuccessor(mainMBB);
12328 MachineBasicBlock *origMainMBB = mainMBB;
12329 mainMBB->addLiveIn(X86::EAX);
12330 mainMBB->addLiveIn(X86::EDX);
12332 // Copy EDX:EAX as they are used more than once.
12333 unsigned LoReg = MRI.createVirtualRegister(RC);
12334 unsigned HiReg = MRI.createVirtualRegister(RC);
12335 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12336 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12338 unsigned t1L = MRI.createVirtualRegister(RC);
12339 unsigned t1H = MRI.createVirtualRegister(RC);
12341 unsigned Opc = MI->getOpcode();
12344 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12345 case X86::ATOMAND6432:
12346 case X86::ATOMOR6432:
12347 case X86::ATOMXOR6432:
12348 case X86::ATOMADD6432:
12349 case X86::ATOMSUB6432: {
12351 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12352 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12353 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12356 case X86::ATOMNAND6432: {
12357 unsigned HiOpc, NOTOpc;
12358 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12359 unsigned t2L = MRI.createVirtualRegister(RC);
12360 unsigned t2H = MRI.createVirtualRegister(RC);
12361 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12362 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12363 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12364 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12367 case X86::ATOMSWAP6432: {
12369 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12370 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12371 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12376 // Copy EDX:EAX back from HiReg:LoReg
12377 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12378 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12379 // Copy ECX:EBX from t1H:t1L
12380 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12381 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12383 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12384 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12385 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12386 MIB.setMemRefs(MMOBegin, MMOEnd);
12388 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12390 mainMBB->addSuccessor(origMainMBB);
12391 mainMBB->addSuccessor(sinkMBB);
12394 sinkMBB->addLiveIn(X86::EAX);
12395 sinkMBB->addLiveIn(X86::EDX);
12397 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12398 TII->get(TargetOpcode::COPY), DstLoReg)
12400 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12401 TII->get(TargetOpcode::COPY), DstHiReg)
12404 MI->eraseFromParent();
12408 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12409 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12410 // in the .td file.
12411 MachineBasicBlock *
12412 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12413 unsigned numArgs, bool memArg) const {
12414 assert(Subtarget->hasSSE42() &&
12415 "Target must have SSE4.2 or AVX features enabled");
12417 DebugLoc dl = MI->getDebugLoc();
12418 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12420 if (!Subtarget->hasAVX()) {
12422 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12424 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12427 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12429 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12432 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12433 for (unsigned i = 0; i < numArgs; ++i) {
12434 MachineOperand &Op = MI->getOperand(i+1);
12435 if (!(Op.isReg() && Op.isImplicit()))
12436 MIB.addOperand(Op);
12438 BuildMI(*BB, MI, dl,
12439 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12440 .addReg(X86::XMM0);
12442 MI->eraseFromParent();
12446 MachineBasicBlock *
12447 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12448 DebugLoc dl = MI->getDebugLoc();
12449 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12451 // Address into RAX/EAX, other two args into ECX, EDX.
12452 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12453 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12454 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12455 for (int i = 0; i < X86::AddrNumOperands; ++i)
12456 MIB.addOperand(MI->getOperand(i));
12458 unsigned ValOps = X86::AddrNumOperands;
12459 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12460 .addReg(MI->getOperand(ValOps).getReg());
12461 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12462 .addReg(MI->getOperand(ValOps+1).getReg());
12464 // The instruction doesn't actually take any operands though.
12465 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12467 MI->eraseFromParent(); // The pseudo is gone now.
12471 MachineBasicBlock *
12472 X86TargetLowering::EmitVAARG64WithCustomInserter(
12474 MachineBasicBlock *MBB) const {
12475 // Emit va_arg instruction on X86-64.
12477 // Operands to this pseudo-instruction:
12478 // 0 ) Output : destination address (reg)
12479 // 1-5) Input : va_list address (addr, i64mem)
12480 // 6 ) ArgSize : Size (in bytes) of vararg type
12481 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12482 // 8 ) Align : Alignment of type
12483 // 9 ) EFLAGS (implicit-def)
12485 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12486 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12488 unsigned DestReg = MI->getOperand(0).getReg();
12489 MachineOperand &Base = MI->getOperand(1);
12490 MachineOperand &Scale = MI->getOperand(2);
12491 MachineOperand &Index = MI->getOperand(3);
12492 MachineOperand &Disp = MI->getOperand(4);
12493 MachineOperand &Segment = MI->getOperand(5);
12494 unsigned ArgSize = MI->getOperand(6).getImm();
12495 unsigned ArgMode = MI->getOperand(7).getImm();
12496 unsigned Align = MI->getOperand(8).getImm();
12498 // Memory Reference
12499 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12500 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12501 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12503 // Machine Information
12504 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12505 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12506 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12507 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12508 DebugLoc DL = MI->getDebugLoc();
12510 // struct va_list {
12513 // i64 overflow_area (address)
12514 // i64 reg_save_area (address)
12516 // sizeof(va_list) = 24
12517 // alignment(va_list) = 8
12519 unsigned TotalNumIntRegs = 6;
12520 unsigned TotalNumXMMRegs = 8;
12521 bool UseGPOffset = (ArgMode == 1);
12522 bool UseFPOffset = (ArgMode == 2);
12523 unsigned MaxOffset = TotalNumIntRegs * 8 +
12524 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12526 /* Align ArgSize to a multiple of 8 */
12527 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12528 bool NeedsAlign = (Align > 8);
12530 MachineBasicBlock *thisMBB = MBB;
12531 MachineBasicBlock *overflowMBB;
12532 MachineBasicBlock *offsetMBB;
12533 MachineBasicBlock *endMBB;
12535 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12536 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12537 unsigned OffsetReg = 0;
12539 if (!UseGPOffset && !UseFPOffset) {
12540 // If we only pull from the overflow region, we don't create a branch.
12541 // We don't need to alter control flow.
12542 OffsetDestReg = 0; // unused
12543 OverflowDestReg = DestReg;
12546 overflowMBB = thisMBB;
12549 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12550 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12551 // If not, pull from overflow_area. (branch to overflowMBB)
12556 // offsetMBB overflowMBB
12561 // Registers for the PHI in endMBB
12562 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12563 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12565 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12566 MachineFunction *MF = MBB->getParent();
12567 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12568 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12569 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12571 MachineFunction::iterator MBBIter = MBB;
12574 // Insert the new basic blocks
12575 MF->insert(MBBIter, offsetMBB);
12576 MF->insert(MBBIter, overflowMBB);
12577 MF->insert(MBBIter, endMBB);
12579 // Transfer the remainder of MBB and its successor edges to endMBB.
12580 endMBB->splice(endMBB->begin(), thisMBB,
12581 llvm::next(MachineBasicBlock::iterator(MI)),
12583 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12585 // Make offsetMBB and overflowMBB successors of thisMBB
12586 thisMBB->addSuccessor(offsetMBB);
12587 thisMBB->addSuccessor(overflowMBB);
12589 // endMBB is a successor of both offsetMBB and overflowMBB
12590 offsetMBB->addSuccessor(endMBB);
12591 overflowMBB->addSuccessor(endMBB);
12593 // Load the offset value into a register
12594 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12595 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12599 .addDisp(Disp, UseFPOffset ? 4 : 0)
12600 .addOperand(Segment)
12601 .setMemRefs(MMOBegin, MMOEnd);
12603 // Check if there is enough room left to pull this argument.
12604 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12606 .addImm(MaxOffset + 8 - ArgSizeA8);
12608 // Branch to "overflowMBB" if offset >= max
12609 // Fall through to "offsetMBB" otherwise
12610 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12611 .addMBB(overflowMBB);
12614 // In offsetMBB, emit code to use the reg_save_area.
12616 assert(OffsetReg != 0);
12618 // Read the reg_save_area address.
12619 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12620 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12625 .addOperand(Segment)
12626 .setMemRefs(MMOBegin, MMOEnd);
12628 // Zero-extend the offset
12629 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12630 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12633 .addImm(X86::sub_32bit);
12635 // Add the offset to the reg_save_area to get the final address.
12636 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12637 .addReg(OffsetReg64)
12638 .addReg(RegSaveReg);
12640 // Compute the offset for the next argument
12641 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12642 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12644 .addImm(UseFPOffset ? 16 : 8);
12646 // Store it back into the va_list.
12647 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12651 .addDisp(Disp, UseFPOffset ? 4 : 0)
12652 .addOperand(Segment)
12653 .addReg(NextOffsetReg)
12654 .setMemRefs(MMOBegin, MMOEnd);
12657 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12662 // Emit code to use overflow area
12665 // Load the overflow_area address into a register.
12666 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12667 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12672 .addOperand(Segment)
12673 .setMemRefs(MMOBegin, MMOEnd);
12675 // If we need to align it, do so. Otherwise, just copy the address
12676 // to OverflowDestReg.
12678 // Align the overflow address
12679 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12680 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12682 // aligned_addr = (addr + (align-1)) & ~(align-1)
12683 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12684 .addReg(OverflowAddrReg)
12687 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12689 .addImm(~(uint64_t)(Align-1));
12691 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12692 .addReg(OverflowAddrReg);
12695 // Compute the next overflow address after this argument.
12696 // (the overflow address should be kept 8-byte aligned)
12697 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12698 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12699 .addReg(OverflowDestReg)
12700 .addImm(ArgSizeA8);
12702 // Store the new overflow address.
12703 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12708 .addOperand(Segment)
12709 .addReg(NextAddrReg)
12710 .setMemRefs(MMOBegin, MMOEnd);
12712 // If we branched, emit the PHI to the front of endMBB.
12714 BuildMI(*endMBB, endMBB->begin(), DL,
12715 TII->get(X86::PHI), DestReg)
12716 .addReg(OffsetDestReg).addMBB(offsetMBB)
12717 .addReg(OverflowDestReg).addMBB(overflowMBB);
12720 // Erase the pseudo instruction
12721 MI->eraseFromParent();
12726 MachineBasicBlock *
12727 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12729 MachineBasicBlock *MBB) const {
12730 // Emit code to save XMM registers to the stack. The ABI says that the
12731 // number of registers to save is given in %al, so it's theoretically
12732 // possible to do an indirect jump trick to avoid saving all of them,
12733 // however this code takes a simpler approach and just executes all
12734 // of the stores if %al is non-zero. It's less code, and it's probably
12735 // easier on the hardware branch predictor, and stores aren't all that
12736 // expensive anyway.
12738 // Create the new basic blocks. One block contains all the XMM stores,
12739 // and one block is the final destination regardless of whether any
12740 // stores were performed.
12741 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12742 MachineFunction *F = MBB->getParent();
12743 MachineFunction::iterator MBBIter = MBB;
12745 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12746 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12747 F->insert(MBBIter, XMMSaveMBB);
12748 F->insert(MBBIter, EndMBB);
12750 // Transfer the remainder of MBB and its successor edges to EndMBB.
12751 EndMBB->splice(EndMBB->begin(), MBB,
12752 llvm::next(MachineBasicBlock::iterator(MI)),
12754 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12756 // The original block will now fall through to the XMM save block.
12757 MBB->addSuccessor(XMMSaveMBB);
12758 // The XMMSaveMBB will fall through to the end block.
12759 XMMSaveMBB->addSuccessor(EndMBB);
12761 // Now add the instructions.
12762 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12763 DebugLoc DL = MI->getDebugLoc();
12765 unsigned CountReg = MI->getOperand(0).getReg();
12766 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12767 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12769 if (!Subtarget->isTargetWin64()) {
12770 // If %al is 0, branch around the XMM save block.
12771 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12772 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12773 MBB->addSuccessor(EndMBB);
12776 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12777 // In the XMM save block, save all the XMM argument registers.
12778 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12779 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12780 MachineMemOperand *MMO =
12781 F->getMachineMemOperand(
12782 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12783 MachineMemOperand::MOStore,
12784 /*Size=*/16, /*Align=*/16);
12785 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12786 .addFrameIndex(RegSaveFrameIndex)
12787 .addImm(/*Scale=*/1)
12788 .addReg(/*IndexReg=*/0)
12789 .addImm(/*Disp=*/Offset)
12790 .addReg(/*Segment=*/0)
12791 .addReg(MI->getOperand(i).getReg())
12792 .addMemOperand(MMO);
12795 MI->eraseFromParent(); // The pseudo instruction is gone now.
12800 // The EFLAGS operand of SelectItr might be missing a kill marker
12801 // because there were multiple uses of EFLAGS, and ISel didn't know
12802 // which to mark. Figure out whether SelectItr should have had a
12803 // kill marker, and set it if it should. Returns the correct kill
12805 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12806 MachineBasicBlock* BB,
12807 const TargetRegisterInfo* TRI) {
12808 // Scan forward through BB for a use/def of EFLAGS.
12809 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12810 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12811 const MachineInstr& mi = *miI;
12812 if (mi.readsRegister(X86::EFLAGS))
12814 if (mi.definesRegister(X86::EFLAGS))
12815 break; // Should have kill-flag - update below.
12818 // If we hit the end of the block, check whether EFLAGS is live into a
12820 if (miI == BB->end()) {
12821 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12822 sEnd = BB->succ_end();
12823 sItr != sEnd; ++sItr) {
12824 MachineBasicBlock* succ = *sItr;
12825 if (succ->isLiveIn(X86::EFLAGS))
12830 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12831 // out. SelectMI should have a kill flag on EFLAGS.
12832 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12836 MachineBasicBlock *
12837 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12838 MachineBasicBlock *BB) const {
12839 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12840 DebugLoc DL = MI->getDebugLoc();
12842 // To "insert" a SELECT_CC instruction, we actually have to insert the
12843 // diamond control-flow pattern. The incoming instruction knows the
12844 // destination vreg to set, the condition code register to branch on, the
12845 // true/false values to select between, and a branch opcode to use.
12846 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12847 MachineFunction::iterator It = BB;
12853 // cmpTY ccX, r1, r2
12855 // fallthrough --> copy0MBB
12856 MachineBasicBlock *thisMBB = BB;
12857 MachineFunction *F = BB->getParent();
12858 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12859 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12860 F->insert(It, copy0MBB);
12861 F->insert(It, sinkMBB);
12863 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12864 // live into the sink and copy blocks.
12865 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12866 if (!MI->killsRegister(X86::EFLAGS) &&
12867 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12868 copy0MBB->addLiveIn(X86::EFLAGS);
12869 sinkMBB->addLiveIn(X86::EFLAGS);
12872 // Transfer the remainder of BB and its successor edges to sinkMBB.
12873 sinkMBB->splice(sinkMBB->begin(), BB,
12874 llvm::next(MachineBasicBlock::iterator(MI)),
12876 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12878 // Add the true and fallthrough blocks as its successors.
12879 BB->addSuccessor(copy0MBB);
12880 BB->addSuccessor(sinkMBB);
12882 // Create the conditional branch instruction.
12884 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12885 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12888 // %FalseValue = ...
12889 // # fallthrough to sinkMBB
12890 copy0MBB->addSuccessor(sinkMBB);
12893 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12895 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12896 TII->get(X86::PHI), MI->getOperand(0).getReg())
12897 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12898 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12900 MI->eraseFromParent(); // The pseudo instruction is gone now.
12904 MachineBasicBlock *
12905 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12906 bool Is64Bit) const {
12907 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12908 DebugLoc DL = MI->getDebugLoc();
12909 MachineFunction *MF = BB->getParent();
12910 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12912 assert(getTargetMachine().Options.EnableSegmentedStacks);
12914 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12915 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12918 // ... [Till the alloca]
12919 // If stacklet is not large enough, jump to mallocMBB
12922 // Allocate by subtracting from RSP
12923 // Jump to continueMBB
12926 // Allocate by call to runtime
12930 // [rest of original BB]
12933 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12934 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12935 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12937 MachineRegisterInfo &MRI = MF->getRegInfo();
12938 const TargetRegisterClass *AddrRegClass =
12939 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12941 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12942 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12943 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12944 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12945 sizeVReg = MI->getOperand(1).getReg(),
12946 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12948 MachineFunction::iterator MBBIter = BB;
12951 MF->insert(MBBIter, bumpMBB);
12952 MF->insert(MBBIter, mallocMBB);
12953 MF->insert(MBBIter, continueMBB);
12955 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12956 (MachineBasicBlock::iterator(MI)), BB->end());
12957 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12959 // Add code to the main basic block to check if the stack limit has been hit,
12960 // and if so, jump to mallocMBB otherwise to bumpMBB.
12961 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12962 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12963 .addReg(tmpSPVReg).addReg(sizeVReg);
12964 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12965 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12966 .addReg(SPLimitVReg);
12967 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12969 // bumpMBB simply decreases the stack pointer, since we know the current
12970 // stacklet has enough space.
12971 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12972 .addReg(SPLimitVReg);
12973 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12974 .addReg(SPLimitVReg);
12975 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12977 // Calls into a routine in libgcc to allocate more space from the heap.
12978 const uint32_t *RegMask =
12979 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12981 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12983 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12984 .addExternalSymbol("__morestack_allocate_stack_space")
12985 .addRegMask(RegMask)
12986 .addReg(X86::RDI, RegState::Implicit)
12987 .addReg(X86::RAX, RegState::ImplicitDefine);
12989 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12991 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12992 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12993 .addExternalSymbol("__morestack_allocate_stack_space")
12994 .addRegMask(RegMask)
12995 .addReg(X86::EAX, RegState::ImplicitDefine);
12999 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13002 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13003 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13004 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13006 // Set up the CFG correctly.
13007 BB->addSuccessor(bumpMBB);
13008 BB->addSuccessor(mallocMBB);
13009 mallocMBB->addSuccessor(continueMBB);
13010 bumpMBB->addSuccessor(continueMBB);
13012 // Take care of the PHI nodes.
13013 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13014 MI->getOperand(0).getReg())
13015 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13016 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13018 // Delete the original pseudo instruction.
13019 MI->eraseFromParent();
13022 return continueMBB;
13025 MachineBasicBlock *
13026 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13027 MachineBasicBlock *BB) const {
13028 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13029 DebugLoc DL = MI->getDebugLoc();
13031 assert(!Subtarget->isTargetEnvMacho());
13033 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13034 // non-trivial part is impdef of ESP.
13036 if (Subtarget->isTargetWin64()) {
13037 if (Subtarget->isTargetCygMing()) {
13038 // ___chkstk(Mingw64):
13039 // Clobbers R10, R11, RAX and EFLAGS.
13041 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13042 .addExternalSymbol("___chkstk")
13043 .addReg(X86::RAX, RegState::Implicit)
13044 .addReg(X86::RSP, RegState::Implicit)
13045 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13046 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13047 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13049 // __chkstk(MSVCRT): does not update stack pointer.
13050 // Clobbers R10, R11 and EFLAGS.
13051 // FIXME: RAX(allocated size) might be reused and not killed.
13052 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13053 .addExternalSymbol("__chkstk")
13054 .addReg(X86::RAX, RegState::Implicit)
13055 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13056 // RAX has the offset to subtracted from RSP.
13057 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13062 const char *StackProbeSymbol =
13063 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13065 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13066 .addExternalSymbol(StackProbeSymbol)
13067 .addReg(X86::EAX, RegState::Implicit)
13068 .addReg(X86::ESP, RegState::Implicit)
13069 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13070 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13071 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13074 MI->eraseFromParent(); // The pseudo instruction is gone now.
13078 MachineBasicBlock *
13079 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13080 MachineBasicBlock *BB) const {
13081 // This is pretty easy. We're taking the value that we received from
13082 // our load from the relocation, sticking it in either RDI (x86-64)
13083 // or EAX and doing an indirect call. The return value will then
13084 // be in the normal return register.
13085 const X86InstrInfo *TII
13086 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13087 DebugLoc DL = MI->getDebugLoc();
13088 MachineFunction *F = BB->getParent();
13090 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13091 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13093 // Get a register mask for the lowered call.
13094 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13095 // proper register mask.
13096 const uint32_t *RegMask =
13097 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13098 if (Subtarget->is64Bit()) {
13099 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13100 TII->get(X86::MOV64rm), X86::RDI)
13102 .addImm(0).addReg(0)
13103 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13104 MI->getOperand(3).getTargetFlags())
13106 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13107 addDirectMem(MIB, X86::RDI);
13108 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13109 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13110 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13111 TII->get(X86::MOV32rm), X86::EAX)
13113 .addImm(0).addReg(0)
13114 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13115 MI->getOperand(3).getTargetFlags())
13117 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13118 addDirectMem(MIB, X86::EAX);
13119 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13121 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13122 TII->get(X86::MOV32rm), X86::EAX)
13123 .addReg(TII->getGlobalBaseReg(F))
13124 .addImm(0).addReg(0)
13125 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13126 MI->getOperand(3).getTargetFlags())
13128 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13129 addDirectMem(MIB, X86::EAX);
13130 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13133 MI->eraseFromParent(); // The pseudo instruction is gone now.
13137 MachineBasicBlock *
13138 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13139 MachineBasicBlock *BB) const {
13140 switch (MI->getOpcode()) {
13141 default: llvm_unreachable("Unexpected instr type to insert");
13142 case X86::TAILJMPd64:
13143 case X86::TAILJMPr64:
13144 case X86::TAILJMPm64:
13145 llvm_unreachable("TAILJMP64 would not be touched here.");
13146 case X86::TCRETURNdi64:
13147 case X86::TCRETURNri64:
13148 case X86::TCRETURNmi64:
13150 case X86::WIN_ALLOCA:
13151 return EmitLoweredWinAlloca(MI, BB);
13152 case X86::SEG_ALLOCA_32:
13153 return EmitLoweredSegAlloca(MI, BB, false);
13154 case X86::SEG_ALLOCA_64:
13155 return EmitLoweredSegAlloca(MI, BB, true);
13156 case X86::TLSCall_32:
13157 case X86::TLSCall_64:
13158 return EmitLoweredTLSCall(MI, BB);
13159 case X86::CMOV_GR8:
13160 case X86::CMOV_FR32:
13161 case X86::CMOV_FR64:
13162 case X86::CMOV_V4F32:
13163 case X86::CMOV_V2F64:
13164 case X86::CMOV_V2I64:
13165 case X86::CMOV_V8F32:
13166 case X86::CMOV_V4F64:
13167 case X86::CMOV_V4I64:
13168 case X86::CMOV_GR16:
13169 case X86::CMOV_GR32:
13170 case X86::CMOV_RFP32:
13171 case X86::CMOV_RFP64:
13172 case X86::CMOV_RFP80:
13173 return EmitLoweredSelect(MI, BB);
13175 case X86::FP32_TO_INT16_IN_MEM:
13176 case X86::FP32_TO_INT32_IN_MEM:
13177 case X86::FP32_TO_INT64_IN_MEM:
13178 case X86::FP64_TO_INT16_IN_MEM:
13179 case X86::FP64_TO_INT32_IN_MEM:
13180 case X86::FP64_TO_INT64_IN_MEM:
13181 case X86::FP80_TO_INT16_IN_MEM:
13182 case X86::FP80_TO_INT32_IN_MEM:
13183 case X86::FP80_TO_INT64_IN_MEM: {
13184 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13185 DebugLoc DL = MI->getDebugLoc();
13187 // Change the floating point control register to use "round towards zero"
13188 // mode when truncating to an integer value.
13189 MachineFunction *F = BB->getParent();
13190 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13191 addFrameReference(BuildMI(*BB, MI, DL,
13192 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13194 // Load the old value of the high byte of the control word...
13196 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13197 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13200 // Set the high part to be round to zero...
13201 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13204 // Reload the modified control word now...
13205 addFrameReference(BuildMI(*BB, MI, DL,
13206 TII->get(X86::FLDCW16m)), CWFrameIdx);
13208 // Restore the memory image of control word to original value
13209 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13212 // Get the X86 opcode to use.
13214 switch (MI->getOpcode()) {
13215 default: llvm_unreachable("illegal opcode!");
13216 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13217 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13218 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13219 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13220 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13221 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13222 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13223 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13224 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13228 MachineOperand &Op = MI->getOperand(0);
13230 AM.BaseType = X86AddressMode::RegBase;
13231 AM.Base.Reg = Op.getReg();
13233 AM.BaseType = X86AddressMode::FrameIndexBase;
13234 AM.Base.FrameIndex = Op.getIndex();
13236 Op = MI->getOperand(1);
13238 AM.Scale = Op.getImm();
13239 Op = MI->getOperand(2);
13241 AM.IndexReg = Op.getImm();
13242 Op = MI->getOperand(3);
13243 if (Op.isGlobal()) {
13244 AM.GV = Op.getGlobal();
13246 AM.Disp = Op.getImm();
13248 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13249 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13251 // Reload the original control word now.
13252 addFrameReference(BuildMI(*BB, MI, DL,
13253 TII->get(X86::FLDCW16m)), CWFrameIdx);
13255 MI->eraseFromParent(); // The pseudo instruction is gone now.
13258 // String/text processing lowering.
13259 case X86::PCMPISTRM128REG:
13260 case X86::VPCMPISTRM128REG:
13261 case X86::PCMPISTRM128MEM:
13262 case X86::VPCMPISTRM128MEM:
13263 case X86::PCMPESTRM128REG:
13264 case X86::VPCMPESTRM128REG:
13265 case X86::PCMPESTRM128MEM:
13266 case X86::VPCMPESTRM128MEM: {
13269 switch (MI->getOpcode()) {
13270 default: llvm_unreachable("illegal opcode!");
13271 case X86::PCMPISTRM128REG:
13272 case X86::VPCMPISTRM128REG:
13273 NumArgs = 3; MemArg = false; break;
13274 case X86::PCMPISTRM128MEM:
13275 case X86::VPCMPISTRM128MEM:
13276 NumArgs = 3; MemArg = true; break;
13277 case X86::PCMPESTRM128REG:
13278 case X86::VPCMPESTRM128REG:
13279 NumArgs = 5; MemArg = false; break;
13280 case X86::PCMPESTRM128MEM:
13281 case X86::VPCMPESTRM128MEM:
13282 NumArgs = 5; MemArg = true; break;
13284 return EmitPCMP(MI, BB, NumArgs, MemArg);
13287 // Thread synchronization.
13289 return EmitMonitor(MI, BB);
13291 // Atomic Lowering.
13292 case X86::ATOMAND8:
13293 case X86::ATOMAND16:
13294 case X86::ATOMAND32:
13295 case X86::ATOMAND64:
13298 case X86::ATOMOR16:
13299 case X86::ATOMOR32:
13300 case X86::ATOMOR64:
13302 case X86::ATOMXOR16:
13303 case X86::ATOMXOR8:
13304 case X86::ATOMXOR32:
13305 case X86::ATOMXOR64:
13307 case X86::ATOMNAND8:
13308 case X86::ATOMNAND16:
13309 case X86::ATOMNAND32:
13310 case X86::ATOMNAND64:
13312 case X86::ATOMMAX16:
13313 case X86::ATOMMAX32:
13314 case X86::ATOMMAX64:
13316 case X86::ATOMMIN16:
13317 case X86::ATOMMIN32:
13318 case X86::ATOMMIN64:
13320 case X86::ATOMUMAX16:
13321 case X86::ATOMUMAX32:
13322 case X86::ATOMUMAX64:
13324 case X86::ATOMUMIN16:
13325 case X86::ATOMUMIN32:
13326 case X86::ATOMUMIN64:
13327 return EmitAtomicLoadArith(MI, BB);
13329 // This group does 64-bit operations on a 32-bit host.
13330 case X86::ATOMAND6432:
13331 case X86::ATOMOR6432:
13332 case X86::ATOMXOR6432:
13333 case X86::ATOMNAND6432:
13334 case X86::ATOMADD6432:
13335 case X86::ATOMSUB6432:
13336 case X86::ATOMSWAP6432:
13337 return EmitAtomicLoadArith6432(MI, BB);
13339 case X86::VASTART_SAVE_XMM_REGS:
13340 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13342 case X86::VAARG_64:
13343 return EmitVAARG64WithCustomInserter(MI, BB);
13347 //===----------------------------------------------------------------------===//
13348 // X86 Optimization Hooks
13349 //===----------------------------------------------------------------------===//
13351 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13354 const SelectionDAG &DAG,
13355 unsigned Depth) const {
13356 unsigned BitWidth = KnownZero.getBitWidth();
13357 unsigned Opc = Op.getOpcode();
13358 assert((Opc >= ISD::BUILTIN_OP_END ||
13359 Opc == ISD::INTRINSIC_WO_CHAIN ||
13360 Opc == ISD::INTRINSIC_W_CHAIN ||
13361 Opc == ISD::INTRINSIC_VOID) &&
13362 "Should use MaskedValueIsZero if you don't know whether Op"
13363 " is a target node!");
13365 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13379 // These nodes' second result is a boolean.
13380 if (Op.getResNo() == 0)
13383 case X86ISD::SETCC:
13384 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13386 case ISD::INTRINSIC_WO_CHAIN: {
13387 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13388 unsigned NumLoBits = 0;
13391 case Intrinsic::x86_sse_movmsk_ps:
13392 case Intrinsic::x86_avx_movmsk_ps_256:
13393 case Intrinsic::x86_sse2_movmsk_pd:
13394 case Intrinsic::x86_avx_movmsk_pd_256:
13395 case Intrinsic::x86_mmx_pmovmskb:
13396 case Intrinsic::x86_sse2_pmovmskb_128:
13397 case Intrinsic::x86_avx2_pmovmskb: {
13398 // High bits of movmskp{s|d}, pmovmskb are known zero.
13400 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13401 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13402 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13403 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13404 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13405 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13406 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13407 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13409 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13418 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13419 unsigned Depth) const {
13420 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13421 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13422 return Op.getValueType().getScalarType().getSizeInBits();
13428 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13429 /// node is a GlobalAddress + offset.
13430 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13431 const GlobalValue* &GA,
13432 int64_t &Offset) const {
13433 if (N->getOpcode() == X86ISD::Wrapper) {
13434 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13435 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13436 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13440 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13443 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13444 /// same as extracting the high 128-bit part of 256-bit vector and then
13445 /// inserting the result into the low part of a new 256-bit vector
13446 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13447 EVT VT = SVOp->getValueType(0);
13448 unsigned NumElems = VT.getVectorNumElements();
13450 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13451 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13452 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13453 SVOp->getMaskElt(j) >= 0)
13459 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13460 /// same as extracting the low 128-bit part of 256-bit vector and then
13461 /// inserting the result into the high part of a new 256-bit vector
13462 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13463 EVT VT = SVOp->getValueType(0);
13464 unsigned NumElems = VT.getVectorNumElements();
13466 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13467 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13468 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13469 SVOp->getMaskElt(j) >= 0)
13475 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13476 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13477 TargetLowering::DAGCombinerInfo &DCI,
13478 const X86Subtarget* Subtarget) {
13479 DebugLoc dl = N->getDebugLoc();
13480 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13481 SDValue V1 = SVOp->getOperand(0);
13482 SDValue V2 = SVOp->getOperand(1);
13483 EVT VT = SVOp->getValueType(0);
13484 unsigned NumElems = VT.getVectorNumElements();
13486 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13487 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13491 // V UNDEF BUILD_VECTOR UNDEF
13493 // CONCAT_VECTOR CONCAT_VECTOR
13496 // RESULT: V + zero extended
13498 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13499 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13500 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13503 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13506 // To match the shuffle mask, the first half of the mask should
13507 // be exactly the first vector, and all the rest a splat with the
13508 // first element of the second one.
13509 for (unsigned i = 0; i != NumElems/2; ++i)
13510 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13511 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13514 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13515 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13516 if (Ld->hasNUsesOfValue(1, 0)) {
13517 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13518 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13520 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13522 Ld->getPointerInfo(),
13523 Ld->getAlignment(),
13524 false/*isVolatile*/, true/*ReadMem*/,
13525 false/*WriteMem*/);
13526 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13530 // Emit a zeroed vector and insert the desired subvector on its
13532 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13533 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13534 return DCI.CombineTo(N, InsV);
13537 //===--------------------------------------------------------------------===//
13538 // Combine some shuffles into subvector extracts and inserts:
13541 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13542 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13543 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13544 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13545 return DCI.CombineTo(N, InsV);
13548 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13549 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13550 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13551 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13552 return DCI.CombineTo(N, InsV);
13558 /// PerformShuffleCombine - Performs several different shuffle combines.
13559 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13560 TargetLowering::DAGCombinerInfo &DCI,
13561 const X86Subtarget *Subtarget) {
13562 DebugLoc dl = N->getDebugLoc();
13563 EVT VT = N->getValueType(0);
13565 // Don't create instructions with illegal types after legalize types has run.
13566 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13567 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13570 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13571 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13572 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13573 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13575 // Only handle 128 wide vector from here on.
13576 if (!VT.is128BitVector())
13579 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13580 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13581 // consecutive, non-overlapping, and in the right order.
13582 SmallVector<SDValue, 16> Elts;
13583 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13584 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13586 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13590 /// PerformTruncateCombine - Converts truncate operation to
13591 /// a sequence of vector shuffle operations.
13592 /// It is possible when we truncate 256-bit vector to 128-bit vector
13593 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13594 TargetLowering::DAGCombinerInfo &DCI,
13595 const X86Subtarget *Subtarget) {
13596 if (!DCI.isBeforeLegalizeOps())
13599 if (!Subtarget->hasAVX())
13602 EVT VT = N->getValueType(0);
13603 SDValue Op = N->getOperand(0);
13604 EVT OpVT = Op.getValueType();
13605 DebugLoc dl = N->getDebugLoc();
13607 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13609 if (Subtarget->hasAVX2()) {
13610 // AVX2: v4i64 -> v4i32
13613 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13615 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13616 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13619 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13620 DAG.getIntPtrConstant(0));
13623 // AVX: v4i64 -> v4i32
13624 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13625 DAG.getIntPtrConstant(0));
13627 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13628 DAG.getIntPtrConstant(2));
13630 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13631 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13634 static const int ShufMask1[] = {0, 2, 0, 0};
13636 SDValue Undef = DAG.getUNDEF(VT);
13637 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13638 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13641 static const int ShufMask2[] = {0, 1, 4, 5};
13643 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13646 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13648 if (Subtarget->hasAVX2()) {
13649 // AVX2: v8i32 -> v8i16
13651 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13654 SmallVector<SDValue,32> pshufbMask;
13655 for (unsigned i = 0; i < 2; ++i) {
13656 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13657 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13658 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13659 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13660 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13661 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13662 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13663 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13664 for (unsigned j = 0; j < 8; ++j)
13665 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13667 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13668 &pshufbMask[0], 32);
13669 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13671 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13673 static const int ShufMask[] = {0, 2, -1, -1};
13674 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13677 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13678 DAG.getIntPtrConstant(0));
13680 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13683 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13684 DAG.getIntPtrConstant(0));
13686 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13687 DAG.getIntPtrConstant(4));
13689 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13690 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13693 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13694 -1, -1, -1, -1, -1, -1, -1, -1};
13696 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13697 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13698 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13700 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13701 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13704 static const int ShufMask2[] = {0, 1, 4, 5};
13706 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13707 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13713 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13714 /// specific shuffle of a load can be folded into a single element load.
13715 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13716 /// shuffles have been customed lowered so we need to handle those here.
13717 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13718 TargetLowering::DAGCombinerInfo &DCI) {
13719 if (DCI.isBeforeLegalizeOps())
13722 SDValue InVec = N->getOperand(0);
13723 SDValue EltNo = N->getOperand(1);
13725 if (!isa<ConstantSDNode>(EltNo))
13728 EVT VT = InVec.getValueType();
13730 bool HasShuffleIntoBitcast = false;
13731 if (InVec.getOpcode() == ISD::BITCAST) {
13732 // Don't duplicate a load with other uses.
13733 if (!InVec.hasOneUse())
13735 EVT BCVT = InVec.getOperand(0).getValueType();
13736 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13738 InVec = InVec.getOperand(0);
13739 HasShuffleIntoBitcast = true;
13742 if (!isTargetShuffle(InVec.getOpcode()))
13745 // Don't duplicate a load with other uses.
13746 if (!InVec.hasOneUse())
13749 SmallVector<int, 16> ShuffleMask;
13751 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13755 // Select the input vector, guarding against out of range extract vector.
13756 unsigned NumElems = VT.getVectorNumElements();
13757 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13758 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13759 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13760 : InVec.getOperand(1);
13762 // If inputs to shuffle are the same for both ops, then allow 2 uses
13763 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13765 if (LdNode.getOpcode() == ISD::BITCAST) {
13766 // Don't duplicate a load with other uses.
13767 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13770 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13771 LdNode = LdNode.getOperand(0);
13774 if (!ISD::isNormalLoad(LdNode.getNode()))
13777 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13779 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13782 if (HasShuffleIntoBitcast) {
13783 // If there's a bitcast before the shuffle, check if the load type and
13784 // alignment is valid.
13785 unsigned Align = LN0->getAlignment();
13786 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13787 unsigned NewAlign = TLI.getTargetData()->
13788 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13790 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13794 // All checks match so transform back to vector_shuffle so that DAG combiner
13795 // can finish the job
13796 DebugLoc dl = N->getDebugLoc();
13798 // Create shuffle node taking into account the case that its a unary shuffle
13799 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13800 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13801 InVec.getOperand(0), Shuffle,
13803 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13804 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13808 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13809 /// generation and convert it from being a bunch of shuffles and extracts
13810 /// to a simple store and scalar loads to extract the elements.
13811 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13812 TargetLowering::DAGCombinerInfo &DCI) {
13813 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13814 if (NewOp.getNode())
13817 SDValue InputVector = N->getOperand(0);
13819 // Only operate on vectors of 4 elements, where the alternative shuffling
13820 // gets to be more expensive.
13821 if (InputVector.getValueType() != MVT::v4i32)
13824 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13825 // single use which is a sign-extend or zero-extend, and all elements are
13827 SmallVector<SDNode *, 4> Uses;
13828 unsigned ExtractedElements = 0;
13829 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13830 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13831 if (UI.getUse().getResNo() != InputVector.getResNo())
13834 SDNode *Extract = *UI;
13835 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13838 if (Extract->getValueType(0) != MVT::i32)
13840 if (!Extract->hasOneUse())
13842 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13843 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13845 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13848 // Record which element was extracted.
13849 ExtractedElements |=
13850 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13852 Uses.push_back(Extract);
13855 // If not all the elements were used, this may not be worthwhile.
13856 if (ExtractedElements != 15)
13859 // Ok, we've now decided to do the transformation.
13860 DebugLoc dl = InputVector.getDebugLoc();
13862 // Store the value to a temporary stack slot.
13863 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13864 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13865 MachinePointerInfo(), false, false, 0);
13867 // Replace each use (extract) with a load of the appropriate element.
13868 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13869 UE = Uses.end(); UI != UE; ++UI) {
13870 SDNode *Extract = *UI;
13872 // cOMpute the element's address.
13873 SDValue Idx = Extract->getOperand(1);
13875 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13876 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13878 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13880 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13881 StackPtr, OffsetVal);
13883 // Load the scalar.
13884 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13885 ScalarAddr, MachinePointerInfo(),
13886 false, false, false, 0);
13888 // Replace the exact with the load.
13889 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13892 // The replacement was made in place; don't return anything.
13896 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13898 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13899 TargetLowering::DAGCombinerInfo &DCI,
13900 const X86Subtarget *Subtarget) {
13901 DebugLoc DL = N->getDebugLoc();
13902 SDValue Cond = N->getOperand(0);
13903 // Get the LHS/RHS of the select.
13904 SDValue LHS = N->getOperand(1);
13905 SDValue RHS = N->getOperand(2);
13906 EVT VT = LHS.getValueType();
13908 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13909 // instructions match the semantics of the common C idiom x<y?x:y but not
13910 // x<=y?x:y, because of how they handle negative zero (which can be
13911 // ignored in unsafe-math mode).
13912 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13913 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13914 (Subtarget->hasSSE2() ||
13915 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13916 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13918 unsigned Opcode = 0;
13919 // Check for x CC y ? x : y.
13920 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13921 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13925 // Converting this to a min would handle NaNs incorrectly, and swapping
13926 // the operands would cause it to handle comparisons between positive
13927 // and negative zero incorrectly.
13928 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13929 if (!DAG.getTarget().Options.UnsafeFPMath &&
13930 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13932 std::swap(LHS, RHS);
13934 Opcode = X86ISD::FMIN;
13937 // Converting this to a min would handle comparisons between positive
13938 // and negative zero incorrectly.
13939 if (!DAG.getTarget().Options.UnsafeFPMath &&
13940 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13942 Opcode = X86ISD::FMIN;
13945 // Converting this to a min would handle both negative zeros and NaNs
13946 // incorrectly, but we can swap the operands to fix both.
13947 std::swap(LHS, RHS);
13951 Opcode = X86ISD::FMIN;
13955 // Converting this to a max would handle comparisons between positive
13956 // and negative zero incorrectly.
13957 if (!DAG.getTarget().Options.UnsafeFPMath &&
13958 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13960 Opcode = X86ISD::FMAX;
13963 // Converting this to a max would handle NaNs incorrectly, and swapping
13964 // the operands would cause it to handle comparisons between positive
13965 // and negative zero incorrectly.
13966 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13967 if (!DAG.getTarget().Options.UnsafeFPMath &&
13968 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13970 std::swap(LHS, RHS);
13972 Opcode = X86ISD::FMAX;
13975 // Converting this to a max would handle both negative zeros and NaNs
13976 // incorrectly, but we can swap the operands to fix both.
13977 std::swap(LHS, RHS);
13981 Opcode = X86ISD::FMAX;
13984 // Check for x CC y ? y : x -- a min/max with reversed arms.
13985 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13986 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13990 // Converting this to a min would handle comparisons between positive
13991 // and negative zero incorrectly, and swapping the operands would
13992 // cause it to handle NaNs incorrectly.
13993 if (!DAG.getTarget().Options.UnsafeFPMath &&
13994 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13995 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13997 std::swap(LHS, RHS);
13999 Opcode = X86ISD::FMIN;
14002 // Converting this to a min would handle NaNs incorrectly.
14003 if (!DAG.getTarget().Options.UnsafeFPMath &&
14004 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14006 Opcode = X86ISD::FMIN;
14009 // Converting this to a min would handle both negative zeros and NaNs
14010 // incorrectly, but we can swap the operands to fix both.
14011 std::swap(LHS, RHS);
14015 Opcode = X86ISD::FMIN;
14019 // Converting this to a max would handle NaNs incorrectly.
14020 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14022 Opcode = X86ISD::FMAX;
14025 // Converting this to a max would handle comparisons between positive
14026 // and negative zero incorrectly, and swapping the operands would
14027 // cause it to handle NaNs incorrectly.
14028 if (!DAG.getTarget().Options.UnsafeFPMath &&
14029 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14030 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14032 std::swap(LHS, RHS);
14034 Opcode = X86ISD::FMAX;
14037 // Converting this to a max would handle both negative zeros and NaNs
14038 // incorrectly, but we can swap the operands to fix both.
14039 std::swap(LHS, RHS);
14043 Opcode = X86ISD::FMAX;
14049 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14052 // If this is a select between two integer constants, try to do some
14054 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14055 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14056 // Don't do this for crazy integer types.
14057 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14058 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14059 // so that TrueC (the true value) is larger than FalseC.
14060 bool NeedsCondInvert = false;
14062 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14063 // Efficiently invertible.
14064 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14065 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14066 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14067 NeedsCondInvert = true;
14068 std::swap(TrueC, FalseC);
14071 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14072 if (FalseC->getAPIntValue() == 0 &&
14073 TrueC->getAPIntValue().isPowerOf2()) {
14074 if (NeedsCondInvert) // Invert the condition if needed.
14075 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14076 DAG.getConstant(1, Cond.getValueType()));
14078 // Zero extend the condition if needed.
14079 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14081 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14082 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14083 DAG.getConstant(ShAmt, MVT::i8));
14086 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14087 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14088 if (NeedsCondInvert) // Invert the condition if needed.
14089 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14090 DAG.getConstant(1, Cond.getValueType()));
14092 // Zero extend the condition if needed.
14093 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14094 FalseC->getValueType(0), Cond);
14095 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14096 SDValue(FalseC, 0));
14099 // Optimize cases that will turn into an LEA instruction. This requires
14100 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14101 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14102 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14103 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14105 bool isFastMultiplier = false;
14107 switch ((unsigned char)Diff) {
14109 case 1: // result = add base, cond
14110 case 2: // result = lea base( , cond*2)
14111 case 3: // result = lea base(cond, cond*2)
14112 case 4: // result = lea base( , cond*4)
14113 case 5: // result = lea base(cond, cond*4)
14114 case 8: // result = lea base( , cond*8)
14115 case 9: // result = lea base(cond, cond*8)
14116 isFastMultiplier = true;
14121 if (isFastMultiplier) {
14122 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14123 if (NeedsCondInvert) // Invert the condition if needed.
14124 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14125 DAG.getConstant(1, Cond.getValueType()));
14127 // Zero extend the condition if needed.
14128 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14130 // Scale the condition by the difference.
14132 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14133 DAG.getConstant(Diff, Cond.getValueType()));
14135 // Add the base if non-zero.
14136 if (FalseC->getAPIntValue() != 0)
14137 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14138 SDValue(FalseC, 0));
14145 // Canonicalize max and min:
14146 // (x > y) ? x : y -> (x >= y) ? x : y
14147 // (x < y) ? x : y -> (x <= y) ? x : y
14148 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14149 // the need for an extra compare
14150 // against zero. e.g.
14151 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14153 // testl %edi, %edi
14155 // cmovgl %edi, %eax
14159 // cmovsl %eax, %edi
14160 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14161 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14162 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14163 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14168 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14169 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14170 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14171 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14176 // If we know that this node is legal then we know that it is going to be
14177 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14178 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14179 // to simplify previous instructions.
14180 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14181 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14182 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14183 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14185 // Don't optimize vector selects that map to mask-registers.
14189 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14190 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14192 APInt KnownZero, KnownOne;
14193 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14194 DCI.isBeforeLegalizeOps());
14195 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14196 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14197 DCI.CommitTargetLoweringOpt(TLO);
14203 // Check whether a boolean test is testing a boolean value generated by
14204 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14207 // Simplify the following patterns:
14208 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14209 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14210 // to (Op EFLAGS Cond)
14212 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14213 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14214 // to (Op EFLAGS !Cond)
14216 // where Op could be BRCOND or CMOV.
14218 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14219 // Quit if not CMP and SUB with its value result used.
14220 if (Cmp.getOpcode() != X86ISD::CMP &&
14221 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14224 // Quit if not used as a boolean value.
14225 if (CC != X86::COND_E && CC != X86::COND_NE)
14228 // Check CMP operands. One of them should be 0 or 1 and the other should be
14229 // an SetCC or extended from it.
14230 SDValue Op1 = Cmp.getOperand(0);
14231 SDValue Op2 = Cmp.getOperand(1);
14234 const ConstantSDNode* C = 0;
14235 bool needOppositeCond = (CC == X86::COND_E);
14237 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14239 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14241 else // Quit if all operands are not constants.
14244 if (C->getZExtValue() == 1)
14245 needOppositeCond = !needOppositeCond;
14246 else if (C->getZExtValue() != 0)
14247 // Quit if the constant is neither 0 or 1.
14250 // Skip 'zext' node.
14251 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14252 SetCC = SetCC.getOperand(0);
14254 switch (SetCC.getOpcode()) {
14255 case X86ISD::SETCC:
14256 // Set the condition code or opposite one if necessary.
14257 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14258 if (needOppositeCond)
14259 CC = X86::GetOppositeBranchCondition(CC);
14260 return SetCC.getOperand(1);
14261 case X86ISD::CMOV: {
14262 // Check whether false/true value has canonical one, i.e. 0 or 1.
14263 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14264 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14265 // Quit if true value is not a constant.
14268 // Quit if false value is not a constant.
14270 // A special case for rdrand, where 0 is set if false cond is found.
14271 SDValue Op = SetCC.getOperand(0);
14272 if (Op.getOpcode() != X86ISD::RDRAND)
14275 // Quit if false value is not the constant 0 or 1.
14276 bool FValIsFalse = true;
14277 if (FVal && FVal->getZExtValue() != 0) {
14278 if (FVal->getZExtValue() != 1)
14280 // If FVal is 1, opposite cond is needed.
14281 needOppositeCond = !needOppositeCond;
14282 FValIsFalse = false;
14284 // Quit if TVal is not the constant opposite of FVal.
14285 if (FValIsFalse && TVal->getZExtValue() != 1)
14287 if (!FValIsFalse && TVal->getZExtValue() != 0)
14289 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14290 if (needOppositeCond)
14291 CC = X86::GetOppositeBranchCondition(CC);
14292 return SetCC.getOperand(3);
14299 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14300 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14301 TargetLowering::DAGCombinerInfo &DCI,
14302 const X86Subtarget *Subtarget) {
14303 DebugLoc DL = N->getDebugLoc();
14305 // If the flag operand isn't dead, don't touch this CMOV.
14306 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14309 SDValue FalseOp = N->getOperand(0);
14310 SDValue TrueOp = N->getOperand(1);
14311 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14312 SDValue Cond = N->getOperand(3);
14314 if (CC == X86::COND_E || CC == X86::COND_NE) {
14315 switch (Cond.getOpcode()) {
14319 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14320 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14321 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14327 Flags = checkBoolTestSetCCCombine(Cond, CC);
14328 if (Flags.getNode() &&
14329 // Extra check as FCMOV only supports a subset of X86 cond.
14330 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14331 SDValue Ops[] = { FalseOp, TrueOp,
14332 DAG.getConstant(CC, MVT::i8), Flags };
14333 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14334 Ops, array_lengthof(Ops));
14337 // If this is a select between two integer constants, try to do some
14338 // optimizations. Note that the operands are ordered the opposite of SELECT
14340 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14341 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14342 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14343 // larger than FalseC (the false value).
14344 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14345 CC = X86::GetOppositeBranchCondition(CC);
14346 std::swap(TrueC, FalseC);
14349 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14350 // This is efficient for any integer data type (including i8/i16) and
14352 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14353 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14354 DAG.getConstant(CC, MVT::i8), Cond);
14356 // Zero extend the condition if needed.
14357 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14359 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14360 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14361 DAG.getConstant(ShAmt, MVT::i8));
14362 if (N->getNumValues() == 2) // Dead flag value?
14363 return DCI.CombineTo(N, Cond, SDValue());
14367 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14368 // for any integer data type, including i8/i16.
14369 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14370 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14371 DAG.getConstant(CC, MVT::i8), Cond);
14373 // Zero extend the condition if needed.
14374 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14375 FalseC->getValueType(0), Cond);
14376 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14377 SDValue(FalseC, 0));
14379 if (N->getNumValues() == 2) // Dead flag value?
14380 return DCI.CombineTo(N, Cond, SDValue());
14384 // Optimize cases that will turn into an LEA instruction. This requires
14385 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14386 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14387 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14388 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14390 bool isFastMultiplier = false;
14392 switch ((unsigned char)Diff) {
14394 case 1: // result = add base, cond
14395 case 2: // result = lea base( , cond*2)
14396 case 3: // result = lea base(cond, cond*2)
14397 case 4: // result = lea base( , cond*4)
14398 case 5: // result = lea base(cond, cond*4)
14399 case 8: // result = lea base( , cond*8)
14400 case 9: // result = lea base(cond, cond*8)
14401 isFastMultiplier = true;
14406 if (isFastMultiplier) {
14407 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14408 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14409 DAG.getConstant(CC, MVT::i8), Cond);
14410 // Zero extend the condition if needed.
14411 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14413 // Scale the condition by the difference.
14415 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14416 DAG.getConstant(Diff, Cond.getValueType()));
14418 // Add the base if non-zero.
14419 if (FalseC->getAPIntValue() != 0)
14420 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14421 SDValue(FalseC, 0));
14422 if (N->getNumValues() == 2) // Dead flag value?
14423 return DCI.CombineTo(N, Cond, SDValue());
14433 /// PerformMulCombine - Optimize a single multiply with constant into two
14434 /// in order to implement it with two cheaper instructions, e.g.
14435 /// LEA + SHL, LEA + LEA.
14436 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14437 TargetLowering::DAGCombinerInfo &DCI) {
14438 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14441 EVT VT = N->getValueType(0);
14442 if (VT != MVT::i64)
14445 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14448 uint64_t MulAmt = C->getZExtValue();
14449 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14452 uint64_t MulAmt1 = 0;
14453 uint64_t MulAmt2 = 0;
14454 if ((MulAmt % 9) == 0) {
14456 MulAmt2 = MulAmt / 9;
14457 } else if ((MulAmt % 5) == 0) {
14459 MulAmt2 = MulAmt / 5;
14460 } else if ((MulAmt % 3) == 0) {
14462 MulAmt2 = MulAmt / 3;
14465 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14466 DebugLoc DL = N->getDebugLoc();
14468 if (isPowerOf2_64(MulAmt2) &&
14469 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14470 // If second multiplifer is pow2, issue it first. We want the multiply by
14471 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14473 std::swap(MulAmt1, MulAmt2);
14476 if (isPowerOf2_64(MulAmt1))
14477 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14478 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14480 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14481 DAG.getConstant(MulAmt1, VT));
14483 if (isPowerOf2_64(MulAmt2))
14484 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14485 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14487 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14488 DAG.getConstant(MulAmt2, VT));
14490 // Do not add new nodes to DAG combiner worklist.
14491 DCI.CombineTo(N, NewMul, false);
14496 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14497 SDValue N0 = N->getOperand(0);
14498 SDValue N1 = N->getOperand(1);
14499 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14500 EVT VT = N0.getValueType();
14502 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14503 // since the result of setcc_c is all zero's or all ones.
14504 if (VT.isInteger() && !VT.isVector() &&
14505 N1C && N0.getOpcode() == ISD::AND &&
14506 N0.getOperand(1).getOpcode() == ISD::Constant) {
14507 SDValue N00 = N0.getOperand(0);
14508 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14509 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14510 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14511 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14512 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14513 APInt ShAmt = N1C->getAPIntValue();
14514 Mask = Mask.shl(ShAmt);
14516 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14517 N00, DAG.getConstant(Mask, VT));
14522 // Hardware support for vector shifts is sparse which makes us scalarize the
14523 // vector operations in many cases. Also, on sandybridge ADD is faster than
14525 // (shl V, 1) -> add V,V
14526 if (isSplatVector(N1.getNode())) {
14527 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14528 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14529 // We shift all of the values by one. In many cases we do not have
14530 // hardware support for this operation. This is better expressed as an ADD
14532 if (N1C && (1 == N1C->getZExtValue())) {
14533 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14540 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14542 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14543 TargetLowering::DAGCombinerInfo &DCI,
14544 const X86Subtarget *Subtarget) {
14545 EVT VT = N->getValueType(0);
14546 if (N->getOpcode() == ISD::SHL) {
14547 SDValue V = PerformSHLCombine(N, DAG);
14548 if (V.getNode()) return V;
14551 // On X86 with SSE2 support, we can transform this to a vector shift if
14552 // all elements are shifted by the same amount. We can't do this in legalize
14553 // because the a constant vector is typically transformed to a constant pool
14554 // so we have no knowledge of the shift amount.
14555 if (!Subtarget->hasSSE2())
14558 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14559 (!Subtarget->hasAVX2() ||
14560 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14563 SDValue ShAmtOp = N->getOperand(1);
14564 EVT EltVT = VT.getVectorElementType();
14565 DebugLoc DL = N->getDebugLoc();
14566 SDValue BaseShAmt = SDValue();
14567 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14568 unsigned NumElts = VT.getVectorNumElements();
14570 for (; i != NumElts; ++i) {
14571 SDValue Arg = ShAmtOp.getOperand(i);
14572 if (Arg.getOpcode() == ISD::UNDEF) continue;
14576 // Handle the case where the build_vector is all undef
14577 // FIXME: Should DAG allow this?
14581 for (; i != NumElts; ++i) {
14582 SDValue Arg = ShAmtOp.getOperand(i);
14583 if (Arg.getOpcode() == ISD::UNDEF) continue;
14584 if (Arg != BaseShAmt) {
14588 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14589 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14590 SDValue InVec = ShAmtOp.getOperand(0);
14591 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14592 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14594 for (; i != NumElts; ++i) {
14595 SDValue Arg = InVec.getOperand(i);
14596 if (Arg.getOpcode() == ISD::UNDEF) continue;
14600 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14601 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14602 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14603 if (C->getZExtValue() == SplatIdx)
14604 BaseShAmt = InVec.getOperand(1);
14607 if (BaseShAmt.getNode() == 0) {
14608 // Don't create instructions with illegal types after legalize
14610 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14611 !DCI.isBeforeLegalize())
14614 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14615 DAG.getIntPtrConstant(0));
14620 // The shift amount is an i32.
14621 if (EltVT.bitsGT(MVT::i32))
14622 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14623 else if (EltVT.bitsLT(MVT::i32))
14624 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14626 // The shift amount is identical so we can do a vector shift.
14627 SDValue ValOp = N->getOperand(0);
14628 switch (N->getOpcode()) {
14630 llvm_unreachable("Unknown shift opcode!");
14632 switch (VT.getSimpleVT().SimpleTy) {
14633 default: return SDValue();
14640 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14643 switch (VT.getSimpleVT().SimpleTy) {
14644 default: return SDValue();
14649 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14652 switch (VT.getSimpleVT().SimpleTy) {
14653 default: return SDValue();
14660 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14666 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14667 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14668 // and friends. Likewise for OR -> CMPNEQSS.
14669 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14670 TargetLowering::DAGCombinerInfo &DCI,
14671 const X86Subtarget *Subtarget) {
14674 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14675 // we're requiring SSE2 for both.
14676 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14677 SDValue N0 = N->getOperand(0);
14678 SDValue N1 = N->getOperand(1);
14679 SDValue CMP0 = N0->getOperand(1);
14680 SDValue CMP1 = N1->getOperand(1);
14681 DebugLoc DL = N->getDebugLoc();
14683 // The SETCCs should both refer to the same CMP.
14684 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14687 SDValue CMP00 = CMP0->getOperand(0);
14688 SDValue CMP01 = CMP0->getOperand(1);
14689 EVT VT = CMP00.getValueType();
14691 if (VT == MVT::f32 || VT == MVT::f64) {
14692 bool ExpectingFlags = false;
14693 // Check for any users that want flags:
14694 for (SDNode::use_iterator UI = N->use_begin(),
14696 !ExpectingFlags && UI != UE; ++UI)
14697 switch (UI->getOpcode()) {
14702 ExpectingFlags = true;
14704 case ISD::CopyToReg:
14705 case ISD::SIGN_EXTEND:
14706 case ISD::ZERO_EXTEND:
14707 case ISD::ANY_EXTEND:
14711 if (!ExpectingFlags) {
14712 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14713 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14715 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14716 X86::CondCode tmp = cc0;
14721 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14722 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14723 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14724 X86ISD::NodeType NTOperator = is64BitFP ?
14725 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14726 // FIXME: need symbolic constants for these magic numbers.
14727 // See X86ATTInstPrinter.cpp:printSSECC().
14728 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14729 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14730 DAG.getConstant(x86cc, MVT::i8));
14731 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14733 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14734 DAG.getConstant(1, MVT::i32));
14735 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14736 return OneBitOfTruth;
14744 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14745 /// so it can be folded inside ANDNP.
14746 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14747 EVT VT = N->getValueType(0);
14749 // Match direct AllOnes for 128 and 256-bit vectors
14750 if (ISD::isBuildVectorAllOnes(N))
14753 // Look through a bit convert.
14754 if (N->getOpcode() == ISD::BITCAST)
14755 N = N->getOperand(0).getNode();
14757 // Sometimes the operand may come from a insert_subvector building a 256-bit
14759 if (VT.is256BitVector() &&
14760 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14761 SDValue V1 = N->getOperand(0);
14762 SDValue V2 = N->getOperand(1);
14764 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14765 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14766 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14767 ISD::isBuildVectorAllOnes(V2.getNode()))
14774 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14775 TargetLowering::DAGCombinerInfo &DCI,
14776 const X86Subtarget *Subtarget) {
14777 if (DCI.isBeforeLegalizeOps())
14780 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14784 EVT VT = N->getValueType(0);
14786 // Create ANDN, BLSI, and BLSR instructions
14787 // BLSI is X & (-X)
14788 // BLSR is X & (X-1)
14789 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14790 SDValue N0 = N->getOperand(0);
14791 SDValue N1 = N->getOperand(1);
14792 DebugLoc DL = N->getDebugLoc();
14794 // Check LHS for not
14795 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14796 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14797 // Check RHS for not
14798 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14799 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14801 // Check LHS for neg
14802 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14803 isZero(N0.getOperand(0)))
14804 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14806 // Check RHS for neg
14807 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14808 isZero(N1.getOperand(0)))
14809 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14811 // Check LHS for X-1
14812 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14813 isAllOnes(N0.getOperand(1)))
14814 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14816 // Check RHS for X-1
14817 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14818 isAllOnes(N1.getOperand(1)))
14819 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14824 // Want to form ANDNP nodes:
14825 // 1) In the hopes of then easily combining them with OR and AND nodes
14826 // to form PBLEND/PSIGN.
14827 // 2) To match ANDN packed intrinsics
14828 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14831 SDValue N0 = N->getOperand(0);
14832 SDValue N1 = N->getOperand(1);
14833 DebugLoc DL = N->getDebugLoc();
14835 // Check LHS for vnot
14836 if (N0.getOpcode() == ISD::XOR &&
14837 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14838 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14839 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14841 // Check RHS for vnot
14842 if (N1.getOpcode() == ISD::XOR &&
14843 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14844 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14845 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14850 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14851 TargetLowering::DAGCombinerInfo &DCI,
14852 const X86Subtarget *Subtarget) {
14853 if (DCI.isBeforeLegalizeOps())
14856 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14860 EVT VT = N->getValueType(0);
14862 SDValue N0 = N->getOperand(0);
14863 SDValue N1 = N->getOperand(1);
14865 // look for psign/blend
14866 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14867 if (!Subtarget->hasSSSE3() ||
14868 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14871 // Canonicalize pandn to RHS
14872 if (N0.getOpcode() == X86ISD::ANDNP)
14874 // or (and (m, y), (pandn m, x))
14875 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14876 SDValue Mask = N1.getOperand(0);
14877 SDValue X = N1.getOperand(1);
14879 if (N0.getOperand(0) == Mask)
14880 Y = N0.getOperand(1);
14881 if (N0.getOperand(1) == Mask)
14882 Y = N0.getOperand(0);
14884 // Check to see if the mask appeared in both the AND and ANDNP and
14888 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14889 // Look through mask bitcast.
14890 if (Mask.getOpcode() == ISD::BITCAST)
14891 Mask = Mask.getOperand(0);
14892 if (X.getOpcode() == ISD::BITCAST)
14893 X = X.getOperand(0);
14894 if (Y.getOpcode() == ISD::BITCAST)
14895 Y = Y.getOperand(0);
14897 EVT MaskVT = Mask.getValueType();
14899 // Validate that the Mask operand is a vector sra node.
14900 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14901 // there is no psrai.b
14902 if (Mask.getOpcode() != X86ISD::VSRAI)
14905 // Check that the SRA is all signbits.
14906 SDValue SraC = Mask.getOperand(1);
14907 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14908 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14909 if ((SraAmt + 1) != EltBits)
14912 DebugLoc DL = N->getDebugLoc();
14914 // Now we know we at least have a plendvb with the mask val. See if
14915 // we can form a psignb/w/d.
14916 // psign = x.type == y.type == mask.type && y = sub(0, x);
14917 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14918 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14919 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14920 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14921 "Unsupported VT for PSIGN");
14922 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14923 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14925 // PBLENDVB only available on SSE 4.1
14926 if (!Subtarget->hasSSE41())
14929 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14931 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14932 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14933 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14934 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14935 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14939 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14942 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14943 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14945 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14947 if (!N0.hasOneUse() || !N1.hasOneUse())
14950 SDValue ShAmt0 = N0.getOperand(1);
14951 if (ShAmt0.getValueType() != MVT::i8)
14953 SDValue ShAmt1 = N1.getOperand(1);
14954 if (ShAmt1.getValueType() != MVT::i8)
14956 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14957 ShAmt0 = ShAmt0.getOperand(0);
14958 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14959 ShAmt1 = ShAmt1.getOperand(0);
14961 DebugLoc DL = N->getDebugLoc();
14962 unsigned Opc = X86ISD::SHLD;
14963 SDValue Op0 = N0.getOperand(0);
14964 SDValue Op1 = N1.getOperand(0);
14965 if (ShAmt0.getOpcode() == ISD::SUB) {
14966 Opc = X86ISD::SHRD;
14967 std::swap(Op0, Op1);
14968 std::swap(ShAmt0, ShAmt1);
14971 unsigned Bits = VT.getSizeInBits();
14972 if (ShAmt1.getOpcode() == ISD::SUB) {
14973 SDValue Sum = ShAmt1.getOperand(0);
14974 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14975 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14976 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14977 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14978 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14979 return DAG.getNode(Opc, DL, VT,
14981 DAG.getNode(ISD::TRUNCATE, DL,
14984 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14985 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14987 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14988 return DAG.getNode(Opc, DL, VT,
14989 N0.getOperand(0), N1.getOperand(0),
14990 DAG.getNode(ISD::TRUNCATE, DL,
14997 // Generate NEG and CMOV for integer abs.
14998 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14999 EVT VT = N->getValueType(0);
15001 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15002 // 8-bit integer abs to NEG and CMOV.
15003 if (VT.isInteger() && VT.getSizeInBits() == 8)
15006 SDValue N0 = N->getOperand(0);
15007 SDValue N1 = N->getOperand(1);
15008 DebugLoc DL = N->getDebugLoc();
15010 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15011 // and change it to SUB and CMOV.
15012 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15013 N0.getOpcode() == ISD::ADD &&
15014 N0.getOperand(1) == N1 &&
15015 N1.getOpcode() == ISD::SRA &&
15016 N1.getOperand(0) == N0.getOperand(0))
15017 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15018 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15019 // Generate SUB & CMOV.
15020 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15021 DAG.getConstant(0, VT), N0.getOperand(0));
15023 SDValue Ops[] = { N0.getOperand(0), Neg,
15024 DAG.getConstant(X86::COND_GE, MVT::i8),
15025 SDValue(Neg.getNode(), 1) };
15026 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15027 Ops, array_lengthof(Ops));
15032 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15033 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15034 TargetLowering::DAGCombinerInfo &DCI,
15035 const X86Subtarget *Subtarget) {
15036 if (DCI.isBeforeLegalizeOps())
15039 if (Subtarget->hasCMov()) {
15040 SDValue RV = performIntegerAbsCombine(N, DAG);
15045 // Try forming BMI if it is available.
15046 if (!Subtarget->hasBMI())
15049 EVT VT = N->getValueType(0);
15051 if (VT != MVT::i32 && VT != MVT::i64)
15054 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15056 // Create BLSMSK instructions by finding X ^ (X-1)
15057 SDValue N0 = N->getOperand(0);
15058 SDValue N1 = N->getOperand(1);
15059 DebugLoc DL = N->getDebugLoc();
15061 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15062 isAllOnes(N0.getOperand(1)))
15063 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15065 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15066 isAllOnes(N1.getOperand(1)))
15067 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15072 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15073 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15074 TargetLowering::DAGCombinerInfo &DCI,
15075 const X86Subtarget *Subtarget) {
15076 LoadSDNode *Ld = cast<LoadSDNode>(N);
15077 EVT RegVT = Ld->getValueType(0);
15078 EVT MemVT = Ld->getMemoryVT();
15079 DebugLoc dl = Ld->getDebugLoc();
15080 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15082 ISD::LoadExtType Ext = Ld->getExtensionType();
15084 // If this is a vector EXT Load then attempt to optimize it using a
15085 // shuffle. We need SSE4 for the shuffles.
15086 // TODO: It is possible to support ZExt by zeroing the undef values
15087 // during the shuffle phase or after the shuffle.
15088 if (RegVT.isVector() && RegVT.isInteger() &&
15089 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15090 assert(MemVT != RegVT && "Cannot extend to the same type");
15091 assert(MemVT.isVector() && "Must load a vector from memory");
15093 unsigned NumElems = RegVT.getVectorNumElements();
15094 unsigned RegSz = RegVT.getSizeInBits();
15095 unsigned MemSz = MemVT.getSizeInBits();
15096 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15098 // All sizes must be a power of two.
15099 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15102 // Attempt to load the original value using scalar loads.
15103 // Find the largest scalar type that divides the total loaded size.
15104 MVT SclrLoadTy = MVT::i8;
15105 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15106 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15107 MVT Tp = (MVT::SimpleValueType)tp;
15108 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15113 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15114 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15116 SclrLoadTy = MVT::f64;
15118 // Calculate the number of scalar loads that we need to perform
15119 // in order to load our vector from memory.
15120 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15122 // Represent our vector as a sequence of elements which are the
15123 // largest scalar that we can load.
15124 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15125 RegSz/SclrLoadTy.getSizeInBits());
15127 // Represent the data using the same element type that is stored in
15128 // memory. In practice, we ''widen'' MemVT.
15129 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15130 RegSz/MemVT.getScalarType().getSizeInBits());
15132 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15133 "Invalid vector type");
15135 // We can't shuffle using an illegal type.
15136 if (!TLI.isTypeLegal(WideVecVT))
15139 SmallVector<SDValue, 8> Chains;
15140 SDValue Ptr = Ld->getBasePtr();
15141 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15142 TLI.getPointerTy());
15143 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15145 for (unsigned i = 0; i < NumLoads; ++i) {
15146 // Perform a single load.
15147 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15148 Ptr, Ld->getPointerInfo(),
15149 Ld->isVolatile(), Ld->isNonTemporal(),
15150 Ld->isInvariant(), Ld->getAlignment());
15151 Chains.push_back(ScalarLoad.getValue(1));
15152 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15153 // another round of DAGCombining.
15155 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15157 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15158 ScalarLoad, DAG.getIntPtrConstant(i));
15160 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15163 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15166 // Bitcast the loaded value to a vector of the original element type, in
15167 // the size of the target vector type.
15168 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15169 unsigned SizeRatio = RegSz/MemSz;
15171 // Redistribute the loaded elements into the different locations.
15172 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15173 for (unsigned i = 0; i != NumElems; ++i)
15174 ShuffleVec[i*SizeRatio] = i;
15176 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15177 DAG.getUNDEF(WideVecVT),
15180 // Bitcast to the requested type.
15181 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15182 // Replace the original load with the new sequence
15183 // and return the new chain.
15184 return DCI.CombineTo(N, Shuff, TF, true);
15190 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15191 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15192 const X86Subtarget *Subtarget) {
15193 StoreSDNode *St = cast<StoreSDNode>(N);
15194 EVT VT = St->getValue().getValueType();
15195 EVT StVT = St->getMemoryVT();
15196 DebugLoc dl = St->getDebugLoc();
15197 SDValue StoredVal = St->getOperand(1);
15198 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15200 // If we are saving a concatenation of two XMM registers, perform two stores.
15201 // On Sandy Bridge, 256-bit memory operations are executed by two
15202 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15203 // memory operation.
15204 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15205 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15206 StoredVal.getNumOperands() == 2) {
15207 SDValue Value0 = StoredVal.getOperand(0);
15208 SDValue Value1 = StoredVal.getOperand(1);
15210 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15211 SDValue Ptr0 = St->getBasePtr();
15212 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15214 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15215 St->getPointerInfo(), St->isVolatile(),
15216 St->isNonTemporal(), St->getAlignment());
15217 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15218 St->getPointerInfo(), St->isVolatile(),
15219 St->isNonTemporal(), St->getAlignment());
15220 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15223 // Optimize trunc store (of multiple scalars) to shuffle and store.
15224 // First, pack all of the elements in one place. Next, store to memory
15225 // in fewer chunks.
15226 if (St->isTruncatingStore() && VT.isVector()) {
15227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15228 unsigned NumElems = VT.getVectorNumElements();
15229 assert(StVT != VT && "Cannot truncate to the same type");
15230 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15231 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15233 // From, To sizes and ElemCount must be pow of two
15234 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15235 // We are going to use the original vector elt for storing.
15236 // Accumulated smaller vector elements must be a multiple of the store size.
15237 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15239 unsigned SizeRatio = FromSz / ToSz;
15241 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15243 // Create a type on which we perform the shuffle
15244 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15245 StVT.getScalarType(), NumElems*SizeRatio);
15247 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15249 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15250 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15251 for (unsigned i = 0; i != NumElems; ++i)
15252 ShuffleVec[i] = i * SizeRatio;
15254 // Can't shuffle using an illegal type.
15255 if (!TLI.isTypeLegal(WideVecVT))
15258 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15259 DAG.getUNDEF(WideVecVT),
15261 // At this point all of the data is stored at the bottom of the
15262 // register. We now need to save it to mem.
15264 // Find the largest store unit
15265 MVT StoreType = MVT::i8;
15266 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15267 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15268 MVT Tp = (MVT::SimpleValueType)tp;
15269 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15273 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15274 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15275 (64 <= NumElems * ToSz))
15276 StoreType = MVT::f64;
15278 // Bitcast the original vector into a vector of store-size units
15279 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15280 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15281 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15282 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15283 SmallVector<SDValue, 8> Chains;
15284 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15285 TLI.getPointerTy());
15286 SDValue Ptr = St->getBasePtr();
15288 // Perform one or more big stores into memory.
15289 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15290 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15291 StoreType, ShuffWide,
15292 DAG.getIntPtrConstant(i));
15293 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15294 St->getPointerInfo(), St->isVolatile(),
15295 St->isNonTemporal(), St->getAlignment());
15296 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15297 Chains.push_back(Ch);
15300 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15305 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15306 // the FP state in cases where an emms may be missing.
15307 // A preferable solution to the general problem is to figure out the right
15308 // places to insert EMMS. This qualifies as a quick hack.
15310 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15311 if (VT.getSizeInBits() != 64)
15314 const Function *F = DAG.getMachineFunction().getFunction();
15315 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15316 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15317 && Subtarget->hasSSE2();
15318 if ((VT.isVector() ||
15319 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15320 isa<LoadSDNode>(St->getValue()) &&
15321 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15322 St->getChain().hasOneUse() && !St->isVolatile()) {
15323 SDNode* LdVal = St->getValue().getNode();
15324 LoadSDNode *Ld = 0;
15325 int TokenFactorIndex = -1;
15326 SmallVector<SDValue, 8> Ops;
15327 SDNode* ChainVal = St->getChain().getNode();
15328 // Must be a store of a load. We currently handle two cases: the load
15329 // is a direct child, and it's under an intervening TokenFactor. It is
15330 // possible to dig deeper under nested TokenFactors.
15331 if (ChainVal == LdVal)
15332 Ld = cast<LoadSDNode>(St->getChain());
15333 else if (St->getValue().hasOneUse() &&
15334 ChainVal->getOpcode() == ISD::TokenFactor) {
15335 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15336 if (ChainVal->getOperand(i).getNode() == LdVal) {
15337 TokenFactorIndex = i;
15338 Ld = cast<LoadSDNode>(St->getValue());
15340 Ops.push_back(ChainVal->getOperand(i));
15344 if (!Ld || !ISD::isNormalLoad(Ld))
15347 // If this is not the MMX case, i.e. we are just turning i64 load/store
15348 // into f64 load/store, avoid the transformation if there are multiple
15349 // uses of the loaded value.
15350 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15353 DebugLoc LdDL = Ld->getDebugLoc();
15354 DebugLoc StDL = N->getDebugLoc();
15355 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15356 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15358 if (Subtarget->is64Bit() || F64IsLegal) {
15359 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15360 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15361 Ld->getPointerInfo(), Ld->isVolatile(),
15362 Ld->isNonTemporal(), Ld->isInvariant(),
15363 Ld->getAlignment());
15364 SDValue NewChain = NewLd.getValue(1);
15365 if (TokenFactorIndex != -1) {
15366 Ops.push_back(NewChain);
15367 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15370 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15371 St->getPointerInfo(),
15372 St->isVolatile(), St->isNonTemporal(),
15373 St->getAlignment());
15376 // Otherwise, lower to two pairs of 32-bit loads / stores.
15377 SDValue LoAddr = Ld->getBasePtr();
15378 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15379 DAG.getConstant(4, MVT::i32));
15381 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15382 Ld->getPointerInfo(),
15383 Ld->isVolatile(), Ld->isNonTemporal(),
15384 Ld->isInvariant(), Ld->getAlignment());
15385 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15386 Ld->getPointerInfo().getWithOffset(4),
15387 Ld->isVolatile(), Ld->isNonTemporal(),
15389 MinAlign(Ld->getAlignment(), 4));
15391 SDValue NewChain = LoLd.getValue(1);
15392 if (TokenFactorIndex != -1) {
15393 Ops.push_back(LoLd);
15394 Ops.push_back(HiLd);
15395 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15399 LoAddr = St->getBasePtr();
15400 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15401 DAG.getConstant(4, MVT::i32));
15403 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15404 St->getPointerInfo(),
15405 St->isVolatile(), St->isNonTemporal(),
15406 St->getAlignment());
15407 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15408 St->getPointerInfo().getWithOffset(4),
15410 St->isNonTemporal(),
15411 MinAlign(St->getAlignment(), 4));
15412 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15417 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15418 /// and return the operands for the horizontal operation in LHS and RHS. A
15419 /// horizontal operation performs the binary operation on successive elements
15420 /// of its first operand, then on successive elements of its second operand,
15421 /// returning the resulting values in a vector. For example, if
15422 /// A = < float a0, float a1, float a2, float a3 >
15424 /// B = < float b0, float b1, float b2, float b3 >
15425 /// then the result of doing a horizontal operation on A and B is
15426 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15427 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15428 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15429 /// set to A, RHS to B, and the routine returns 'true'.
15430 /// Note that the binary operation should have the property that if one of the
15431 /// operands is UNDEF then the result is UNDEF.
15432 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15433 // Look for the following pattern: if
15434 // A = < float a0, float a1, float a2, float a3 >
15435 // B = < float b0, float b1, float b2, float b3 >
15437 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15438 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15439 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15440 // which is A horizontal-op B.
15442 // At least one of the operands should be a vector shuffle.
15443 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15444 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15447 EVT VT = LHS.getValueType();
15449 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15450 "Unsupported vector type for horizontal add/sub");
15452 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15453 // operate independently on 128-bit lanes.
15454 unsigned NumElts = VT.getVectorNumElements();
15455 unsigned NumLanes = VT.getSizeInBits()/128;
15456 unsigned NumLaneElts = NumElts / NumLanes;
15457 assert((NumLaneElts % 2 == 0) &&
15458 "Vector type should have an even number of elements in each lane");
15459 unsigned HalfLaneElts = NumLaneElts/2;
15461 // View LHS in the form
15462 // LHS = VECTOR_SHUFFLE A, B, LMask
15463 // If LHS is not a shuffle then pretend it is the shuffle
15464 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15465 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15468 SmallVector<int, 16> LMask(NumElts);
15469 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15470 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15471 A = LHS.getOperand(0);
15472 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15473 B = LHS.getOperand(1);
15474 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15475 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15477 if (LHS.getOpcode() != ISD::UNDEF)
15479 for (unsigned i = 0; i != NumElts; ++i)
15483 // Likewise, view RHS in the form
15484 // RHS = VECTOR_SHUFFLE C, D, RMask
15486 SmallVector<int, 16> RMask(NumElts);
15487 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15488 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15489 C = RHS.getOperand(0);
15490 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15491 D = RHS.getOperand(1);
15492 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15493 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15495 if (RHS.getOpcode() != ISD::UNDEF)
15497 for (unsigned i = 0; i != NumElts; ++i)
15501 // Check that the shuffles are both shuffling the same vectors.
15502 if (!(A == C && B == D) && !(A == D && B == C))
15505 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15506 if (!A.getNode() && !B.getNode())
15509 // If A and B occur in reverse order in RHS, then "swap" them (which means
15510 // rewriting the mask).
15512 CommuteVectorShuffleMask(RMask, NumElts);
15514 // At this point LHS and RHS are equivalent to
15515 // LHS = VECTOR_SHUFFLE A, B, LMask
15516 // RHS = VECTOR_SHUFFLE A, B, RMask
15517 // Check that the masks correspond to performing a horizontal operation.
15518 for (unsigned i = 0; i != NumElts; ++i) {
15519 int LIdx = LMask[i], RIdx = RMask[i];
15521 // Ignore any UNDEF components.
15522 if (LIdx < 0 || RIdx < 0 ||
15523 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15524 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15527 // Check that successive elements are being operated on. If not, this is
15528 // not a horizontal operation.
15529 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15530 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15531 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15532 if (!(LIdx == Index && RIdx == Index + 1) &&
15533 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15537 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15538 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15542 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15543 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15544 const X86Subtarget *Subtarget) {
15545 EVT VT = N->getValueType(0);
15546 SDValue LHS = N->getOperand(0);
15547 SDValue RHS = N->getOperand(1);
15549 // Try to synthesize horizontal adds from adds of shuffles.
15550 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15551 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15552 isHorizontalBinOp(LHS, RHS, true))
15553 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15557 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15558 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15559 const X86Subtarget *Subtarget) {
15560 EVT VT = N->getValueType(0);
15561 SDValue LHS = N->getOperand(0);
15562 SDValue RHS = N->getOperand(1);
15564 // Try to synthesize horizontal subs from subs of shuffles.
15565 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15566 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15567 isHorizontalBinOp(LHS, RHS, false))
15568 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15572 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15573 /// X86ISD::FXOR nodes.
15574 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15575 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15576 // F[X]OR(0.0, x) -> x
15577 // F[X]OR(x, 0.0) -> x
15578 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15579 if (C->getValueAPF().isPosZero())
15580 return N->getOperand(1);
15581 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15582 if (C->getValueAPF().isPosZero())
15583 return N->getOperand(0);
15587 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15588 /// X86ISD::FMAX nodes.
15589 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15590 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15592 // Only perform optimizations if UnsafeMath is used.
15593 if (!DAG.getTarget().Options.UnsafeFPMath)
15596 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15597 // into FMINC and FMAXC, which are Commutative operations.
15598 unsigned NewOp = 0;
15599 switch (N->getOpcode()) {
15600 default: llvm_unreachable("unknown opcode");
15601 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15602 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15605 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15606 N->getOperand(0), N->getOperand(1));
15610 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15611 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15612 // FAND(0.0, x) -> 0.0
15613 // FAND(x, 0.0) -> 0.0
15614 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15615 if (C->getValueAPF().isPosZero())
15616 return N->getOperand(0);
15617 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15618 if (C->getValueAPF().isPosZero())
15619 return N->getOperand(1);
15623 static SDValue PerformBTCombine(SDNode *N,
15625 TargetLowering::DAGCombinerInfo &DCI) {
15626 // BT ignores high bits in the bit index operand.
15627 SDValue Op1 = N->getOperand(1);
15628 if (Op1.hasOneUse()) {
15629 unsigned BitWidth = Op1.getValueSizeInBits();
15630 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15631 APInt KnownZero, KnownOne;
15632 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15633 !DCI.isBeforeLegalizeOps());
15634 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15635 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15636 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15637 DCI.CommitTargetLoweringOpt(TLO);
15642 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15643 SDValue Op = N->getOperand(0);
15644 if (Op.getOpcode() == ISD::BITCAST)
15645 Op = Op.getOperand(0);
15646 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15647 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15648 VT.getVectorElementType().getSizeInBits() ==
15649 OpVT.getVectorElementType().getSizeInBits()) {
15650 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15655 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15656 TargetLowering::DAGCombinerInfo &DCI,
15657 const X86Subtarget *Subtarget) {
15658 if (!DCI.isBeforeLegalizeOps())
15661 if (!Subtarget->hasAVX())
15664 EVT VT = N->getValueType(0);
15665 SDValue Op = N->getOperand(0);
15666 EVT OpVT = Op.getValueType();
15667 DebugLoc dl = N->getDebugLoc();
15669 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15670 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15672 if (Subtarget->hasAVX2())
15673 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15675 // Optimize vectors in AVX mode
15676 // Sign extend v8i16 to v8i32 and
15679 // Divide input vector into two parts
15680 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15681 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15682 // concat the vectors to original VT
15684 unsigned NumElems = OpVT.getVectorNumElements();
15685 SDValue Undef = DAG.getUNDEF(OpVT);
15687 SmallVector<int,8> ShufMask1(NumElems, -1);
15688 for (unsigned i = 0; i != NumElems/2; ++i)
15691 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15693 SmallVector<int,8> ShufMask2(NumElems, -1);
15694 for (unsigned i = 0; i != NumElems/2; ++i)
15695 ShufMask2[i] = i + NumElems/2;
15697 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15699 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15700 VT.getVectorNumElements()/2);
15702 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15703 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15705 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15710 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15711 const X86Subtarget* Subtarget) {
15712 DebugLoc dl = N->getDebugLoc();
15713 EVT VT = N->getValueType(0);
15715 // Let legalize expand this if it isn't a legal type yet.
15716 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15719 EVT ScalarVT = VT.getScalarType();
15720 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15721 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15724 SDValue A = N->getOperand(0);
15725 SDValue B = N->getOperand(1);
15726 SDValue C = N->getOperand(2);
15728 bool NegA = (A.getOpcode() == ISD::FNEG);
15729 bool NegB = (B.getOpcode() == ISD::FNEG);
15730 bool NegC = (C.getOpcode() == ISD::FNEG);
15732 // Negative multiplication when NegA xor NegB
15733 bool NegMul = (NegA != NegB);
15735 A = A.getOperand(0);
15737 B = B.getOperand(0);
15739 C = C.getOperand(0);
15743 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15745 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15747 return DAG.getNode(Opcode, dl, VT, A, B, C);
15750 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15751 TargetLowering::DAGCombinerInfo &DCI,
15752 const X86Subtarget *Subtarget) {
15753 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15754 // (and (i32 x86isd::setcc_carry), 1)
15755 // This eliminates the zext. This transformation is necessary because
15756 // ISD::SETCC is always legalized to i8.
15757 DebugLoc dl = N->getDebugLoc();
15758 SDValue N0 = N->getOperand(0);
15759 EVT VT = N->getValueType(0);
15760 EVT OpVT = N0.getValueType();
15762 if (N0.getOpcode() == ISD::AND &&
15764 N0.getOperand(0).hasOneUse()) {
15765 SDValue N00 = N0.getOperand(0);
15766 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15768 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15769 if (!C || C->getZExtValue() != 1)
15771 return DAG.getNode(ISD::AND, dl, VT,
15772 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15773 N00.getOperand(0), N00.getOperand(1)),
15774 DAG.getConstant(1, VT));
15777 // Optimize vectors in AVX mode:
15780 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15781 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15782 // Concat upper and lower parts.
15785 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15786 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15787 // Concat upper and lower parts.
15789 if (!DCI.isBeforeLegalizeOps())
15792 if (!Subtarget->hasAVX())
15795 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15796 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15798 if (Subtarget->hasAVX2())
15799 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15801 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15802 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15803 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15805 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15806 VT.getVectorNumElements()/2);
15808 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15809 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15811 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15817 // Optimize x == -y --> x+y == 0
15818 // x != -y --> x+y != 0
15819 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15820 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15821 SDValue LHS = N->getOperand(0);
15822 SDValue RHS = N->getOperand(1);
15824 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15826 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15827 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15828 LHS.getValueType(), RHS, LHS.getOperand(1));
15829 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15830 addV, DAG.getConstant(0, addV.getValueType()), CC);
15832 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15833 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15834 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15835 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15836 RHS.getValueType(), LHS, RHS.getOperand(1));
15837 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15838 addV, DAG.getConstant(0, addV.getValueType()), CC);
15843 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15844 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15845 TargetLowering::DAGCombinerInfo &DCI,
15846 const X86Subtarget *Subtarget) {
15847 DebugLoc DL = N->getDebugLoc();
15848 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15849 SDValue EFLAGS = N->getOperand(1);
15851 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15852 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15854 if (CC == X86::COND_B)
15855 return DAG.getNode(ISD::AND, DL, MVT::i8,
15856 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15857 DAG.getConstant(CC, MVT::i8), EFLAGS),
15858 DAG.getConstant(1, MVT::i8));
15862 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15863 if (Flags.getNode()) {
15864 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15865 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15871 // Optimize branch condition evaluation.
15873 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15874 TargetLowering::DAGCombinerInfo &DCI,
15875 const X86Subtarget *Subtarget) {
15876 DebugLoc DL = N->getDebugLoc();
15877 SDValue Chain = N->getOperand(0);
15878 SDValue Dest = N->getOperand(1);
15879 SDValue EFLAGS = N->getOperand(3);
15880 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15884 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15885 if (Flags.getNode()) {
15886 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15887 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15894 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15895 SDValue Op0 = N->getOperand(0);
15896 EVT InVT = Op0->getValueType(0);
15898 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15899 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15900 DebugLoc dl = N->getDebugLoc();
15901 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15902 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15903 // Notice that we use SINT_TO_FP because we know that the high bits
15904 // are zero and SINT_TO_FP is better supported by the hardware.
15905 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15911 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15912 const X86TargetLowering *XTLI) {
15913 SDValue Op0 = N->getOperand(0);
15914 EVT InVT = Op0->getValueType(0);
15916 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15917 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15918 DebugLoc dl = N->getDebugLoc();
15919 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15920 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15921 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15924 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15925 // a 32-bit target where SSE doesn't support i64->FP operations.
15926 if (Op0.getOpcode() == ISD::LOAD) {
15927 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15928 EVT VT = Ld->getValueType(0);
15929 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15930 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15931 !XTLI->getSubtarget()->is64Bit() &&
15932 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15933 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15934 Ld->getChain(), Op0, DAG);
15935 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15942 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15943 EVT VT = N->getValueType(0);
15945 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15946 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15947 DebugLoc dl = N->getDebugLoc();
15948 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15949 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15950 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15956 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15957 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15958 X86TargetLowering::DAGCombinerInfo &DCI) {
15959 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15960 // the result is either zero or one (depending on the input carry bit).
15961 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15962 if (X86::isZeroNode(N->getOperand(0)) &&
15963 X86::isZeroNode(N->getOperand(1)) &&
15964 // We don't have a good way to replace an EFLAGS use, so only do this when
15966 SDValue(N, 1).use_empty()) {
15967 DebugLoc DL = N->getDebugLoc();
15968 EVT VT = N->getValueType(0);
15969 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15970 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15971 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15972 DAG.getConstant(X86::COND_B,MVT::i8),
15974 DAG.getConstant(1, VT));
15975 return DCI.CombineTo(N, Res1, CarryOut);
15981 // fold (add Y, (sete X, 0)) -> adc 0, Y
15982 // (add Y, (setne X, 0)) -> sbb -1, Y
15983 // (sub (sete X, 0), Y) -> sbb 0, Y
15984 // (sub (setne X, 0), Y) -> adc -1, Y
15985 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15986 DebugLoc DL = N->getDebugLoc();
15988 // Look through ZExts.
15989 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15990 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15993 SDValue SetCC = Ext.getOperand(0);
15994 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15997 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15998 if (CC != X86::COND_E && CC != X86::COND_NE)
16001 SDValue Cmp = SetCC.getOperand(1);
16002 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16003 !X86::isZeroNode(Cmp.getOperand(1)) ||
16004 !Cmp.getOperand(0).getValueType().isInteger())
16007 SDValue CmpOp0 = Cmp.getOperand(0);
16008 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16009 DAG.getConstant(1, CmpOp0.getValueType()));
16011 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16012 if (CC == X86::COND_NE)
16013 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16014 DL, OtherVal.getValueType(), OtherVal,
16015 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16016 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16017 DL, OtherVal.getValueType(), OtherVal,
16018 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16021 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16022 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16023 const X86Subtarget *Subtarget) {
16024 EVT VT = N->getValueType(0);
16025 SDValue Op0 = N->getOperand(0);
16026 SDValue Op1 = N->getOperand(1);
16028 // Try to synthesize horizontal adds from adds of shuffles.
16029 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16030 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16031 isHorizontalBinOp(Op0, Op1, true))
16032 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16034 return OptimizeConditionalInDecrement(N, DAG);
16037 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16038 const X86Subtarget *Subtarget) {
16039 SDValue Op0 = N->getOperand(0);
16040 SDValue Op1 = N->getOperand(1);
16042 // X86 can't encode an immediate LHS of a sub. See if we can push the
16043 // negation into a preceding instruction.
16044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16045 // If the RHS of the sub is a XOR with one use and a constant, invert the
16046 // immediate. Then add one to the LHS of the sub so we can turn
16047 // X-Y -> X+~Y+1, saving one register.
16048 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16049 isa<ConstantSDNode>(Op1.getOperand(1))) {
16050 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16051 EVT VT = Op0.getValueType();
16052 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16054 DAG.getConstant(~XorC, VT));
16055 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16056 DAG.getConstant(C->getAPIntValue()+1, VT));
16060 // Try to synthesize horizontal adds from adds of shuffles.
16061 EVT VT = N->getValueType(0);
16062 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16063 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16064 isHorizontalBinOp(Op0, Op1, true))
16065 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16067 return OptimizeConditionalInDecrement(N, DAG);
16070 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16071 DAGCombinerInfo &DCI) const {
16072 SelectionDAG &DAG = DCI.DAG;
16073 switch (N->getOpcode()) {
16075 case ISD::EXTRACT_VECTOR_ELT:
16076 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16078 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16079 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16080 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16081 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16082 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16083 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16086 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16087 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16088 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16089 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16090 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16091 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16092 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16093 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16094 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
16095 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16096 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16098 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16100 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16101 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16102 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16103 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16104 case ISD::ANY_EXTEND:
16105 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16106 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16107 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16108 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16109 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16110 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16111 case X86ISD::SHUFP: // Handle all target specific shuffles
16112 case X86ISD::PALIGN:
16113 case X86ISD::UNPCKH:
16114 case X86ISD::UNPCKL:
16115 case X86ISD::MOVHLPS:
16116 case X86ISD::MOVLHPS:
16117 case X86ISD::PSHUFD:
16118 case X86ISD::PSHUFHW:
16119 case X86ISD::PSHUFLW:
16120 case X86ISD::MOVSS:
16121 case X86ISD::MOVSD:
16122 case X86ISD::VPERMILP:
16123 case X86ISD::VPERM2X128:
16124 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16125 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16131 /// isTypeDesirableForOp - Return true if the target has native support for
16132 /// the specified value type and it is 'desirable' to use the type for the
16133 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16134 /// instruction encodings are longer and some i16 instructions are slow.
16135 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16136 if (!isTypeLegal(VT))
16138 if (VT != MVT::i16)
16145 case ISD::SIGN_EXTEND:
16146 case ISD::ZERO_EXTEND:
16147 case ISD::ANY_EXTEND:
16160 /// IsDesirableToPromoteOp - This method query the target whether it is
16161 /// beneficial for dag combiner to promote the specified node. If true, it
16162 /// should return the desired promotion type by reference.
16163 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16164 EVT VT = Op.getValueType();
16165 if (VT != MVT::i16)
16168 bool Promote = false;
16169 bool Commute = false;
16170 switch (Op.getOpcode()) {
16173 LoadSDNode *LD = cast<LoadSDNode>(Op);
16174 // If the non-extending load has a single use and it's not live out, then it
16175 // might be folded.
16176 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16177 Op.hasOneUse()*/) {
16178 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16179 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16180 // The only case where we'd want to promote LOAD (rather then it being
16181 // promoted as an operand is when it's only use is liveout.
16182 if (UI->getOpcode() != ISD::CopyToReg)
16189 case ISD::SIGN_EXTEND:
16190 case ISD::ZERO_EXTEND:
16191 case ISD::ANY_EXTEND:
16196 SDValue N0 = Op.getOperand(0);
16197 // Look out for (store (shl (load), x)).
16198 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16211 SDValue N0 = Op.getOperand(0);
16212 SDValue N1 = Op.getOperand(1);
16213 if (!Commute && MayFoldLoad(N1))
16215 // Avoid disabling potential load folding opportunities.
16216 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16218 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16228 //===----------------------------------------------------------------------===//
16229 // X86 Inline Assembly Support
16230 //===----------------------------------------------------------------------===//
16233 // Helper to match a string separated by whitespace.
16234 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16235 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16237 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16238 StringRef piece(*args[i]);
16239 if (!s.startswith(piece)) // Check if the piece matches.
16242 s = s.substr(piece.size());
16243 StringRef::size_type pos = s.find_first_not_of(" \t");
16244 if (pos == 0) // We matched a prefix.
16252 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16255 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16256 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16258 std::string AsmStr = IA->getAsmString();
16260 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16261 if (!Ty || Ty->getBitWidth() % 16 != 0)
16264 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16265 SmallVector<StringRef, 4> AsmPieces;
16266 SplitString(AsmStr, AsmPieces, ";\n");
16268 switch (AsmPieces.size()) {
16269 default: return false;
16271 // FIXME: this should verify that we are targeting a 486 or better. If not,
16272 // we will turn this bswap into something that will be lowered to logical
16273 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16274 // lower so don't worry about this.
16276 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16277 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16278 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16279 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16280 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16281 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16282 // No need to check constraints, nothing other than the equivalent of
16283 // "=r,0" would be valid here.
16284 return IntrinsicLowering::LowerToByteSwap(CI);
16287 // rorw $$8, ${0:w} --> llvm.bswap.i16
16288 if (CI->getType()->isIntegerTy(16) &&
16289 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16290 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16291 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16293 const std::string &ConstraintsStr = IA->getConstraintString();
16294 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16295 std::sort(AsmPieces.begin(), AsmPieces.end());
16296 if (AsmPieces.size() == 4 &&
16297 AsmPieces[0] == "~{cc}" &&
16298 AsmPieces[1] == "~{dirflag}" &&
16299 AsmPieces[2] == "~{flags}" &&
16300 AsmPieces[3] == "~{fpsr}")
16301 return IntrinsicLowering::LowerToByteSwap(CI);
16305 if (CI->getType()->isIntegerTy(32) &&
16306 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16307 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16308 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16309 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16311 const std::string &ConstraintsStr = IA->getConstraintString();
16312 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16313 std::sort(AsmPieces.begin(), AsmPieces.end());
16314 if (AsmPieces.size() == 4 &&
16315 AsmPieces[0] == "~{cc}" &&
16316 AsmPieces[1] == "~{dirflag}" &&
16317 AsmPieces[2] == "~{flags}" &&
16318 AsmPieces[3] == "~{fpsr}")
16319 return IntrinsicLowering::LowerToByteSwap(CI);
16322 if (CI->getType()->isIntegerTy(64)) {
16323 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16324 if (Constraints.size() >= 2 &&
16325 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16326 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16327 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16328 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16329 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16330 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16331 return IntrinsicLowering::LowerToByteSwap(CI);
16341 /// getConstraintType - Given a constraint letter, return the type of
16342 /// constraint it is for this target.
16343 X86TargetLowering::ConstraintType
16344 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16345 if (Constraint.size() == 1) {
16346 switch (Constraint[0]) {
16357 return C_RegisterClass;
16381 return TargetLowering::getConstraintType(Constraint);
16384 /// Examine constraint type and operand type and determine a weight value.
16385 /// This object must already have been set up with the operand type
16386 /// and the current alternative constraint selected.
16387 TargetLowering::ConstraintWeight
16388 X86TargetLowering::getSingleConstraintMatchWeight(
16389 AsmOperandInfo &info, const char *constraint) const {
16390 ConstraintWeight weight = CW_Invalid;
16391 Value *CallOperandVal = info.CallOperandVal;
16392 // If we don't have a value, we can't do a match,
16393 // but allow it at the lowest weight.
16394 if (CallOperandVal == NULL)
16396 Type *type = CallOperandVal->getType();
16397 // Look at the constraint type.
16398 switch (*constraint) {
16400 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16411 if (CallOperandVal->getType()->isIntegerTy())
16412 weight = CW_SpecificReg;
16417 if (type->isFloatingPointTy())
16418 weight = CW_SpecificReg;
16421 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16422 weight = CW_SpecificReg;
16426 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16427 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16428 weight = CW_Register;
16431 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16432 if (C->getZExtValue() <= 31)
16433 weight = CW_Constant;
16437 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16438 if (C->getZExtValue() <= 63)
16439 weight = CW_Constant;
16443 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16444 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16445 weight = CW_Constant;
16449 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16450 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16451 weight = CW_Constant;
16455 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16456 if (C->getZExtValue() <= 3)
16457 weight = CW_Constant;
16461 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16462 if (C->getZExtValue() <= 0xff)
16463 weight = CW_Constant;
16468 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16469 weight = CW_Constant;
16473 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16474 if ((C->getSExtValue() >= -0x80000000LL) &&
16475 (C->getSExtValue() <= 0x7fffffffLL))
16476 weight = CW_Constant;
16480 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16481 if (C->getZExtValue() <= 0xffffffff)
16482 weight = CW_Constant;
16489 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16490 /// with another that has more specific requirements based on the type of the
16491 /// corresponding operand.
16492 const char *X86TargetLowering::
16493 LowerXConstraint(EVT ConstraintVT) const {
16494 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16495 // 'f' like normal targets.
16496 if (ConstraintVT.isFloatingPoint()) {
16497 if (Subtarget->hasSSE2())
16499 if (Subtarget->hasSSE1())
16503 return TargetLowering::LowerXConstraint(ConstraintVT);
16506 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16507 /// vector. If it is invalid, don't add anything to Ops.
16508 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16509 std::string &Constraint,
16510 std::vector<SDValue>&Ops,
16511 SelectionDAG &DAG) const {
16512 SDValue Result(0, 0);
16514 // Only support length 1 constraints for now.
16515 if (Constraint.length() > 1) return;
16517 char ConstraintLetter = Constraint[0];
16518 switch (ConstraintLetter) {
16521 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16522 if (C->getZExtValue() <= 31) {
16523 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16529 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16530 if (C->getZExtValue() <= 63) {
16531 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16537 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16538 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16539 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16545 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16546 if (C->getZExtValue() <= 255) {
16547 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16553 // 32-bit signed value
16554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16555 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16556 C->getSExtValue())) {
16557 // Widen to 64 bits here to get it sign extended.
16558 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16561 // FIXME gcc accepts some relocatable values here too, but only in certain
16562 // memory models; it's complicated.
16567 // 32-bit unsigned value
16568 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16569 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16570 C->getZExtValue())) {
16571 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16575 // FIXME gcc accepts some relocatable values here too, but only in certain
16576 // memory models; it's complicated.
16580 // Literal immediates are always ok.
16581 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16582 // Widen to 64 bits here to get it sign extended.
16583 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16587 // In any sort of PIC mode addresses need to be computed at runtime by
16588 // adding in a register or some sort of table lookup. These can't
16589 // be used as immediates.
16590 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16593 // If we are in non-pic codegen mode, we allow the address of a global (with
16594 // an optional displacement) to be used with 'i'.
16595 GlobalAddressSDNode *GA = 0;
16596 int64_t Offset = 0;
16598 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16600 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16601 Offset += GA->getOffset();
16603 } else if (Op.getOpcode() == ISD::ADD) {
16604 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16605 Offset += C->getZExtValue();
16606 Op = Op.getOperand(0);
16609 } else if (Op.getOpcode() == ISD::SUB) {
16610 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16611 Offset += -C->getZExtValue();
16612 Op = Op.getOperand(0);
16617 // Otherwise, this isn't something we can handle, reject it.
16621 const GlobalValue *GV = GA->getGlobal();
16622 // If we require an extra load to get this address, as in PIC mode, we
16623 // can't accept it.
16624 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16625 getTargetMachine())))
16628 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16629 GA->getValueType(0), Offset);
16634 if (Result.getNode()) {
16635 Ops.push_back(Result);
16638 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16641 std::pair<unsigned, const TargetRegisterClass*>
16642 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16644 // First, see if this is a constraint that directly corresponds to an LLVM
16646 if (Constraint.size() == 1) {
16647 // GCC Constraint Letters
16648 switch (Constraint[0]) {
16650 // TODO: Slight differences here in allocation order and leaving
16651 // RIP in the class. Do they matter any more here than they do
16652 // in the normal allocation?
16653 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16654 if (Subtarget->is64Bit()) {
16655 if (VT == MVT::i32 || VT == MVT::f32)
16656 return std::make_pair(0U, &X86::GR32RegClass);
16657 if (VT == MVT::i16)
16658 return std::make_pair(0U, &X86::GR16RegClass);
16659 if (VT == MVT::i8 || VT == MVT::i1)
16660 return std::make_pair(0U, &X86::GR8RegClass);
16661 if (VT == MVT::i64 || VT == MVT::f64)
16662 return std::make_pair(0U, &X86::GR64RegClass);
16665 // 32-bit fallthrough
16666 case 'Q': // Q_REGS
16667 if (VT == MVT::i32 || VT == MVT::f32)
16668 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16669 if (VT == MVT::i16)
16670 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16671 if (VT == MVT::i8 || VT == MVT::i1)
16672 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16673 if (VT == MVT::i64)
16674 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16676 case 'r': // GENERAL_REGS
16677 case 'l': // INDEX_REGS
16678 if (VT == MVT::i8 || VT == MVT::i1)
16679 return std::make_pair(0U, &X86::GR8RegClass);
16680 if (VT == MVT::i16)
16681 return std::make_pair(0U, &X86::GR16RegClass);
16682 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16683 return std::make_pair(0U, &X86::GR32RegClass);
16684 return std::make_pair(0U, &X86::GR64RegClass);
16685 case 'R': // LEGACY_REGS
16686 if (VT == MVT::i8 || VT == MVT::i1)
16687 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16688 if (VT == MVT::i16)
16689 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16690 if (VT == MVT::i32 || !Subtarget->is64Bit())
16691 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16692 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16693 case 'f': // FP Stack registers.
16694 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16695 // value to the correct fpstack register class.
16696 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16697 return std::make_pair(0U, &X86::RFP32RegClass);
16698 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16699 return std::make_pair(0U, &X86::RFP64RegClass);
16700 return std::make_pair(0U, &X86::RFP80RegClass);
16701 case 'y': // MMX_REGS if MMX allowed.
16702 if (!Subtarget->hasMMX()) break;
16703 return std::make_pair(0U, &X86::VR64RegClass);
16704 case 'Y': // SSE_REGS if SSE2 allowed
16705 if (!Subtarget->hasSSE2()) break;
16707 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16708 if (!Subtarget->hasSSE1()) break;
16710 switch (VT.getSimpleVT().SimpleTy) {
16712 // Scalar SSE types.
16715 return std::make_pair(0U, &X86::FR32RegClass);
16718 return std::make_pair(0U, &X86::FR64RegClass);
16726 return std::make_pair(0U, &X86::VR128RegClass);
16734 return std::make_pair(0U, &X86::VR256RegClass);
16740 // Use the default implementation in TargetLowering to convert the register
16741 // constraint into a member of a register class.
16742 std::pair<unsigned, const TargetRegisterClass*> Res;
16743 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16745 // Not found as a standard register?
16746 if (Res.second == 0) {
16747 // Map st(0) -> st(7) -> ST0
16748 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16749 tolower(Constraint[1]) == 's' &&
16750 tolower(Constraint[2]) == 't' &&
16751 Constraint[3] == '(' &&
16752 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16753 Constraint[5] == ')' &&
16754 Constraint[6] == '}') {
16756 Res.first = X86::ST0+Constraint[4]-'0';
16757 Res.second = &X86::RFP80RegClass;
16761 // GCC allows "st(0)" to be called just plain "st".
16762 if (StringRef("{st}").equals_lower(Constraint)) {
16763 Res.first = X86::ST0;
16764 Res.second = &X86::RFP80RegClass;
16769 if (StringRef("{flags}").equals_lower(Constraint)) {
16770 Res.first = X86::EFLAGS;
16771 Res.second = &X86::CCRRegClass;
16775 // 'A' means EAX + EDX.
16776 if (Constraint == "A") {
16777 Res.first = X86::EAX;
16778 Res.second = &X86::GR32_ADRegClass;
16784 // Otherwise, check to see if this is a register class of the wrong value
16785 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16786 // turn into {ax},{dx}.
16787 if (Res.second->hasType(VT))
16788 return Res; // Correct type already, nothing to do.
16790 // All of the single-register GCC register classes map their values onto
16791 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16792 // really want an 8-bit or 32-bit register, map to the appropriate register
16793 // class and return the appropriate register.
16794 if (Res.second == &X86::GR16RegClass) {
16795 if (VT == MVT::i8) {
16796 unsigned DestReg = 0;
16797 switch (Res.first) {
16799 case X86::AX: DestReg = X86::AL; break;
16800 case X86::DX: DestReg = X86::DL; break;
16801 case X86::CX: DestReg = X86::CL; break;
16802 case X86::BX: DestReg = X86::BL; break;
16805 Res.first = DestReg;
16806 Res.second = &X86::GR8RegClass;
16808 } else if (VT == MVT::i32) {
16809 unsigned DestReg = 0;
16810 switch (Res.first) {
16812 case X86::AX: DestReg = X86::EAX; break;
16813 case X86::DX: DestReg = X86::EDX; break;
16814 case X86::CX: DestReg = X86::ECX; break;
16815 case X86::BX: DestReg = X86::EBX; break;
16816 case X86::SI: DestReg = X86::ESI; break;
16817 case X86::DI: DestReg = X86::EDI; break;
16818 case X86::BP: DestReg = X86::EBP; break;
16819 case X86::SP: DestReg = X86::ESP; break;
16822 Res.first = DestReg;
16823 Res.second = &X86::GR32RegClass;
16825 } else if (VT == MVT::i64) {
16826 unsigned DestReg = 0;
16827 switch (Res.first) {
16829 case X86::AX: DestReg = X86::RAX; break;
16830 case X86::DX: DestReg = X86::RDX; break;
16831 case X86::CX: DestReg = X86::RCX; break;
16832 case X86::BX: DestReg = X86::RBX; break;
16833 case X86::SI: DestReg = X86::RSI; break;
16834 case X86::DI: DestReg = X86::RDI; break;
16835 case X86::BP: DestReg = X86::RBP; break;
16836 case X86::SP: DestReg = X86::RSP; break;
16839 Res.first = DestReg;
16840 Res.second = &X86::GR64RegClass;
16843 } else if (Res.second == &X86::FR32RegClass ||
16844 Res.second == &X86::FR64RegClass ||
16845 Res.second == &X86::VR128RegClass) {
16846 // Handle references to XMM physical registers that got mapped into the
16847 // wrong class. This can happen with constraints like {xmm0} where the
16848 // target independent register mapper will just pick the first match it can
16849 // find, ignoring the required type.
16851 if (VT == MVT::f32 || VT == MVT::i32)
16852 Res.second = &X86::FR32RegClass;
16853 else if (VT == MVT::f64 || VT == MVT::i64)
16854 Res.second = &X86::FR64RegClass;
16855 else if (X86::VR128RegClass.hasType(VT))
16856 Res.second = &X86::VR128RegClass;
16857 else if (X86::VR256RegClass.hasType(VT))
16858 Res.second = &X86::VR256RegClass;