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::f64 , Expand);
651 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
653 addLegalFPImmediate(APFloat(+0.0)); // FLD0
654 addLegalFPImmediate(APFloat(+1.0)); // FLD1
655 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
656 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
657 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
658 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
659 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
660 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
663 // We don't support FMA.
664 setOperationAction(ISD::FMA, MVT::f64, Expand);
665 setOperationAction(ISD::FMA, MVT::f32, Expand);
667 // Long double always uses X87.
668 if (!TM.Options.UseSoftFloat) {
669 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
670 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
671 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
673 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
674 addLegalFPImmediate(TmpFlt); // FLD0
676 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
679 APFloat TmpFlt2(+1.0);
680 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
682 addLegalFPImmediate(TmpFlt2); // FLD1
683 TmpFlt2.changeSign();
684 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
687 if (!TM.Options.UnsafeFPMath) {
688 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
689 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
692 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
693 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
694 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
695 setOperationAction(ISD::FRINT, MVT::f80, Expand);
696 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
697 setOperationAction(ISD::FMA, MVT::f80, Expand);
700 // Always use a library call for pow.
701 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
702 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
703 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
705 setOperationAction(ISD::FLOG, MVT::f80, Expand);
706 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
707 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
708 setOperationAction(ISD::FEXP, MVT::f80, Expand);
709 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
711 // First set operation action for all vector types to either promote
712 // (for widening) or expand (for scalarization). Then we will selectively
713 // turn on ones that can be effectively codegen'd.
714 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
715 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
716 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
731 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
733 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
734 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
770 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
775 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
776 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
777 setTruncStoreAction((MVT::SimpleValueType)VT,
778 (MVT::SimpleValueType)InnerVT, Expand);
779 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
781 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
784 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
785 // with -msoft-float, disable use of MMX as well.
786 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
787 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
788 // No operations on x86mmx supported, everything uses intrinsics.
791 // MMX-sized vectors (other than x86mmx) are expected to be expanded
792 // into smaller operations.
793 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
794 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
795 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
796 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
797 setOperationAction(ISD::AND, MVT::v8i8, Expand);
798 setOperationAction(ISD::AND, MVT::v4i16, Expand);
799 setOperationAction(ISD::AND, MVT::v2i32, Expand);
800 setOperationAction(ISD::AND, MVT::v1i64, Expand);
801 setOperationAction(ISD::OR, MVT::v8i8, Expand);
802 setOperationAction(ISD::OR, MVT::v4i16, Expand);
803 setOperationAction(ISD::OR, MVT::v2i32, Expand);
804 setOperationAction(ISD::OR, MVT::v1i64, Expand);
805 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
806 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
807 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
808 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
810 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
813 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
814 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
815 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
816 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
817 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
818 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
819 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
820 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
821 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
823 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
824 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
826 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
827 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
828 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
829 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
831 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
832 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
833 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
834 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
835 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
836 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
837 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
840 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
841 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
843 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
844 // registers cannot be used even for integer operations.
845 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
846 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
847 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
848 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
850 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
851 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
852 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
853 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
854 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
855 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
856 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
857 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
858 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
859 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
860 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
861 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
862 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
863 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
864 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
865 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
866 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
868 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
869 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
870 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
871 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
873 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
874 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
877 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
879 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881 MVT VT = (MVT::SimpleValueType)i;
882 // Do not attempt to custom lower non-power-of-2 vectors
883 if (!isPowerOf2_32(VT.getVectorNumElements()))
885 // Do not attempt to custom lower non-128-bit vectors
886 if (!VT.is128BitVector())
888 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
889 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
890 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
893 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
895 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
900 if (Subtarget->is64Bit()) {
901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
902 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
905 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907 MVT VT = (MVT::SimpleValueType)i;
909 // Do not attempt to promote non-128-bit vectors
910 if (!VT.is128BitVector())
913 setOperationAction(ISD::AND, VT, Promote);
914 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
915 setOperationAction(ISD::OR, VT, Promote);
916 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
917 setOperationAction(ISD::XOR, VT, Promote);
918 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
919 setOperationAction(ISD::LOAD, VT, Promote);
920 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
921 setOperationAction(ISD::SELECT, VT, Promote);
922 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
925 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
927 // Custom lower v2i64 and v2f64 selects.
928 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
929 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
930 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
931 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
933 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
934 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
936 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
939 if (Subtarget->hasSSE41()) {
940 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
941 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
942 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
943 setOperationAction(ISD::FRINT, MVT::f32, Legal);
944 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
945 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
946 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
947 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
948 setOperationAction(ISD::FRINT, MVT::f64, Legal);
949 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
951 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
952 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
954 // FIXME: Do we need to handle scalar-to-vector here?
955 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
957 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
958 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
959 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
960 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
961 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
963 // i8 and i16 vectors are custom , because the source register and source
964 // source memory operand types are not the same width. f32 vectors are
965 // custom since the immediate controlling the insert encodes additional
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
974 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
975 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
977 // FIXME: these should be Legal but thats only for the case where
978 // the index is constant. For now custom expand to deal with that.
979 if (Subtarget->is64Bit()) {
980 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
985 if (Subtarget->hasSSE2()) {
986 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
987 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
989 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
990 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
992 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
993 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
995 if (Subtarget->hasAVX2()) {
996 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
997 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
999 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1000 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1002 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1004 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1005 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1007 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1008 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1010 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1014 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1015 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1016 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1017 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1018 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1019 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1020 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1022 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1023 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1024 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1026 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1027 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1028 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1029 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1030 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1031 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1032 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1033 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1035 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1036 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1037 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1038 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1039 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1040 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1041 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1042 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1044 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1045 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1046 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1048 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1050 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1051 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1053 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1054 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1056 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1057 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1059 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1060 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1061 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1062 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1064 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1065 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1066 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1068 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1073 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1074 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1075 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1076 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1077 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1078 setOperationAction(ISD::FMA, MVT::f32, Custom);
1079 setOperationAction(ISD::FMA, MVT::f64, Custom);
1082 if (Subtarget->hasAVX2()) {
1083 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1084 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1085 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1086 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1088 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1089 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1090 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1091 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1093 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1094 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1095 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1096 // Don't lower v32i8 because there is no 128-bit byte mul
1098 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1100 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1101 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1103 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1104 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1106 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1108 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1109 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1110 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1111 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1113 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1114 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1115 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1116 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1118 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1119 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1120 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1121 // Don't lower v32i8 because there is no 128-bit byte mul
1123 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1124 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1126 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1127 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1129 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1132 // Custom lower several nodes for 256-bit types.
1133 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1134 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1135 MVT VT = (MVT::SimpleValueType)i;
1137 // Extract subvector is special because the value type
1138 // (result) is 128-bit but the source is 256-bit wide.
1139 if (VT.is128BitVector())
1140 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1142 // Do not attempt to custom lower other non-256-bit vectors
1143 if (!VT.is256BitVector())
1146 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1147 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1148 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1149 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1150 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1151 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1152 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1155 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1156 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1157 MVT VT = (MVT::SimpleValueType)i;
1159 // Do not attempt to promote non-256-bit vectors
1160 if (!VT.is256BitVector())
1163 setOperationAction(ISD::AND, VT, Promote);
1164 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1165 setOperationAction(ISD::OR, VT, Promote);
1166 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1167 setOperationAction(ISD::XOR, VT, Promote);
1168 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1169 setOperationAction(ISD::LOAD, VT, Promote);
1170 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1171 setOperationAction(ISD::SELECT, VT, Promote);
1172 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1176 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1177 // of this type with custom code.
1178 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1179 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1180 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1184 // We want to custom lower some of our intrinsics.
1185 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1186 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1189 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1190 // handle type legalization for these operations here.
1192 // FIXME: We really should do custom legalization for addition and
1193 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1194 // than generic legalization for 64-bit multiplication-with-overflow, though.
1195 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1196 // Add/Sub/Mul with overflow operations are custom lowered.
1198 setOperationAction(ISD::SADDO, VT, Custom);
1199 setOperationAction(ISD::UADDO, VT, Custom);
1200 setOperationAction(ISD::SSUBO, VT, Custom);
1201 setOperationAction(ISD::USUBO, VT, Custom);
1202 setOperationAction(ISD::SMULO, VT, Custom);
1203 setOperationAction(ISD::UMULO, VT, Custom);
1206 // There are no 8-bit 3-address imul/mul instructions
1207 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1208 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1210 if (!Subtarget->is64Bit()) {
1211 // These libcalls are not available in 32-bit.
1212 setLibcallName(RTLIB::SHL_I128, 0);
1213 setLibcallName(RTLIB::SRL_I128, 0);
1214 setLibcallName(RTLIB::SRA_I128, 0);
1217 // We have target-specific dag combine patterns for the following nodes:
1218 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1219 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1220 setTargetDAGCombine(ISD::VSELECT);
1221 setTargetDAGCombine(ISD::SELECT);
1222 setTargetDAGCombine(ISD::SHL);
1223 setTargetDAGCombine(ISD::SRA);
1224 setTargetDAGCombine(ISD::SRL);
1225 setTargetDAGCombine(ISD::OR);
1226 setTargetDAGCombine(ISD::AND);
1227 setTargetDAGCombine(ISD::ADD);
1228 setTargetDAGCombine(ISD::FADD);
1229 setTargetDAGCombine(ISD::FSUB);
1230 setTargetDAGCombine(ISD::FMA);
1231 setTargetDAGCombine(ISD::SUB);
1232 setTargetDAGCombine(ISD::LOAD);
1233 setTargetDAGCombine(ISD::STORE);
1234 setTargetDAGCombine(ISD::ZERO_EXTEND);
1235 setTargetDAGCombine(ISD::ANY_EXTEND);
1236 setTargetDAGCombine(ISD::SIGN_EXTEND);
1237 setTargetDAGCombine(ISD::TRUNCATE);
1238 setTargetDAGCombine(ISD::UINT_TO_FP);
1239 setTargetDAGCombine(ISD::SINT_TO_FP);
1240 setTargetDAGCombine(ISD::SETCC);
1241 setTargetDAGCombine(ISD::FP_TO_SINT);
1242 if (Subtarget->is64Bit())
1243 setTargetDAGCombine(ISD::MUL);
1244 setTargetDAGCombine(ISD::XOR);
1246 computeRegisterProperties();
1248 // On Darwin, -Os means optimize for size without hurting performance,
1249 // do not reduce the limit.
1250 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1251 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1252 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1253 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1254 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1255 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1256 setPrefLoopAlignment(4); // 2^4 bytes.
1257 benefitFromCodePlacementOpt = true;
1259 // Predictable cmov don't hurt on atom because it's in-order.
1260 predictableSelectIsExpensive = !Subtarget->isAtom();
1262 setPrefFunctionAlignment(4); // 2^4 bytes.
1266 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1267 if (!VT.isVector()) return MVT::i8;
1268 return VT.changeVectorElementTypeToInteger();
1272 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1273 /// the desired ByVal argument alignment.
1274 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1277 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1278 if (VTy->getBitWidth() == 128)
1280 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1281 unsigned EltAlign = 0;
1282 getMaxByValAlign(ATy->getElementType(), EltAlign);
1283 if (EltAlign > MaxAlign)
1284 MaxAlign = EltAlign;
1285 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1286 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1287 unsigned EltAlign = 0;
1288 getMaxByValAlign(STy->getElementType(i), EltAlign);
1289 if (EltAlign > MaxAlign)
1290 MaxAlign = EltAlign;
1297 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1298 /// function arguments in the caller parameter area. For X86, aggregates
1299 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1300 /// are at 4-byte boundaries.
1301 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1302 if (Subtarget->is64Bit()) {
1303 // Max of 8 and alignment of type.
1304 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1311 if (Subtarget->hasSSE1())
1312 getMaxByValAlign(Ty, Align);
1316 /// getOptimalMemOpType - Returns the target specific optimal type for load
1317 /// and store operations as a result of memset, memcpy, and memmove
1318 /// lowering. If DstAlign is zero that means it's safe to destination
1319 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1320 /// means there isn't a need to check it against alignment requirement,
1321 /// probably because the source does not need to be loaded. If
1322 /// 'IsZeroVal' is true, that means it's safe to return a
1323 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1324 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1325 /// constant so it does not need to be loaded.
1326 /// It returns EVT::Other if the type should be determined using generic
1327 /// target-independent logic.
1329 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1330 unsigned DstAlign, unsigned SrcAlign,
1333 MachineFunction &MF) const {
1334 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1335 // linux. This is because the stack realignment code can't handle certain
1336 // cases like PR2962. This should be removed when PR2962 is fixed.
1337 const Function *F = MF.getFunction();
1339 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1341 (Subtarget->isUnalignedMemAccessFast() ||
1342 ((DstAlign == 0 || DstAlign >= 16) &&
1343 (SrcAlign == 0 || SrcAlign >= 16))) &&
1344 Subtarget->getStackAlignment() >= 16) {
1345 if (Subtarget->getStackAlignment() >= 32) {
1346 if (Subtarget->hasAVX2())
1348 if (Subtarget->hasAVX())
1351 if (Subtarget->hasSSE2())
1353 if (Subtarget->hasSSE1())
1355 } else if (!MemcpyStrSrc && Size >= 8 &&
1356 !Subtarget->is64Bit() &&
1357 Subtarget->getStackAlignment() >= 8 &&
1358 Subtarget->hasSSE2()) {
1359 // Do not use f64 to lower memcpy if source is string constant. It's
1360 // better to use i32 to avoid the loads.
1364 if (Subtarget->is64Bit() && Size >= 8)
1369 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1370 /// current function. The returned value is a member of the
1371 /// MachineJumpTableInfo::JTEntryKind enum.
1372 unsigned X86TargetLowering::getJumpTableEncoding() const {
1373 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1375 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1376 Subtarget->isPICStyleGOT())
1377 return MachineJumpTableInfo::EK_Custom32;
1379 // Otherwise, use the normal jump table encoding heuristics.
1380 return TargetLowering::getJumpTableEncoding();
1384 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1385 const MachineBasicBlock *MBB,
1386 unsigned uid,MCContext &Ctx) const{
1387 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1388 Subtarget->isPICStyleGOT());
1389 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1391 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1392 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1395 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1397 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1398 SelectionDAG &DAG) const {
1399 if (!Subtarget->is64Bit())
1400 // This doesn't have DebugLoc associated with it, but is not really the
1401 // same as a Register.
1402 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1406 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1407 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1409 const MCExpr *X86TargetLowering::
1410 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1411 MCContext &Ctx) const {
1412 // X86-64 uses RIP relative addressing based on the jump table label.
1413 if (Subtarget->isPICStyleRIPRel())
1414 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1416 // Otherwise, the reference is relative to the PIC base.
1417 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1420 // FIXME: Why this routine is here? Move to RegInfo!
1421 std::pair<const TargetRegisterClass*, uint8_t>
1422 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1423 const TargetRegisterClass *RRC = 0;
1425 switch (VT.getSimpleVT().SimpleTy) {
1427 return TargetLowering::findRepresentativeClass(VT);
1428 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1429 RRC = Subtarget->is64Bit() ?
1430 (const TargetRegisterClass*)&X86::GR64RegClass :
1431 (const TargetRegisterClass*)&X86::GR32RegClass;
1434 RRC = &X86::VR64RegClass;
1436 case MVT::f32: case MVT::f64:
1437 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1438 case MVT::v4f32: case MVT::v2f64:
1439 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1441 RRC = &X86::VR128RegClass;
1444 return std::make_pair(RRC, Cost);
1447 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1448 unsigned &Offset) const {
1449 if (!Subtarget->isTargetLinux())
1452 if (Subtarget->is64Bit()) {
1453 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1455 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1468 //===----------------------------------------------------------------------===//
1469 // Return Value Calling Convention Implementation
1470 //===----------------------------------------------------------------------===//
1472 #include "X86GenCallingConv.inc"
1475 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1476 MachineFunction &MF, bool isVarArg,
1477 const SmallVectorImpl<ISD::OutputArg> &Outs,
1478 LLVMContext &Context) const {
1479 SmallVector<CCValAssign, 16> RVLocs;
1480 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1482 return CCInfo.CheckReturn(Outs, RetCC_X86);
1486 X86TargetLowering::LowerReturn(SDValue Chain,
1487 CallingConv::ID CallConv, bool isVarArg,
1488 const SmallVectorImpl<ISD::OutputArg> &Outs,
1489 const SmallVectorImpl<SDValue> &OutVals,
1490 DebugLoc dl, SelectionDAG &DAG) const {
1491 MachineFunction &MF = DAG.getMachineFunction();
1492 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1494 SmallVector<CCValAssign, 16> RVLocs;
1495 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1496 RVLocs, *DAG.getContext());
1497 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1499 // Add the regs to the liveout set for the function.
1500 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1501 for (unsigned i = 0; i != RVLocs.size(); ++i)
1502 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1503 MRI.addLiveOut(RVLocs[i].getLocReg());
1507 SmallVector<SDValue, 6> RetOps;
1508 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1509 // Operand #1 = Bytes To Pop
1510 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1513 // Copy the result values into the output registers.
1514 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1515 CCValAssign &VA = RVLocs[i];
1516 assert(VA.isRegLoc() && "Can only return in registers!");
1517 SDValue ValToCopy = OutVals[i];
1518 EVT ValVT = ValToCopy.getValueType();
1520 // Promote values to the appropriate types
1521 if (VA.getLocInfo() == CCValAssign::SExt)
1522 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1523 else if (VA.getLocInfo() == CCValAssign::ZExt)
1524 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1525 else if (VA.getLocInfo() == CCValAssign::AExt)
1526 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1527 else if (VA.getLocInfo() == CCValAssign::BCvt)
1528 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1530 // If this is x86-64, and we disabled SSE, we can't return FP values,
1531 // or SSE or MMX vectors.
1532 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1533 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1534 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1535 report_fatal_error("SSE register return with SSE disabled");
1537 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1538 // llvm-gcc has never done it right and no one has noticed, so this
1539 // should be OK for now.
1540 if (ValVT == MVT::f64 &&
1541 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1542 report_fatal_error("SSE2 register return with SSE2 disabled");
1544 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1545 // the RET instruction and handled by the FP Stackifier.
1546 if (VA.getLocReg() == X86::ST0 ||
1547 VA.getLocReg() == X86::ST1) {
1548 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1549 // change the value to the FP stack register class.
1550 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1551 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1552 RetOps.push_back(ValToCopy);
1553 // Don't emit a copytoreg.
1557 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1558 // which is returned in RAX / RDX.
1559 if (Subtarget->is64Bit()) {
1560 if (ValVT == MVT::x86mmx) {
1561 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1562 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1563 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1565 // If we don't have SSE2 available, convert to v4f32 so the generated
1566 // register is legal.
1567 if (!Subtarget->hasSSE2())
1568 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1573 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1574 Flag = Chain.getValue(1);
1577 // The x86-64 ABI for returning structs by value requires that we copy
1578 // the sret argument into %rax for the return. We saved the argument into
1579 // a virtual register in the entry block, so now we copy the value out
1581 if (Subtarget->is64Bit() &&
1582 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1583 MachineFunction &MF = DAG.getMachineFunction();
1584 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1585 unsigned Reg = FuncInfo->getSRetReturnReg();
1587 "SRetReturnReg should have been set in LowerFormalArguments().");
1588 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1590 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1591 Flag = Chain.getValue(1);
1593 // RAX now acts like a return value.
1594 MRI.addLiveOut(X86::RAX);
1597 RetOps[0] = Chain; // Update chain.
1599 // Add the flag if we have it.
1601 RetOps.push_back(Flag);
1603 return DAG.getNode(X86ISD::RET_FLAG, dl,
1604 MVT::Other, &RetOps[0], RetOps.size());
1607 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1608 if (N->getNumValues() != 1)
1610 if (!N->hasNUsesOfValue(1, 0))
1613 SDValue TCChain = Chain;
1614 SDNode *Copy = *N->use_begin();
1615 if (Copy->getOpcode() == ISD::CopyToReg) {
1616 // If the copy has a glue operand, we conservatively assume it isn't safe to
1617 // perform a tail call.
1618 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1620 TCChain = Copy->getOperand(0);
1621 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1624 bool HasRet = false;
1625 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1627 if (UI->getOpcode() != X86ISD::RET_FLAG)
1640 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1641 ISD::NodeType ExtendKind) const {
1643 // TODO: Is this also valid on 32-bit?
1644 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1645 ReturnMVT = MVT::i8;
1647 ReturnMVT = MVT::i32;
1649 EVT MinVT = getRegisterType(Context, ReturnMVT);
1650 return VT.bitsLT(MinVT) ? MinVT : VT;
1653 /// LowerCallResult - Lower the result values of a call into the
1654 /// appropriate copies out of appropriate physical registers.
1657 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1658 CallingConv::ID CallConv, bool isVarArg,
1659 const SmallVectorImpl<ISD::InputArg> &Ins,
1660 DebugLoc dl, SelectionDAG &DAG,
1661 SmallVectorImpl<SDValue> &InVals) const {
1663 // Assign locations to each value returned by this call.
1664 SmallVector<CCValAssign, 16> RVLocs;
1665 bool Is64Bit = Subtarget->is64Bit();
1666 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1667 getTargetMachine(), RVLocs, *DAG.getContext());
1668 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1670 // Copy all of the result registers out of their specified physreg.
1671 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1672 CCValAssign &VA = RVLocs[i];
1673 EVT CopyVT = VA.getValVT();
1675 // If this is x86-64, and we disabled SSE, we can't return FP values
1676 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1677 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1678 report_fatal_error("SSE register return with SSE disabled");
1683 // If this is a call to a function that returns an fp value on the floating
1684 // point stack, we must guarantee the value is popped from the stack, so
1685 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1686 // if the return value is not used. We use the FpPOP_RETVAL instruction
1688 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1689 // If we prefer to use the value in xmm registers, copy it out as f80 and
1690 // use a truncate to move it from fp stack reg to xmm reg.
1691 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1692 SDValue Ops[] = { Chain, InFlag };
1693 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1694 MVT::Other, MVT::Glue, Ops, 2), 1);
1695 Val = Chain.getValue(0);
1697 // Round the f80 to the right size, which also moves it to the appropriate
1699 if (CopyVT != VA.getValVT())
1700 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1701 // This truncation won't change the value.
1702 DAG.getIntPtrConstant(1));
1704 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1705 CopyVT, InFlag).getValue(1);
1706 Val = Chain.getValue(0);
1708 InFlag = Chain.getValue(2);
1709 InVals.push_back(Val);
1716 //===----------------------------------------------------------------------===//
1717 // C & StdCall & Fast Calling Convention implementation
1718 //===----------------------------------------------------------------------===//
1719 // StdCall calling convention seems to be standard for many Windows' API
1720 // routines and around. It differs from C calling convention just a little:
1721 // callee should clean up the stack, not caller. Symbols should be also
1722 // decorated in some fancy way :) It doesn't support any vector arguments.
1723 // For info on fast calling convention see Fast Calling Convention (tail call)
1724 // implementation LowerX86_32FastCCCallTo.
1726 /// CallIsStructReturn - Determines whether a call uses struct return
1728 enum StructReturnType {
1733 static StructReturnType
1734 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1736 return NotStructReturn;
1738 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1739 if (!Flags.isSRet())
1740 return NotStructReturn;
1741 if (Flags.isInReg())
1742 return RegStructReturn;
1743 return StackStructReturn;
1746 /// ArgsAreStructReturn - Determines whether a function uses struct
1747 /// return semantics.
1748 static StructReturnType
1749 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1751 return NotStructReturn;
1753 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1754 if (!Flags.isSRet())
1755 return NotStructReturn;
1756 if (Flags.isInReg())
1757 return RegStructReturn;
1758 return StackStructReturn;
1761 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1762 /// by "Src" to address "Dst" with size and alignment information specified by
1763 /// the specific parameter attribute. The copy will be passed as a byval
1764 /// function parameter.
1766 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1767 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1769 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1771 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1772 /*isVolatile*/false, /*AlwaysInline=*/true,
1773 MachinePointerInfo(), MachinePointerInfo());
1776 /// IsTailCallConvention - Return true if the calling convention is one that
1777 /// supports tail call optimization.
1778 static bool IsTailCallConvention(CallingConv::ID CC) {
1779 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1782 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1783 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1787 CallingConv::ID CalleeCC = CS.getCallingConv();
1788 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1794 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1795 /// a tailcall target by changing its ABI.
1796 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1797 bool GuaranteedTailCallOpt) {
1798 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1802 X86TargetLowering::LowerMemArgument(SDValue Chain,
1803 CallingConv::ID CallConv,
1804 const SmallVectorImpl<ISD::InputArg> &Ins,
1805 DebugLoc dl, SelectionDAG &DAG,
1806 const CCValAssign &VA,
1807 MachineFrameInfo *MFI,
1809 // Create the nodes corresponding to a load from this parameter slot.
1810 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1811 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1812 getTargetMachine().Options.GuaranteedTailCallOpt);
1813 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1816 // If value is passed by pointer we have address passed instead of the value
1818 if (VA.getLocInfo() == CCValAssign::Indirect)
1819 ValVT = VA.getLocVT();
1821 ValVT = VA.getValVT();
1823 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1824 // changed with more analysis.
1825 // In case of tail call optimization mark all arguments mutable. Since they
1826 // could be overwritten by lowering of arguments in case of a tail call.
1827 if (Flags.isByVal()) {
1828 unsigned Bytes = Flags.getByValSize();
1829 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1830 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1831 return DAG.getFrameIndex(FI, getPointerTy());
1833 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1834 VA.getLocMemOffset(), isImmutable);
1835 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1836 return DAG.getLoad(ValVT, dl, Chain, FIN,
1837 MachinePointerInfo::getFixedStack(FI),
1838 false, false, false, 0);
1843 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1844 CallingConv::ID CallConv,
1846 const SmallVectorImpl<ISD::InputArg> &Ins,
1849 SmallVectorImpl<SDValue> &InVals)
1851 MachineFunction &MF = DAG.getMachineFunction();
1852 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1854 const Function* Fn = MF.getFunction();
1855 if (Fn->hasExternalLinkage() &&
1856 Subtarget->isTargetCygMing() &&
1857 Fn->getName() == "main")
1858 FuncInfo->setForceFramePointer(true);
1860 MachineFrameInfo *MFI = MF.getFrameInfo();
1861 bool Is64Bit = Subtarget->is64Bit();
1862 bool IsWindows = Subtarget->isTargetWindows();
1863 bool IsWin64 = Subtarget->isTargetWin64();
1865 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1866 "Var args not supported with calling convention fastcc or ghc");
1868 // Assign locations to all of the incoming arguments.
1869 SmallVector<CCValAssign, 16> ArgLocs;
1870 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1871 ArgLocs, *DAG.getContext());
1873 // Allocate shadow area for Win64
1875 CCInfo.AllocateStack(32, 8);
1878 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1880 unsigned LastVal = ~0U;
1882 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1883 CCValAssign &VA = ArgLocs[i];
1884 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1886 assert(VA.getValNo() != LastVal &&
1887 "Don't support value assigned to multiple locs yet");
1889 LastVal = VA.getValNo();
1891 if (VA.isRegLoc()) {
1892 EVT RegVT = VA.getLocVT();
1893 const TargetRegisterClass *RC;
1894 if (RegVT == MVT::i32)
1895 RC = &X86::GR32RegClass;
1896 else if (Is64Bit && RegVT == MVT::i64)
1897 RC = &X86::GR64RegClass;
1898 else if (RegVT == MVT::f32)
1899 RC = &X86::FR32RegClass;
1900 else if (RegVT == MVT::f64)
1901 RC = &X86::FR64RegClass;
1902 else if (RegVT.is256BitVector())
1903 RC = &X86::VR256RegClass;
1904 else if (RegVT.is128BitVector())
1905 RC = &X86::VR128RegClass;
1906 else if (RegVT == MVT::x86mmx)
1907 RC = &X86::VR64RegClass;
1909 llvm_unreachable("Unknown argument type!");
1911 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1912 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1914 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1915 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1917 if (VA.getLocInfo() == CCValAssign::SExt)
1918 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1919 DAG.getValueType(VA.getValVT()));
1920 else if (VA.getLocInfo() == CCValAssign::ZExt)
1921 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1922 DAG.getValueType(VA.getValVT()));
1923 else if (VA.getLocInfo() == CCValAssign::BCvt)
1924 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1926 if (VA.isExtInLoc()) {
1927 // Handle MMX values passed in XMM regs.
1928 if (RegVT.isVector()) {
1929 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1932 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1935 assert(VA.isMemLoc());
1936 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1939 // If value is passed via pointer - do a load.
1940 if (VA.getLocInfo() == CCValAssign::Indirect)
1941 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1942 MachinePointerInfo(), false, false, false, 0);
1944 InVals.push_back(ArgValue);
1947 // The x86-64 ABI for returning structs by value requires that we copy
1948 // the sret argument into %rax for the return. Save the argument into
1949 // a virtual register so that we can access it from the return points.
1950 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1951 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1952 unsigned Reg = FuncInfo->getSRetReturnReg();
1954 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1955 FuncInfo->setSRetReturnReg(Reg);
1957 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1958 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1961 unsigned StackSize = CCInfo.getNextStackOffset();
1962 // Align stack specially for tail calls.
1963 if (FuncIsMadeTailCallSafe(CallConv,
1964 MF.getTarget().Options.GuaranteedTailCallOpt))
1965 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1967 // If the function takes variable number of arguments, make a frame index for
1968 // the start of the first vararg value... for expansion of llvm.va_start.
1970 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1971 CallConv != CallingConv::X86_ThisCall)) {
1972 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1975 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1977 // FIXME: We should really autogenerate these arrays
1978 static const uint16_t GPR64ArgRegsWin64[] = {
1979 X86::RCX, X86::RDX, X86::R8, X86::R9
1981 static const uint16_t GPR64ArgRegs64Bit[] = {
1982 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1984 static const uint16_t XMMArgRegs64Bit[] = {
1985 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1986 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1988 const uint16_t *GPR64ArgRegs;
1989 unsigned NumXMMRegs = 0;
1992 // The XMM registers which might contain var arg parameters are shadowed
1993 // in their paired GPR. So we only need to save the GPR to their home
1995 TotalNumIntRegs = 4;
1996 GPR64ArgRegs = GPR64ArgRegsWin64;
1998 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1999 GPR64ArgRegs = GPR64ArgRegs64Bit;
2001 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2004 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2007 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2008 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2009 "SSE register cannot be used when SSE is disabled!");
2010 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2011 NoImplicitFloatOps) &&
2012 "SSE register cannot be used when SSE is disabled!");
2013 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2014 !Subtarget->hasSSE1())
2015 // Kernel mode asks for SSE to be disabled, so don't push them
2017 TotalNumXMMRegs = 0;
2020 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2021 // Get to the caller-allocated home save location. Add 8 to account
2022 // for the return address.
2023 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2024 FuncInfo->setRegSaveFrameIndex(
2025 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2026 // Fixup to set vararg frame on shadow area (4 x i64).
2028 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2030 // For X86-64, if there are vararg parameters that are passed via
2031 // registers, then we must store them to their spots on the stack so
2032 // they may be loaded by deferencing the result of va_next.
2033 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2034 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2035 FuncInfo->setRegSaveFrameIndex(
2036 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2040 // Store the integer parameter registers.
2041 SmallVector<SDValue, 8> MemOps;
2042 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2044 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2045 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2046 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2047 DAG.getIntPtrConstant(Offset));
2048 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2049 &X86::GR64RegClass);
2050 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2052 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2053 MachinePointerInfo::getFixedStack(
2054 FuncInfo->getRegSaveFrameIndex(), Offset),
2056 MemOps.push_back(Store);
2060 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2061 // Now store the XMM (fp + vector) parameter registers.
2062 SmallVector<SDValue, 11> SaveXMMOps;
2063 SaveXMMOps.push_back(Chain);
2065 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2066 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2067 SaveXMMOps.push_back(ALVal);
2069 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2070 FuncInfo->getRegSaveFrameIndex()));
2071 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2072 FuncInfo->getVarArgsFPOffset()));
2074 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2075 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2076 &X86::VR128RegClass);
2077 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2078 SaveXMMOps.push_back(Val);
2080 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2082 &SaveXMMOps[0], SaveXMMOps.size()));
2085 if (!MemOps.empty())
2086 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2087 &MemOps[0], MemOps.size());
2091 // Some CCs need callee pop.
2092 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2093 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2094 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2096 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2097 // If this is an sret function, the return should pop the hidden pointer.
2098 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2099 argsAreStructReturn(Ins) == StackStructReturn)
2100 FuncInfo->setBytesToPopOnReturn(4);
2104 // RegSaveFrameIndex is X86-64 only.
2105 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2106 if (CallConv == CallingConv::X86_FastCall ||
2107 CallConv == CallingConv::X86_ThisCall)
2108 // fastcc functions can't have varargs.
2109 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2112 FuncInfo->setArgumentStackSize(StackSize);
2118 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2119 SDValue StackPtr, SDValue Arg,
2120 DebugLoc dl, SelectionDAG &DAG,
2121 const CCValAssign &VA,
2122 ISD::ArgFlagsTy Flags) const {
2123 unsigned LocMemOffset = VA.getLocMemOffset();
2124 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2125 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2126 if (Flags.isByVal())
2127 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2129 return DAG.getStore(Chain, dl, Arg, PtrOff,
2130 MachinePointerInfo::getStack(LocMemOffset),
2134 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2135 /// optimization is performed and it is required.
2137 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2138 SDValue &OutRetAddr, SDValue Chain,
2139 bool IsTailCall, bool Is64Bit,
2140 int FPDiff, DebugLoc dl) const {
2141 // Adjust the Return address stack slot.
2142 EVT VT = getPointerTy();
2143 OutRetAddr = getReturnAddressFrameIndex(DAG);
2145 // Load the "old" Return address.
2146 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2147 false, false, false, 0);
2148 return SDValue(OutRetAddr.getNode(), 1);
2151 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2152 /// optimization is performed and it is required (FPDiff!=0).
2154 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2155 SDValue Chain, SDValue RetAddrFrIdx,
2156 bool Is64Bit, int FPDiff, DebugLoc dl) {
2157 // Store the return address to the appropriate stack slot.
2158 if (!FPDiff) return Chain;
2159 // Calculate the new stack slot for the return address.
2160 int SlotSize = Is64Bit ? 8 : 4;
2161 int NewReturnAddrFI =
2162 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2163 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2164 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2165 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2166 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2172 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2173 SmallVectorImpl<SDValue> &InVals) const {
2174 SelectionDAG &DAG = CLI.DAG;
2175 DebugLoc &dl = CLI.DL;
2176 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2177 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2178 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2179 SDValue Chain = CLI.Chain;
2180 SDValue Callee = CLI.Callee;
2181 CallingConv::ID CallConv = CLI.CallConv;
2182 bool &isTailCall = CLI.IsTailCall;
2183 bool isVarArg = CLI.IsVarArg;
2185 MachineFunction &MF = DAG.getMachineFunction();
2186 bool Is64Bit = Subtarget->is64Bit();
2187 bool IsWin64 = Subtarget->isTargetWin64();
2188 bool IsWindows = Subtarget->isTargetWindows();
2189 StructReturnType SR = callIsStructReturn(Outs);
2190 bool IsSibcall = false;
2192 if (MF.getTarget().Options.DisableTailCalls)
2196 // Check if it's really possible to do a tail call.
2197 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2198 isVarArg, SR != NotStructReturn,
2199 MF.getFunction()->hasStructRetAttr(),
2200 Outs, OutVals, Ins, DAG);
2202 // Sibcalls are automatically detected tailcalls which do not require
2204 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2211 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2212 "Var args not supported with calling convention fastcc or ghc");
2214 // Analyze operands of the call, assigning locations to each operand.
2215 SmallVector<CCValAssign, 16> ArgLocs;
2216 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2217 ArgLocs, *DAG.getContext());
2219 // Allocate shadow area for Win64
2221 CCInfo.AllocateStack(32, 8);
2224 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2226 // Get a count of how many bytes are to be pushed on the stack.
2227 unsigned NumBytes = CCInfo.getNextStackOffset();
2229 // This is a sibcall. The memory operands are available in caller's
2230 // own caller's stack.
2232 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2233 IsTailCallConvention(CallConv))
2234 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2237 if (isTailCall && !IsSibcall) {
2238 // Lower arguments at fp - stackoffset + fpdiff.
2239 unsigned NumBytesCallerPushed =
2240 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2241 FPDiff = NumBytesCallerPushed - NumBytes;
2243 // Set the delta of movement of the returnaddr stackslot.
2244 // But only set if delta is greater than previous delta.
2245 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2246 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2250 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2252 SDValue RetAddrFrIdx;
2253 // Load return address for tail calls.
2254 if (isTailCall && FPDiff)
2255 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2256 Is64Bit, FPDiff, dl);
2258 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2259 SmallVector<SDValue, 8> MemOpChains;
2262 // Walk the register/memloc assignments, inserting copies/loads. In the case
2263 // of tail call optimization arguments are handle later.
2264 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2265 CCValAssign &VA = ArgLocs[i];
2266 EVT RegVT = VA.getLocVT();
2267 SDValue Arg = OutVals[i];
2268 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2269 bool isByVal = Flags.isByVal();
2271 // Promote the value if needed.
2272 switch (VA.getLocInfo()) {
2273 default: llvm_unreachable("Unknown loc info!");
2274 case CCValAssign::Full: break;
2275 case CCValAssign::SExt:
2276 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2278 case CCValAssign::ZExt:
2279 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2281 case CCValAssign::AExt:
2282 if (RegVT.is128BitVector()) {
2283 // Special case: passing MMX values in XMM registers.
2284 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2285 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2286 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2288 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2290 case CCValAssign::BCvt:
2291 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2293 case CCValAssign::Indirect: {
2294 // Store the argument.
2295 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2296 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2297 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2298 MachinePointerInfo::getFixedStack(FI),
2305 if (VA.isRegLoc()) {
2306 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2307 if (isVarArg && IsWin64) {
2308 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2309 // shadow reg if callee is a varargs function.
2310 unsigned ShadowReg = 0;
2311 switch (VA.getLocReg()) {
2312 case X86::XMM0: ShadowReg = X86::RCX; break;
2313 case X86::XMM1: ShadowReg = X86::RDX; break;
2314 case X86::XMM2: ShadowReg = X86::R8; break;
2315 case X86::XMM3: ShadowReg = X86::R9; break;
2318 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2320 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2321 assert(VA.isMemLoc());
2322 if (StackPtr.getNode() == 0)
2323 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2324 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2325 dl, DAG, VA, Flags));
2329 if (!MemOpChains.empty())
2330 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2331 &MemOpChains[0], MemOpChains.size());
2333 if (Subtarget->isPICStyleGOT()) {
2334 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2337 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2338 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2340 // If we are tail calling and generating PIC/GOT style code load the
2341 // address of the callee into ECX. The value in ecx is used as target of
2342 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2343 // for tail calls on PIC/GOT architectures. Normally we would just put the
2344 // address of GOT into ebx and then call target@PLT. But for tail calls
2345 // ebx would be restored (since ebx is callee saved) before jumping to the
2348 // Note: The actual moving to ECX is done further down.
2349 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2350 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2351 !G->getGlobal()->hasProtectedVisibility())
2352 Callee = LowerGlobalAddress(Callee, DAG);
2353 else if (isa<ExternalSymbolSDNode>(Callee))
2354 Callee = LowerExternalSymbol(Callee, DAG);
2358 if (Is64Bit && isVarArg && !IsWin64) {
2359 // From AMD64 ABI document:
2360 // For calls that may call functions that use varargs or stdargs
2361 // (prototype-less calls or calls to functions containing ellipsis (...) in
2362 // the declaration) %al is used as hidden argument to specify the number
2363 // of SSE registers used. The contents of %al do not need to match exactly
2364 // the number of registers, but must be an ubound on the number of SSE
2365 // registers used and is in the range 0 - 8 inclusive.
2367 // Count the number of XMM registers allocated.
2368 static const uint16_t XMMArgRegs[] = {
2369 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2370 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2372 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2373 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2374 && "SSE registers cannot be used when SSE is disabled");
2376 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2377 DAG.getConstant(NumXMMRegs, MVT::i8)));
2380 // For tail calls lower the arguments to the 'real' stack slot.
2382 // Force all the incoming stack arguments to be loaded from the stack
2383 // before any new outgoing arguments are stored to the stack, because the
2384 // outgoing stack slots may alias the incoming argument stack slots, and
2385 // the alias isn't otherwise explicit. This is slightly more conservative
2386 // than necessary, because it means that each store effectively depends
2387 // on every argument instead of just those arguments it would clobber.
2388 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2390 SmallVector<SDValue, 8> MemOpChains2;
2393 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2394 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2395 CCValAssign &VA = ArgLocs[i];
2398 assert(VA.isMemLoc());
2399 SDValue Arg = OutVals[i];
2400 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2401 // Create frame index.
2402 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2403 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2404 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2405 FIN = DAG.getFrameIndex(FI, getPointerTy());
2407 if (Flags.isByVal()) {
2408 // Copy relative to framepointer.
2409 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2410 if (StackPtr.getNode() == 0)
2411 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2413 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2415 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2419 // Store relative to framepointer.
2420 MemOpChains2.push_back(
2421 DAG.getStore(ArgChain, dl, Arg, FIN,
2422 MachinePointerInfo::getFixedStack(FI),
2428 if (!MemOpChains2.empty())
2429 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2430 &MemOpChains2[0], MemOpChains2.size());
2432 // Store the return address to the appropriate stack slot.
2433 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2437 // Build a sequence of copy-to-reg nodes chained together with token chain
2438 // and flag operands which copy the outgoing args into registers.
2440 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2441 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2442 RegsToPass[i].second, InFlag);
2443 InFlag = Chain.getValue(1);
2446 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2447 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2448 // In the 64-bit large code model, we have to make all calls
2449 // through a register, since the call instruction's 32-bit
2450 // pc-relative offset may not be large enough to hold the whole
2452 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2453 // If the callee is a GlobalAddress node (quite common, every direct call
2454 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2457 // We should use extra load for direct calls to dllimported functions in
2459 const GlobalValue *GV = G->getGlobal();
2460 if (!GV->hasDLLImportLinkage()) {
2461 unsigned char OpFlags = 0;
2462 bool ExtraLoad = false;
2463 unsigned WrapperKind = ISD::DELETED_NODE;
2465 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2466 // external symbols most go through the PLT in PIC mode. If the symbol
2467 // has hidden or protected visibility, or if it is static or local, then
2468 // we don't need to use the PLT - we can directly call it.
2469 if (Subtarget->isTargetELF() &&
2470 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2471 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2472 OpFlags = X86II::MO_PLT;
2473 } else if (Subtarget->isPICStyleStubAny() &&
2474 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2475 (!Subtarget->getTargetTriple().isMacOSX() ||
2476 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2477 // PC-relative references to external symbols should go through $stub,
2478 // unless we're building with the leopard linker or later, which
2479 // automatically synthesizes these stubs.
2480 OpFlags = X86II::MO_DARWIN_STUB;
2481 } else if (Subtarget->isPICStyleRIPRel() &&
2482 isa<Function>(GV) &&
2483 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2484 // If the function is marked as non-lazy, generate an indirect call
2485 // which loads from the GOT directly. This avoids runtime overhead
2486 // at the cost of eager binding (and one extra byte of encoding).
2487 OpFlags = X86II::MO_GOTPCREL;
2488 WrapperKind = X86ISD::WrapperRIP;
2492 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2493 G->getOffset(), OpFlags);
2495 // Add a wrapper if needed.
2496 if (WrapperKind != ISD::DELETED_NODE)
2497 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2498 // Add extra indirection if needed.
2500 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2501 MachinePointerInfo::getGOT(),
2502 false, false, false, 0);
2504 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2505 unsigned char OpFlags = 0;
2507 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2508 // external symbols should go through the PLT.
2509 if (Subtarget->isTargetELF() &&
2510 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2511 OpFlags = X86II::MO_PLT;
2512 } else if (Subtarget->isPICStyleStubAny() &&
2513 (!Subtarget->getTargetTriple().isMacOSX() ||
2514 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2515 // PC-relative references to external symbols should go through $stub,
2516 // unless we're building with the leopard linker or later, which
2517 // automatically synthesizes these stubs.
2518 OpFlags = X86II::MO_DARWIN_STUB;
2521 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2525 // Returns a chain & a flag for retval copy to use.
2526 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2527 SmallVector<SDValue, 8> Ops;
2529 if (!IsSibcall && isTailCall) {
2530 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2531 DAG.getIntPtrConstant(0, true), InFlag);
2532 InFlag = Chain.getValue(1);
2535 Ops.push_back(Chain);
2536 Ops.push_back(Callee);
2539 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2541 // Add argument registers to the end of the list so that they are known live
2543 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2544 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2545 RegsToPass[i].second.getValueType()));
2547 // Add a register mask operand representing the call-preserved registers.
2548 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2549 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2550 assert(Mask && "Missing call preserved mask for calling convention");
2551 Ops.push_back(DAG.getRegisterMask(Mask));
2553 if (InFlag.getNode())
2554 Ops.push_back(InFlag);
2558 //// If this is the first return lowered for this function, add the regs
2559 //// to the liveout set for the function.
2560 // This isn't right, although it's probably harmless on x86; liveouts
2561 // should be computed from returns not tail calls. Consider a void
2562 // function making a tail call to a function returning int.
2563 return DAG.getNode(X86ISD::TC_RETURN, dl,
2564 NodeTys, &Ops[0], Ops.size());
2567 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2568 InFlag = Chain.getValue(1);
2570 // Create the CALLSEQ_END node.
2571 unsigned NumBytesForCalleeToPush;
2572 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2573 getTargetMachine().Options.GuaranteedTailCallOpt))
2574 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2575 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2576 SR == StackStructReturn)
2577 // If this is a call to a struct-return function, the callee
2578 // pops the hidden struct pointer, so we have to push it back.
2579 // This is common for Darwin/X86, Linux & Mingw32 targets.
2580 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2581 NumBytesForCalleeToPush = 4;
2583 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2585 // Returns a flag for retval copy to use.
2587 Chain = DAG.getCALLSEQ_END(Chain,
2588 DAG.getIntPtrConstant(NumBytes, true),
2589 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2592 InFlag = Chain.getValue(1);
2595 // Handle result values, copying them out of physregs into vregs that we
2597 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2598 Ins, dl, DAG, InVals);
2602 //===----------------------------------------------------------------------===//
2603 // Fast Calling Convention (tail call) implementation
2604 //===----------------------------------------------------------------------===//
2606 // Like std call, callee cleans arguments, convention except that ECX is
2607 // reserved for storing the tail called function address. Only 2 registers are
2608 // free for argument passing (inreg). Tail call optimization is performed
2610 // * tailcallopt is enabled
2611 // * caller/callee are fastcc
2612 // On X86_64 architecture with GOT-style position independent code only local
2613 // (within module) calls are supported at the moment.
2614 // To keep the stack aligned according to platform abi the function
2615 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2616 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2617 // If a tail called function callee has more arguments than the caller the
2618 // caller needs to make sure that there is room to move the RETADDR to. This is
2619 // achieved by reserving an area the size of the argument delta right after the
2620 // original REtADDR, but before the saved framepointer or the spilled registers
2621 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2633 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2634 /// for a 16 byte align requirement.
2636 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2637 SelectionDAG& DAG) const {
2638 MachineFunction &MF = DAG.getMachineFunction();
2639 const TargetMachine &TM = MF.getTarget();
2640 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2641 unsigned StackAlignment = TFI.getStackAlignment();
2642 uint64_t AlignMask = StackAlignment - 1;
2643 int64_t Offset = StackSize;
2644 uint64_t SlotSize = TD->getPointerSize();
2645 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2646 // Number smaller than 12 so just add the difference.
2647 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2649 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2650 Offset = ((~AlignMask) & Offset) + StackAlignment +
2651 (StackAlignment-SlotSize);
2656 /// MatchingStackOffset - Return true if the given stack call argument is
2657 /// already available in the same position (relatively) of the caller's
2658 /// incoming argument stack.
2660 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2661 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2662 const X86InstrInfo *TII) {
2663 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2665 if (Arg.getOpcode() == ISD::CopyFromReg) {
2666 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2667 if (!TargetRegisterInfo::isVirtualRegister(VR))
2669 MachineInstr *Def = MRI->getVRegDef(VR);
2672 if (!Flags.isByVal()) {
2673 if (!TII->isLoadFromStackSlot(Def, FI))
2676 unsigned Opcode = Def->getOpcode();
2677 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2678 Def->getOperand(1).isFI()) {
2679 FI = Def->getOperand(1).getIndex();
2680 Bytes = Flags.getByValSize();
2684 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2685 if (Flags.isByVal())
2686 // ByVal argument is passed in as a pointer but it's now being
2687 // dereferenced. e.g.
2688 // define @foo(%struct.X* %A) {
2689 // tail call @bar(%struct.X* byval %A)
2692 SDValue Ptr = Ld->getBasePtr();
2693 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2696 FI = FINode->getIndex();
2697 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2698 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2699 FI = FINode->getIndex();
2700 Bytes = Flags.getByValSize();
2704 assert(FI != INT_MAX);
2705 if (!MFI->isFixedObjectIndex(FI))
2707 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2710 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2711 /// for tail call optimization. Targets which want to do tail call
2712 /// optimization should implement this function.
2714 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2715 CallingConv::ID CalleeCC,
2717 bool isCalleeStructRet,
2718 bool isCallerStructRet,
2719 const SmallVectorImpl<ISD::OutputArg> &Outs,
2720 const SmallVectorImpl<SDValue> &OutVals,
2721 const SmallVectorImpl<ISD::InputArg> &Ins,
2722 SelectionDAG& DAG) const {
2723 if (!IsTailCallConvention(CalleeCC) &&
2724 CalleeCC != CallingConv::C)
2727 // If -tailcallopt is specified, make fastcc functions tail-callable.
2728 const MachineFunction &MF = DAG.getMachineFunction();
2729 const Function *CallerF = DAG.getMachineFunction().getFunction();
2730 CallingConv::ID CallerCC = CallerF->getCallingConv();
2731 bool CCMatch = CallerCC == CalleeCC;
2733 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2734 if (IsTailCallConvention(CalleeCC) && CCMatch)
2739 // Look for obvious safe cases to perform tail call optimization that do not
2740 // require ABI changes. This is what gcc calls sibcall.
2742 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2743 // emit a special epilogue.
2744 if (RegInfo->needsStackRealignment(MF))
2747 // Also avoid sibcall optimization if either caller or callee uses struct
2748 // return semantics.
2749 if (isCalleeStructRet || isCallerStructRet)
2752 // An stdcall caller is expected to clean up its arguments; the callee
2753 // isn't going to do that.
2754 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2757 // Do not sibcall optimize vararg calls unless all arguments are passed via
2759 if (isVarArg && !Outs.empty()) {
2761 // Optimizing for varargs on Win64 is unlikely to be safe without
2762 // additional testing.
2763 if (Subtarget->isTargetWin64())
2766 SmallVector<CCValAssign, 16> ArgLocs;
2767 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2768 getTargetMachine(), ArgLocs, *DAG.getContext());
2770 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2771 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2772 if (!ArgLocs[i].isRegLoc())
2776 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2777 // stack. Therefore, if it's not used by the call it is not safe to optimize
2778 // this into a sibcall.
2779 bool Unused = false;
2780 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2787 SmallVector<CCValAssign, 16> RVLocs;
2788 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2789 getTargetMachine(), RVLocs, *DAG.getContext());
2790 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2791 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2792 CCValAssign &VA = RVLocs[i];
2793 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2798 // If the calling conventions do not match, then we'd better make sure the
2799 // results are returned in the same way as what the caller expects.
2801 SmallVector<CCValAssign, 16> RVLocs1;
2802 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2803 getTargetMachine(), RVLocs1, *DAG.getContext());
2804 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2806 SmallVector<CCValAssign, 16> RVLocs2;
2807 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2808 getTargetMachine(), RVLocs2, *DAG.getContext());
2809 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2811 if (RVLocs1.size() != RVLocs2.size())
2813 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2814 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2816 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2818 if (RVLocs1[i].isRegLoc()) {
2819 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2822 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2828 // If the callee takes no arguments then go on to check the results of the
2830 if (!Outs.empty()) {
2831 // Check if stack adjustment is needed. For now, do not do this if any
2832 // argument is passed on the stack.
2833 SmallVector<CCValAssign, 16> ArgLocs;
2834 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2835 getTargetMachine(), ArgLocs, *DAG.getContext());
2837 // Allocate shadow area for Win64
2838 if (Subtarget->isTargetWin64()) {
2839 CCInfo.AllocateStack(32, 8);
2842 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2843 if (CCInfo.getNextStackOffset()) {
2844 MachineFunction &MF = DAG.getMachineFunction();
2845 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2848 // Check if the arguments are already laid out in the right way as
2849 // the caller's fixed stack objects.
2850 MachineFrameInfo *MFI = MF.getFrameInfo();
2851 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2852 const X86InstrInfo *TII =
2853 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2854 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855 CCValAssign &VA = ArgLocs[i];
2856 SDValue Arg = OutVals[i];
2857 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2858 if (VA.getLocInfo() == CCValAssign::Indirect)
2860 if (!VA.isRegLoc()) {
2861 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2868 // If the tailcall address may be in a register, then make sure it's
2869 // possible to register allocate for it. In 32-bit, the call address can
2870 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2871 // callee-saved registers are restored. These happen to be the same
2872 // registers used to pass 'inreg' arguments so watch out for those.
2873 if (!Subtarget->is64Bit() &&
2874 !isa<GlobalAddressSDNode>(Callee) &&
2875 !isa<ExternalSymbolSDNode>(Callee)) {
2876 unsigned NumInRegs = 0;
2877 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2878 CCValAssign &VA = ArgLocs[i];
2881 unsigned Reg = VA.getLocReg();
2884 case X86::EAX: case X86::EDX: case X86::ECX:
2885 if (++NumInRegs == 3)
2897 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2898 const TargetLibraryInfo *libInfo) const {
2899 return X86::createFastISel(funcInfo, libInfo);
2903 //===----------------------------------------------------------------------===//
2904 // Other Lowering Hooks
2905 //===----------------------------------------------------------------------===//
2907 static bool MayFoldLoad(SDValue Op) {
2908 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2911 static bool MayFoldIntoStore(SDValue Op) {
2912 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2915 static bool isTargetShuffle(unsigned Opcode) {
2917 default: return false;
2918 case X86ISD::PSHUFD:
2919 case X86ISD::PSHUFHW:
2920 case X86ISD::PSHUFLW:
2922 case X86ISD::PALIGN:
2923 case X86ISD::MOVLHPS:
2924 case X86ISD::MOVLHPD:
2925 case X86ISD::MOVHLPS:
2926 case X86ISD::MOVLPS:
2927 case X86ISD::MOVLPD:
2928 case X86ISD::MOVSHDUP:
2929 case X86ISD::MOVSLDUP:
2930 case X86ISD::MOVDDUP:
2933 case X86ISD::UNPCKL:
2934 case X86ISD::UNPCKH:
2935 case X86ISD::VPERMILP:
2936 case X86ISD::VPERM2X128:
2937 case X86ISD::VPERMI:
2942 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2943 SDValue V1, SelectionDAG &DAG) {
2945 default: llvm_unreachable("Unknown x86 shuffle node");
2946 case X86ISD::MOVSHDUP:
2947 case X86ISD::MOVSLDUP:
2948 case X86ISD::MOVDDUP:
2949 return DAG.getNode(Opc, dl, VT, V1);
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954 SDValue V1, unsigned TargetMask,
2955 SelectionDAG &DAG) {
2957 default: llvm_unreachable("Unknown x86 shuffle node");
2958 case X86ISD::PSHUFD:
2959 case X86ISD::PSHUFHW:
2960 case X86ISD::PSHUFLW:
2961 case X86ISD::VPERMILP:
2962 case X86ISD::VPERMI:
2963 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2967 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2968 SDValue V1, SDValue V2, unsigned TargetMask,
2969 SelectionDAG &DAG) {
2971 default: llvm_unreachable("Unknown x86 shuffle node");
2972 case X86ISD::PALIGN:
2974 case X86ISD::VPERM2X128:
2975 return DAG.getNode(Opc, dl, VT, V1, V2,
2976 DAG.getConstant(TargetMask, MVT::i8));
2980 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2981 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2983 default: llvm_unreachable("Unknown x86 shuffle node");
2984 case X86ISD::MOVLHPS:
2985 case X86ISD::MOVLHPD:
2986 case X86ISD::MOVHLPS:
2987 case X86ISD::MOVLPS:
2988 case X86ISD::MOVLPD:
2991 case X86ISD::UNPCKL:
2992 case X86ISD::UNPCKH:
2993 return DAG.getNode(Opc, dl, VT, V1, V2);
2997 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2998 MachineFunction &MF = DAG.getMachineFunction();
2999 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3000 int ReturnAddrIndex = FuncInfo->getRAIndex();
3002 if (ReturnAddrIndex == 0) {
3003 // Set up a frame object for the return address.
3004 uint64_t SlotSize = TD->getPointerSize();
3005 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3007 FuncInfo->setRAIndex(ReturnAddrIndex);
3010 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3014 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3015 bool hasSymbolicDisplacement) {
3016 // Offset should fit into 32 bit immediate field.
3017 if (!isInt<32>(Offset))
3020 // If we don't have a symbolic displacement - we don't have any extra
3022 if (!hasSymbolicDisplacement)
3025 // FIXME: Some tweaks might be needed for medium code model.
3026 if (M != CodeModel::Small && M != CodeModel::Kernel)
3029 // For small code model we assume that latest object is 16MB before end of 31
3030 // bits boundary. We may also accept pretty large negative constants knowing
3031 // that all objects are in the positive half of address space.
3032 if (M == CodeModel::Small && Offset < 16*1024*1024)
3035 // For kernel code model we know that all object resist in the negative half
3036 // of 32bits address space. We may not accept negative offsets, since they may
3037 // be just off and we may accept pretty large positive ones.
3038 if (M == CodeModel::Kernel && Offset > 0)
3044 /// isCalleePop - Determines whether the callee is required to pop its
3045 /// own arguments. Callee pop is necessary to support tail calls.
3046 bool X86::isCalleePop(CallingConv::ID CallingConv,
3047 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3051 switch (CallingConv) {
3054 case CallingConv::X86_StdCall:
3056 case CallingConv::X86_FastCall:
3058 case CallingConv::X86_ThisCall:
3060 case CallingConv::Fast:
3062 case CallingConv::GHC:
3067 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3068 /// specific condition code, returning the condition code and the LHS/RHS of the
3069 /// comparison to make.
3070 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3071 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3073 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3074 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3075 // X > -1 -> X == 0, jump !sign.
3076 RHS = DAG.getConstant(0, RHS.getValueType());
3077 return X86::COND_NS;
3079 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3080 // X < 0 -> X == 0, jump on sign.
3083 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3085 RHS = DAG.getConstant(0, RHS.getValueType());
3086 return X86::COND_LE;
3090 switch (SetCCOpcode) {
3091 default: llvm_unreachable("Invalid integer condition!");
3092 case ISD::SETEQ: return X86::COND_E;
3093 case ISD::SETGT: return X86::COND_G;
3094 case ISD::SETGE: return X86::COND_GE;
3095 case ISD::SETLT: return X86::COND_L;
3096 case ISD::SETLE: return X86::COND_LE;
3097 case ISD::SETNE: return X86::COND_NE;
3098 case ISD::SETULT: return X86::COND_B;
3099 case ISD::SETUGT: return X86::COND_A;
3100 case ISD::SETULE: return X86::COND_BE;
3101 case ISD::SETUGE: return X86::COND_AE;
3105 // First determine if it is required or is profitable to flip the operands.
3107 // If LHS is a foldable load, but RHS is not, flip the condition.
3108 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3109 !ISD::isNON_EXTLoad(RHS.getNode())) {
3110 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3111 std::swap(LHS, RHS);
3114 switch (SetCCOpcode) {
3120 std::swap(LHS, RHS);
3124 // On a floating point condition, the flags are set as follows:
3126 // 0 | 0 | 0 | X > Y
3127 // 0 | 0 | 1 | X < Y
3128 // 1 | 0 | 0 | X == Y
3129 // 1 | 1 | 1 | unordered
3130 switch (SetCCOpcode) {
3131 default: llvm_unreachable("Condcode should be pre-legalized away");
3133 case ISD::SETEQ: return X86::COND_E;
3134 case ISD::SETOLT: // flipped
3136 case ISD::SETGT: return X86::COND_A;
3137 case ISD::SETOLE: // flipped
3139 case ISD::SETGE: return X86::COND_AE;
3140 case ISD::SETUGT: // flipped
3142 case ISD::SETLT: return X86::COND_B;
3143 case ISD::SETUGE: // flipped
3145 case ISD::SETLE: return X86::COND_BE;
3147 case ISD::SETNE: return X86::COND_NE;
3148 case ISD::SETUO: return X86::COND_P;
3149 case ISD::SETO: return X86::COND_NP;
3151 case ISD::SETUNE: return X86::COND_INVALID;
3155 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3156 /// code. Current x86 isa includes the following FP cmov instructions:
3157 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3158 static bool hasFPCMov(unsigned X86CC) {
3174 /// isFPImmLegal - Returns true if the target can instruction select the
3175 /// specified FP immediate natively. If false, the legalizer will
3176 /// materialize the FP immediate as a load from a constant pool.
3177 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3178 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3179 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3185 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3186 /// the specified range (L, H].
3187 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3188 return (Val < 0) || (Val >= Low && Val < Hi);
3191 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3192 /// specified value.
3193 static bool isUndefOrEqual(int Val, int CmpVal) {
3194 if (Val < 0 || Val == CmpVal)
3199 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3200 /// from position Pos and ending in Pos+Size, falls within the specified
3201 /// sequential range (L, L+Pos]. or is undef.
3202 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3203 unsigned Pos, unsigned Size, int Low) {
3204 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3205 if (!isUndefOrEqual(Mask[i], Low))
3210 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3211 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3212 /// the second operand.
3213 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3214 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3215 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3216 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3217 return (Mask[0] < 2 && Mask[1] < 2);
3221 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3222 /// is suitable for input to PSHUFHW.
3223 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3224 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3227 // Lower quadword copied in order or undef.
3228 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3231 // Upper quadword shuffled.
3232 for (unsigned i = 4; i != 8; ++i)
3233 if (!isUndefOrInRange(Mask[i], 4, 8))
3236 if (VT == MVT::v16i16) {
3237 // Lower quadword copied in order or undef.
3238 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3241 // Upper quadword shuffled.
3242 for (unsigned i = 12; i != 16; ++i)
3243 if (!isUndefOrInRange(Mask[i], 12, 16))
3250 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3251 /// is suitable for input to PSHUFLW.
3252 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3253 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3256 // Upper quadword copied in order.
3257 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3260 // Lower quadword shuffled.
3261 for (unsigned i = 0; i != 4; ++i)
3262 if (!isUndefOrInRange(Mask[i], 0, 4))
3265 if (VT == MVT::v16i16) {
3266 // Upper quadword copied in order.
3267 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3270 // Lower quadword shuffled.
3271 for (unsigned i = 8; i != 12; ++i)
3272 if (!isUndefOrInRange(Mask[i], 8, 12))
3279 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3280 /// is suitable for input to PALIGNR.
3281 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3282 const X86Subtarget *Subtarget) {
3283 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3284 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3287 unsigned NumElts = VT.getVectorNumElements();
3288 unsigned NumLanes = VT.getSizeInBits()/128;
3289 unsigned NumLaneElts = NumElts/NumLanes;
3291 // Do not handle 64-bit element shuffles with palignr.
3292 if (NumLaneElts == 2)
3295 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3297 for (i = 0; i != NumLaneElts; ++i) {
3302 // Lane is all undef, go to next lane
3303 if (i == NumLaneElts)
3306 int Start = Mask[i+l];
3308 // Make sure its in this lane in one of the sources
3309 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3310 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3313 // If not lane 0, then we must match lane 0
3314 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3317 // Correct second source to be contiguous with first source
3318 if (Start >= (int)NumElts)
3319 Start -= NumElts - NumLaneElts;
3321 // Make sure we're shifting in the right direction.
3322 if (Start <= (int)(i+l))
3327 // Check the rest of the elements to see if they are consecutive.
3328 for (++i; i != NumLaneElts; ++i) {
3329 int Idx = Mask[i+l];
3331 // Make sure its in this lane
3332 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3333 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3336 // If not lane 0, then we must match lane 0
3337 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3340 if (Idx >= (int)NumElts)
3341 Idx -= NumElts - NumLaneElts;
3343 if (!isUndefOrEqual(Idx, Start+i))
3352 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3353 /// the two vector operands have swapped position.
3354 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3355 unsigned NumElems) {
3356 for (unsigned i = 0; i != NumElems; ++i) {
3360 else if (idx < (int)NumElems)
3361 Mask[i] = idx + NumElems;
3363 Mask[i] = idx - NumElems;
3367 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3368 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3369 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3370 /// reverse of what x86 shuffles want.
3371 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3372 bool Commuted = false) {
3373 if (!HasAVX && VT.getSizeInBits() == 256)
3376 unsigned NumElems = VT.getVectorNumElements();
3377 unsigned NumLanes = VT.getSizeInBits()/128;
3378 unsigned NumLaneElems = NumElems/NumLanes;
3380 if (NumLaneElems != 2 && NumLaneElems != 4)
3383 // VSHUFPSY divides the resulting vector into 4 chunks.
3384 // The sources are also splitted into 4 chunks, and each destination
3385 // chunk must come from a different source chunk.
3387 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3388 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3390 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3391 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3393 // VSHUFPDY divides the resulting vector into 4 chunks.
3394 // The sources are also splitted into 4 chunks, and each destination
3395 // chunk must come from a different source chunk.
3397 // SRC1 => X3 X2 X1 X0
3398 // SRC2 => Y3 Y2 Y1 Y0
3400 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3402 unsigned HalfLaneElems = NumLaneElems/2;
3403 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3404 for (unsigned i = 0; i != NumLaneElems; ++i) {
3405 int Idx = Mask[i+l];
3406 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3407 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3409 // For VSHUFPSY, the mask of the second half must be the same as the
3410 // first but with the appropriate offsets. This works in the same way as
3411 // VPERMILPS works with masks.
3412 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3414 if (!isUndefOrEqual(Idx, Mask[i]+l))
3422 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3423 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3424 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3425 if (!VT.is128BitVector())
3428 unsigned NumElems = VT.getVectorNumElements();
3433 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3434 return isUndefOrEqual(Mask[0], 6) &&
3435 isUndefOrEqual(Mask[1], 7) &&
3436 isUndefOrEqual(Mask[2], 2) &&
3437 isUndefOrEqual(Mask[3], 3);
3440 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3441 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3443 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3444 if (!VT.is128BitVector())
3447 unsigned NumElems = VT.getVectorNumElements();
3452 return isUndefOrEqual(Mask[0], 2) &&
3453 isUndefOrEqual(Mask[1], 3) &&
3454 isUndefOrEqual(Mask[2], 2) &&
3455 isUndefOrEqual(Mask[3], 3);
3458 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3459 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3460 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3461 if (!VT.is128BitVector())
3464 unsigned NumElems = VT.getVectorNumElements();
3466 if (NumElems != 2 && NumElems != 4)
3469 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3470 if (!isUndefOrEqual(Mask[i], i + NumElems))
3473 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3474 if (!isUndefOrEqual(Mask[i], i))
3480 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3481 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3482 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3483 if (!VT.is128BitVector())
3486 unsigned NumElems = VT.getVectorNumElements();
3488 if (NumElems != 2 && NumElems != 4)
3491 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492 if (!isUndefOrEqual(Mask[i], i))
3495 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3496 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3503 // Some special combinations that can be optimized.
3506 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3507 SelectionDAG &DAG) {
3508 EVT VT = SVOp->getValueType(0);
3509 DebugLoc dl = SVOp->getDebugLoc();
3511 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3514 ArrayRef<int> Mask = SVOp->getMask();
3516 // These are the special masks that may be optimized.
3517 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3518 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3519 bool MatchEvenMask = true;
3520 bool MatchOddMask = true;
3521 for (int i=0; i<8; ++i) {
3522 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3523 MatchEvenMask = false;
3524 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3525 MatchOddMask = false;
3528 if (!MatchEvenMask && !MatchOddMask)
3531 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3533 SDValue Op0 = SVOp->getOperand(0);
3534 SDValue Op1 = SVOp->getOperand(1);
3536 if (MatchEvenMask) {
3537 // Shift the second operand right to 32 bits.
3538 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3539 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3541 // Shift the first operand left to 32 bits.
3542 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3543 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3545 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3546 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3549 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3550 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3551 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3552 bool HasAVX2, bool V2IsSplat = false) {
3553 unsigned NumElts = VT.getVectorNumElements();
3555 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3556 "Unsupported vector type for unpckh");
3558 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3559 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3562 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3563 // independently on 128-bit lanes.
3564 unsigned NumLanes = VT.getSizeInBits()/128;
3565 unsigned NumLaneElts = NumElts/NumLanes;
3567 for (unsigned l = 0; l != NumLanes; ++l) {
3568 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3569 i != (l+1)*NumLaneElts;
3572 int BitI1 = Mask[i+1];
3573 if (!isUndefOrEqual(BitI, j))
3576 if (!isUndefOrEqual(BitI1, NumElts))
3579 if (!isUndefOrEqual(BitI1, j + NumElts))
3588 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3589 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3590 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3591 bool HasAVX2, bool V2IsSplat = false) {
3592 unsigned NumElts = VT.getVectorNumElements();
3594 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3595 "Unsupported vector type for unpckh");
3597 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3598 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3601 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3602 // independently on 128-bit lanes.
3603 unsigned NumLanes = VT.getSizeInBits()/128;
3604 unsigned NumLaneElts = NumElts/NumLanes;
3606 for (unsigned l = 0; l != NumLanes; ++l) {
3607 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3608 i != (l+1)*NumLaneElts; i += 2, ++j) {
3610 int BitI1 = Mask[i+1];
3611 if (!isUndefOrEqual(BitI, j))
3614 if (isUndefOrEqual(BitI1, NumElts))
3617 if (!isUndefOrEqual(BitI1, j+NumElts))
3625 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3626 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3628 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3630 unsigned NumElts = VT.getVectorNumElements();
3632 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3633 "Unsupported vector type for unpckh");
3635 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3636 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3639 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3640 // FIXME: Need a better way to get rid of this, there's no latency difference
3641 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3642 // the former later. We should also remove the "_undef" special mask.
3643 if (NumElts == 4 && VT.getSizeInBits() == 256)
3646 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3647 // independently on 128-bit lanes.
3648 unsigned NumLanes = VT.getSizeInBits()/128;
3649 unsigned NumLaneElts = NumElts/NumLanes;
3651 for (unsigned l = 0; l != NumLanes; ++l) {
3652 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3653 i != (l+1)*NumLaneElts;
3656 int BitI1 = Mask[i+1];
3658 if (!isUndefOrEqual(BitI, j))
3660 if (!isUndefOrEqual(BitI1, j))
3668 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3669 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3671 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3672 unsigned NumElts = VT.getVectorNumElements();
3674 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3675 "Unsupported vector type for unpckh");
3677 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3678 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3681 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3682 // independently on 128-bit lanes.
3683 unsigned NumLanes = VT.getSizeInBits()/128;
3684 unsigned NumLaneElts = NumElts/NumLanes;
3686 for (unsigned l = 0; l != NumLanes; ++l) {
3687 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3688 i != (l+1)*NumLaneElts; i += 2, ++j) {
3690 int BitI1 = Mask[i+1];
3691 if (!isUndefOrEqual(BitI, j))
3693 if (!isUndefOrEqual(BitI1, j))
3700 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3701 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3702 /// MOVSD, and MOVD, i.e. setting the lowest element.
3703 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3704 if (VT.getVectorElementType().getSizeInBits() < 32)
3706 if (!VT.is128BitVector())
3709 unsigned NumElts = VT.getVectorNumElements();
3711 if (!isUndefOrEqual(Mask[0], NumElts))
3714 for (unsigned i = 1; i != NumElts; ++i)
3715 if (!isUndefOrEqual(Mask[i], i))
3721 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3722 /// as permutations between 128-bit chunks or halves. As an example: this
3724 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3725 /// The first half comes from the second half of V1 and the second half from the
3726 /// the second half of V2.
3727 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3728 if (!HasAVX || !VT.is256BitVector())
3731 // The shuffle result is divided into half A and half B. In total the two
3732 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3733 // B must come from C, D, E or F.
3734 unsigned HalfSize = VT.getVectorNumElements()/2;
3735 bool MatchA = false, MatchB = false;
3737 // Check if A comes from one of C, D, E, F.
3738 for (unsigned Half = 0; Half != 4; ++Half) {
3739 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3745 // Check if B comes from one of C, D, E, F.
3746 for (unsigned Half = 0; Half != 4; ++Half) {
3747 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3753 return MatchA && MatchB;
3756 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3757 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3758 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3759 EVT VT = SVOp->getValueType(0);
3761 unsigned HalfSize = VT.getVectorNumElements()/2;
3763 unsigned FstHalf = 0, SndHalf = 0;
3764 for (unsigned i = 0; i < HalfSize; ++i) {
3765 if (SVOp->getMaskElt(i) > 0) {
3766 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3770 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3771 if (SVOp->getMaskElt(i) > 0) {
3772 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3777 return (FstHalf | (SndHalf << 4));
3780 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3782 /// Note that VPERMIL mask matching is different depending whether theunderlying
3783 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3784 /// to the same elements of the low, but to the higher half of the source.
3785 /// In VPERMILPD the two lanes could be shuffled independently of each other
3786 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3787 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3791 unsigned NumElts = VT.getVectorNumElements();
3792 // Only match 256-bit with 32/64-bit types
3793 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3796 unsigned NumLanes = VT.getSizeInBits()/128;
3797 unsigned LaneSize = NumElts/NumLanes;
3798 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3799 for (unsigned i = 0; i != LaneSize; ++i) {
3800 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3802 if (NumElts != 8 || l == 0)
3804 // VPERMILPS handling
3807 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3815 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3816 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3817 /// element of vector 2 and the other elements to come from vector 1 in order.
3818 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3819 bool V2IsSplat = false, bool V2IsUndef = false) {
3820 if (!VT.is128BitVector())
3823 unsigned NumOps = VT.getVectorNumElements();
3824 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3827 if (!isUndefOrEqual(Mask[0], 0))
3830 for (unsigned i = 1; i != NumOps; ++i)
3831 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3832 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3833 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3839 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3840 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3841 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3842 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3843 const X86Subtarget *Subtarget) {
3844 if (!Subtarget->hasSSE3())
3847 unsigned NumElems = VT.getVectorNumElements();
3849 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3850 (VT.getSizeInBits() == 256 && NumElems != 8))
3853 // "i+1" is the value the indexed mask element must have
3854 for (unsigned i = 0; i != NumElems; i += 2)
3855 if (!isUndefOrEqual(Mask[i], i+1) ||
3856 !isUndefOrEqual(Mask[i+1], i+1))
3862 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3863 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3864 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3865 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3866 const X86Subtarget *Subtarget) {
3867 if (!Subtarget->hasSSE3())
3870 unsigned NumElems = VT.getVectorNumElements();
3872 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3873 (VT.getSizeInBits() == 256 && NumElems != 8))
3876 // "i" is the value the indexed mask element must have
3877 for (unsigned i = 0; i != NumElems; i += 2)
3878 if (!isUndefOrEqual(Mask[i], i) ||
3879 !isUndefOrEqual(Mask[i+1], i))
3885 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3886 /// specifies a shuffle of elements that is suitable for input to 256-bit
3887 /// version of MOVDDUP.
3888 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3889 if (!HasAVX || !VT.is256BitVector())
3892 unsigned NumElts = VT.getVectorNumElements();
3896 for (unsigned i = 0; i != NumElts/2; ++i)
3897 if (!isUndefOrEqual(Mask[i], 0))
3899 for (unsigned i = NumElts/2; i != NumElts; ++i)
3900 if (!isUndefOrEqual(Mask[i], NumElts/2))
3905 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to 128-bit
3907 /// version of MOVDDUP.
3908 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3909 if (!VT.is128BitVector())
3912 unsigned e = VT.getVectorNumElements() / 2;
3913 for (unsigned i = 0; i != e; ++i)
3914 if (!isUndefOrEqual(Mask[i], i))
3916 for (unsigned i = 0; i != e; ++i)
3917 if (!isUndefOrEqual(Mask[e+i], i))
3922 /// isVEXTRACTF128Index - Return true if the specified
3923 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3924 /// suitable for input to VEXTRACTF128.
3925 bool X86::isVEXTRACTF128Index(SDNode *N) {
3926 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3929 // The index should be aligned on a 128-bit boundary.
3931 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3933 unsigned VL = N->getValueType(0).getVectorNumElements();
3934 unsigned VBits = N->getValueType(0).getSizeInBits();
3935 unsigned ElSize = VBits / VL;
3936 bool Result = (Index * ElSize) % 128 == 0;
3941 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3942 /// operand specifies a subvector insert that is suitable for input to
3944 bool X86::isVINSERTF128Index(SDNode *N) {
3945 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3948 // The index should be aligned on a 128-bit boundary.
3950 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3952 unsigned VL = N->getValueType(0).getVectorNumElements();
3953 unsigned VBits = N->getValueType(0).getSizeInBits();
3954 unsigned ElSize = VBits / VL;
3955 bool Result = (Index * ElSize) % 128 == 0;
3960 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3961 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3962 /// Handles 128-bit and 256-bit.
3963 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3964 EVT VT = N->getValueType(0);
3966 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3967 "Unsupported vector type for PSHUF/SHUFP");
3969 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3970 // independently on 128-bit lanes.
3971 unsigned NumElts = VT.getVectorNumElements();
3972 unsigned NumLanes = VT.getSizeInBits()/128;
3973 unsigned NumLaneElts = NumElts/NumLanes;
3975 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3976 "Only supports 2 or 4 elements per lane");
3978 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3980 for (unsigned i = 0; i != NumElts; ++i) {
3981 int Elt = N->getMaskElt(i);
3982 if (Elt < 0) continue;
3983 Elt &= NumLaneElts - 1;
3984 unsigned ShAmt = (i << Shift) % 8;
3985 Mask |= Elt << ShAmt;
3991 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3992 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3993 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3994 EVT VT = N->getValueType(0);
3996 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3997 "Unsupported vector type for PSHUFHW");
3999 unsigned NumElts = VT.getVectorNumElements();
4002 for (unsigned l = 0; l != NumElts; l += 8) {
4003 // 8 nodes per lane, but we only care about the last 4.
4004 for (unsigned i = 0; i < 4; ++i) {
4005 int Elt = N->getMaskElt(l+i+4);
4006 if (Elt < 0) continue;
4007 Elt &= 0x3; // only 2-bits.
4008 Mask |= Elt << (i * 2);
4015 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4016 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4017 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4018 EVT VT = N->getValueType(0);
4020 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4021 "Unsupported vector type for PSHUFHW");
4023 unsigned NumElts = VT.getVectorNumElements();
4026 for (unsigned l = 0; l != NumElts; l += 8) {
4027 // 8 nodes per lane, but we only care about the first 4.
4028 for (unsigned i = 0; i < 4; ++i) {
4029 int Elt = N->getMaskElt(l+i);
4030 if (Elt < 0) continue;
4031 Elt &= 0x3; // only 2-bits
4032 Mask |= Elt << (i * 2);
4039 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4040 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4041 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4042 EVT VT = SVOp->getValueType(0);
4043 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4045 unsigned NumElts = VT.getVectorNumElements();
4046 unsigned NumLanes = VT.getSizeInBits()/128;
4047 unsigned NumLaneElts = NumElts/NumLanes;
4051 for (i = 0; i != NumElts; ++i) {
4052 Val = SVOp->getMaskElt(i);
4056 if (Val >= (int)NumElts)
4057 Val -= NumElts - NumLaneElts;
4059 assert(Val - i > 0 && "PALIGNR imm should be positive");
4060 return (Val - i) * EltSize;
4063 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4064 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4066 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4067 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4068 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4071 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4073 EVT VecVT = N->getOperand(0).getValueType();
4074 EVT ElVT = VecVT.getVectorElementType();
4076 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4077 return Index / NumElemsPerChunk;
4080 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4081 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4083 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4084 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4085 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4088 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4090 EVT VecVT = N->getValueType(0);
4091 EVT ElVT = VecVT.getVectorElementType();
4093 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4094 return Index / NumElemsPerChunk;
4097 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4098 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4099 /// Handles 256-bit.
4100 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4101 EVT VT = N->getValueType(0);
4103 unsigned NumElts = VT.getVectorNumElements();
4105 assert((VT.is256BitVector() && NumElts == 4) &&
4106 "Unsupported vector type for VPERMQ/VPERMPD");
4109 for (unsigned i = 0; i != NumElts; ++i) {
4110 int Elt = N->getMaskElt(i);
4113 Mask |= Elt << (i*2);
4118 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4120 bool X86::isZeroNode(SDValue Elt) {
4121 return ((isa<ConstantSDNode>(Elt) &&
4122 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4123 (isa<ConstantFPSDNode>(Elt) &&
4124 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4127 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4128 /// their permute mask.
4129 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4130 SelectionDAG &DAG) {
4131 EVT VT = SVOp->getValueType(0);
4132 unsigned NumElems = VT.getVectorNumElements();
4133 SmallVector<int, 8> MaskVec;
4135 for (unsigned i = 0; i != NumElems; ++i) {
4136 int Idx = SVOp->getMaskElt(i);
4138 if (Idx < (int)NumElems)
4143 MaskVec.push_back(Idx);
4145 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4146 SVOp->getOperand(0), &MaskVec[0]);
4149 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4150 /// match movhlps. The lower half elements should come from upper half of
4151 /// V1 (and in order), and the upper half elements should come from the upper
4152 /// half of V2 (and in order).
4153 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4154 if (!VT.is128BitVector())
4156 if (VT.getVectorNumElements() != 4)
4158 for (unsigned i = 0, e = 2; i != e; ++i)
4159 if (!isUndefOrEqual(Mask[i], i+2))
4161 for (unsigned i = 2; i != 4; ++i)
4162 if (!isUndefOrEqual(Mask[i], i+4))
4167 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4168 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4170 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4171 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4173 N = N->getOperand(0).getNode();
4174 if (!ISD::isNON_EXTLoad(N))
4177 *LD = cast<LoadSDNode>(N);
4181 // Test whether the given value is a vector value which will be legalized
4183 static bool WillBeConstantPoolLoad(SDNode *N) {
4184 if (N->getOpcode() != ISD::BUILD_VECTOR)
4187 // Check for any non-constant elements.
4188 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4189 switch (N->getOperand(i).getNode()->getOpcode()) {
4191 case ISD::ConstantFP:
4198 // Vectors of all-zeros and all-ones are materialized with special
4199 // instructions rather than being loaded.
4200 return !ISD::isBuildVectorAllZeros(N) &&
4201 !ISD::isBuildVectorAllOnes(N);
4204 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4205 /// match movlp{s|d}. The lower half elements should come from lower half of
4206 /// V1 (and in order), and the upper half elements should come from the upper
4207 /// half of V2 (and in order). And since V1 will become the source of the
4208 /// MOVLP, it must be either a vector load or a scalar load to vector.
4209 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4210 ArrayRef<int> Mask, EVT VT) {
4211 if (!VT.is128BitVector())
4214 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4216 // Is V2 is a vector load, don't do this transformation. We will try to use
4217 // load folding shufps op.
4218 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4221 unsigned NumElems = VT.getVectorNumElements();
4223 if (NumElems != 2 && NumElems != 4)
4225 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4226 if (!isUndefOrEqual(Mask[i], i))
4228 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4229 if (!isUndefOrEqual(Mask[i], i+NumElems))
4234 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4236 static bool isSplatVector(SDNode *N) {
4237 if (N->getOpcode() != ISD::BUILD_VECTOR)
4240 SDValue SplatValue = N->getOperand(0);
4241 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4242 if (N->getOperand(i) != SplatValue)
4247 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4248 /// to an zero vector.
4249 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4250 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4251 SDValue V1 = N->getOperand(0);
4252 SDValue V2 = N->getOperand(1);
4253 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4254 for (unsigned i = 0; i != NumElems; ++i) {
4255 int Idx = N->getMaskElt(i);
4256 if (Idx >= (int)NumElems) {
4257 unsigned Opc = V2.getOpcode();
4258 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4260 if (Opc != ISD::BUILD_VECTOR ||
4261 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4263 } else if (Idx >= 0) {
4264 unsigned Opc = V1.getOpcode();
4265 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4267 if (Opc != ISD::BUILD_VECTOR ||
4268 !X86::isZeroNode(V1.getOperand(Idx)))
4275 /// getZeroVector - Returns a vector of specified type with all zero elements.
4277 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4278 SelectionDAG &DAG, DebugLoc dl) {
4279 assert(VT.isVector() && "Expected a vector type");
4280 unsigned Size = VT.getSizeInBits();
4282 // Always build SSE zero vectors as <4 x i32> bitcasted
4283 // to their dest type. This ensures they get CSE'd.
4285 if (Size == 128) { // SSE
4286 if (Subtarget->hasSSE2()) { // SSE2
4287 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4288 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4290 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4291 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4293 } else if (Size == 256) { // AVX
4294 if (Subtarget->hasAVX2()) { // AVX2
4295 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4296 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4297 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4299 // 256-bit logic and arithmetic instructions in AVX are all
4300 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4301 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4302 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4303 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4306 llvm_unreachable("Unexpected vector type");
4308 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4311 /// getOnesVector - Returns a vector of specified type with all bits set.
4312 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4313 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4314 /// Then bitcast to their original type, ensuring they get CSE'd.
4315 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4317 assert(VT.isVector() && "Expected a vector type");
4318 unsigned Size = VT.getSizeInBits();
4320 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4323 if (HasAVX2) { // AVX2
4324 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4325 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4327 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4328 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4330 } else if (Size == 128) {
4331 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4333 llvm_unreachable("Unexpected vector type");
4335 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4338 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4339 /// that point to V2 points to its first element.
4340 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4341 for (unsigned i = 0; i != NumElems; ++i) {
4342 if (Mask[i] > (int)NumElems) {
4348 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4349 /// operation of specified width.
4350 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4352 unsigned NumElems = VT.getVectorNumElements();
4353 SmallVector<int, 8> Mask;
4354 Mask.push_back(NumElems);
4355 for (unsigned i = 1; i != NumElems; ++i)
4357 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4360 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4361 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4363 unsigned NumElems = VT.getVectorNumElements();
4364 SmallVector<int, 8> Mask;
4365 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4367 Mask.push_back(i + NumElems);
4369 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4372 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4373 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4375 unsigned NumElems = VT.getVectorNumElements();
4376 SmallVector<int, 8> Mask;
4377 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4378 Mask.push_back(i + Half);
4379 Mask.push_back(i + NumElems + Half);
4381 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4384 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4385 // a generic shuffle instruction because the target has no such instructions.
4386 // Generate shuffles which repeat i16 and i8 several times until they can be
4387 // represented by v4f32 and then be manipulated by target suported shuffles.
4388 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4389 EVT VT = V.getValueType();
4390 int NumElems = VT.getVectorNumElements();
4391 DebugLoc dl = V.getDebugLoc();
4393 while (NumElems > 4) {
4394 if (EltNo < NumElems/2) {
4395 V = getUnpackl(DAG, dl, VT, V, V);
4397 V = getUnpackh(DAG, dl, VT, V, V);
4398 EltNo -= NumElems/2;
4405 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4406 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4407 EVT VT = V.getValueType();
4408 DebugLoc dl = V.getDebugLoc();
4409 unsigned Size = VT.getSizeInBits();
4412 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4413 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4414 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4416 } else if (Size == 256) {
4417 // To use VPERMILPS to splat scalars, the second half of indicies must
4418 // refer to the higher part, which is a duplication of the lower one,
4419 // because VPERMILPS can only handle in-lane permutations.
4420 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4421 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4423 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4424 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4427 llvm_unreachable("Vector size not supported");
4429 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4432 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4433 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4434 EVT SrcVT = SV->getValueType(0);
4435 SDValue V1 = SV->getOperand(0);
4436 DebugLoc dl = SV->getDebugLoc();
4438 int EltNo = SV->getSplatIndex();
4439 int NumElems = SrcVT.getVectorNumElements();
4440 unsigned Size = SrcVT.getSizeInBits();
4442 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4443 "Unknown how to promote splat for type");
4445 // Extract the 128-bit part containing the splat element and update
4446 // the splat element index when it refers to the higher register.
4448 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4449 if (EltNo >= NumElems/2)
4450 EltNo -= NumElems/2;
4453 // All i16 and i8 vector types can't be used directly by a generic shuffle
4454 // instruction because the target has no such instruction. Generate shuffles
4455 // which repeat i16 and i8 several times until they fit in i32, and then can
4456 // be manipulated by target suported shuffles.
4457 EVT EltVT = SrcVT.getVectorElementType();
4458 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4459 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4461 // Recreate the 256-bit vector and place the same 128-bit vector
4462 // into the low and high part. This is necessary because we want
4463 // to use VPERM* to shuffle the vectors
4465 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4468 return getLegalSplat(DAG, V1, EltNo);
4471 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4472 /// vector of zero or undef vector. This produces a shuffle where the low
4473 /// element of V2 is swizzled into the zero/undef vector, landing at element
4474 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4475 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4477 const X86Subtarget *Subtarget,
4478 SelectionDAG &DAG) {
4479 EVT VT = V2.getValueType();
4481 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4482 unsigned NumElems = VT.getVectorNumElements();
4483 SmallVector<int, 16> MaskVec;
4484 for (unsigned i = 0; i != NumElems; ++i)
4485 // If this is the insertion idx, put the low elt of V2 here.
4486 MaskVec.push_back(i == Idx ? NumElems : i);
4487 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4490 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4491 /// target specific opcode. Returns true if the Mask could be calculated.
4492 /// Sets IsUnary to true if only uses one source.
4493 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4494 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4495 unsigned NumElems = VT.getVectorNumElements();
4499 switch(N->getOpcode()) {
4501 ImmN = N->getOperand(N->getNumOperands()-1);
4502 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4504 case X86ISD::UNPCKH:
4505 DecodeUNPCKHMask(VT, Mask);
4507 case X86ISD::UNPCKL:
4508 DecodeUNPCKLMask(VT, Mask);
4510 case X86ISD::MOVHLPS:
4511 DecodeMOVHLPSMask(NumElems, Mask);
4513 case X86ISD::MOVLHPS:
4514 DecodeMOVLHPSMask(NumElems, Mask);
4516 case X86ISD::PSHUFD:
4517 case X86ISD::VPERMILP:
4518 ImmN = N->getOperand(N->getNumOperands()-1);
4519 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4522 case X86ISD::PSHUFHW:
4523 ImmN = N->getOperand(N->getNumOperands()-1);
4524 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4527 case X86ISD::PSHUFLW:
4528 ImmN = N->getOperand(N->getNumOperands()-1);
4529 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4532 case X86ISD::VPERMI:
4533 ImmN = N->getOperand(N->getNumOperands()-1);
4534 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4538 case X86ISD::MOVSD: {
4539 // The index 0 always comes from the first element of the second source,
4540 // this is why MOVSS and MOVSD are used in the first place. The other
4541 // elements come from the other positions of the first source vector
4542 Mask.push_back(NumElems);
4543 for (unsigned i = 1; i != NumElems; ++i) {
4548 case X86ISD::VPERM2X128:
4549 ImmN = N->getOperand(N->getNumOperands()-1);
4550 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551 if (Mask.empty()) return false;
4553 case X86ISD::MOVDDUP:
4554 case X86ISD::MOVLHPD:
4555 case X86ISD::MOVLPD:
4556 case X86ISD::MOVLPS:
4557 case X86ISD::MOVSHDUP:
4558 case X86ISD::MOVSLDUP:
4559 case X86ISD::PALIGN:
4560 // Not yet implemented
4562 default: llvm_unreachable("unknown target shuffle node");
4568 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4569 /// element of the result of the vector shuffle.
4570 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4573 return SDValue(); // Limit search depth.
4575 SDValue V = SDValue(N, 0);
4576 EVT VT = V.getValueType();
4577 unsigned Opcode = V.getOpcode();
4579 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4580 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4581 int Elt = SV->getMaskElt(Index);
4584 return DAG.getUNDEF(VT.getVectorElementType());
4586 unsigned NumElems = VT.getVectorNumElements();
4587 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4588 : SV->getOperand(1);
4589 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4592 // Recurse into target specific vector shuffles to find scalars.
4593 if (isTargetShuffle(Opcode)) {
4594 MVT ShufVT = V.getValueType().getSimpleVT();
4595 unsigned NumElems = ShufVT.getVectorNumElements();
4596 SmallVector<int, 16> ShuffleMask;
4600 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4603 int Elt = ShuffleMask[Index];
4605 return DAG.getUNDEF(ShufVT.getVectorElementType());
4607 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4609 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4613 // Actual nodes that may contain scalar elements
4614 if (Opcode == ISD::BITCAST) {
4615 V = V.getOperand(0);
4616 EVT SrcVT = V.getValueType();
4617 unsigned NumElems = VT.getVectorNumElements();
4619 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4623 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4624 return (Index == 0) ? V.getOperand(0)
4625 : DAG.getUNDEF(VT.getVectorElementType());
4627 if (V.getOpcode() == ISD::BUILD_VECTOR)
4628 return V.getOperand(Index);
4633 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4634 /// shuffle operation which come from a consecutively from a zero. The
4635 /// search can start in two different directions, from left or right.
4637 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4638 bool ZerosFromLeft, SelectionDAG &DAG) {
4640 for (i = 0; i != NumElems; ++i) {
4641 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4642 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4643 if (!(Elt.getNode() &&
4644 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4651 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4652 /// correspond consecutively to elements from one of the vector operands,
4653 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4655 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4656 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4657 unsigned NumElems, unsigned &OpNum) {
4658 bool SeenV1 = false;
4659 bool SeenV2 = false;
4661 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4662 int Idx = SVOp->getMaskElt(i);
4663 // Ignore undef indicies
4667 if (Idx < (int)NumElems)
4672 // Only accept consecutive elements from the same vector
4673 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4677 OpNum = SeenV1 ? 0 : 1;
4681 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4682 /// logical left shift of a vector.
4683 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4684 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4685 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4686 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4687 false /* check zeros from right */, DAG);
4693 // Considering the elements in the mask that are not consecutive zeros,
4694 // check if they consecutively come from only one of the source vectors.
4696 // V1 = {X, A, B, C} 0
4698 // vector_shuffle V1, V2 <1, 2, 3, X>
4700 if (!isShuffleMaskConsecutive(SVOp,
4701 0, // Mask Start Index
4702 NumElems-NumZeros, // Mask End Index(exclusive)
4703 NumZeros, // Where to start looking in the src vector
4704 NumElems, // Number of elements in vector
4705 OpSrc)) // Which source operand ?
4710 ShVal = SVOp->getOperand(OpSrc);
4714 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4715 /// logical left shift of a vector.
4716 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4717 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4718 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4719 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4720 true /* check zeros from left */, DAG);
4726 // Considering the elements in the mask that are not consecutive zeros,
4727 // check if they consecutively come from only one of the source vectors.
4729 // 0 { A, B, X, X } = V2
4731 // vector_shuffle V1, V2 <X, X, 4, 5>
4733 if (!isShuffleMaskConsecutive(SVOp,
4734 NumZeros, // Mask Start Index
4735 NumElems, // Mask End Index(exclusive)
4736 0, // Where to start looking in the src vector
4737 NumElems, // Number of elements in vector
4738 OpSrc)) // Which source operand ?
4743 ShVal = SVOp->getOperand(OpSrc);
4747 /// isVectorShift - Returns true if the shuffle can be implemented as a
4748 /// logical left or right shift of a vector.
4749 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4750 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4751 // Although the logic below support any bitwidth size, there are no
4752 // shift instructions which handle more than 128-bit vectors.
4753 if (!SVOp->getValueType(0).is128BitVector())
4756 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4757 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4763 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4765 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4766 unsigned NumNonZero, unsigned NumZero,
4768 const X86Subtarget* Subtarget,
4769 const TargetLowering &TLI) {
4773 DebugLoc dl = Op.getDebugLoc();
4776 for (unsigned i = 0; i < 16; ++i) {
4777 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4778 if (ThisIsNonZero && First) {
4780 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4782 V = DAG.getUNDEF(MVT::v8i16);
4787 SDValue ThisElt(0, 0), LastElt(0, 0);
4788 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4789 if (LastIsNonZero) {
4790 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4791 MVT::i16, Op.getOperand(i-1));
4793 if (ThisIsNonZero) {
4794 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4795 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4796 ThisElt, DAG.getConstant(8, MVT::i8));
4798 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4802 if (ThisElt.getNode())
4803 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4804 DAG.getIntPtrConstant(i/2));
4808 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4811 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4813 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4814 unsigned NumNonZero, unsigned NumZero,
4816 const X86Subtarget* Subtarget,
4817 const TargetLowering &TLI) {
4821 DebugLoc dl = Op.getDebugLoc();
4824 for (unsigned i = 0; i < 8; ++i) {
4825 bool isNonZero = (NonZeros & (1 << i)) != 0;
4829 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4831 V = DAG.getUNDEF(MVT::v8i16);
4834 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4835 MVT::v8i16, V, Op.getOperand(i),
4836 DAG.getIntPtrConstant(i));
4843 /// getVShift - Return a vector logical shift node.
4845 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4846 unsigned NumBits, SelectionDAG &DAG,
4847 const TargetLowering &TLI, DebugLoc dl) {
4848 assert(VT.is128BitVector() && "Unknown type for VShift");
4849 EVT ShVT = MVT::v2i64;
4850 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4851 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4852 return DAG.getNode(ISD::BITCAST, dl, VT,
4853 DAG.getNode(Opc, dl, ShVT, SrcOp,
4854 DAG.getConstant(NumBits,
4855 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4859 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4860 SelectionDAG &DAG) const {
4862 // Check if the scalar load can be widened into a vector load. And if
4863 // the address is "base + cst" see if the cst can be "absorbed" into
4864 // the shuffle mask.
4865 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4866 SDValue Ptr = LD->getBasePtr();
4867 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4869 EVT PVT = LD->getValueType(0);
4870 if (PVT != MVT::i32 && PVT != MVT::f32)
4875 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4876 FI = FINode->getIndex();
4878 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4879 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4880 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4881 Offset = Ptr.getConstantOperandVal(1);
4882 Ptr = Ptr.getOperand(0);
4887 // FIXME: 256-bit vector instructions don't require a strict alignment,
4888 // improve this code to support it better.
4889 unsigned RequiredAlign = VT.getSizeInBits()/8;
4890 SDValue Chain = LD->getChain();
4891 // Make sure the stack object alignment is at least 16 or 32.
4892 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4893 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4894 if (MFI->isFixedObjectIndex(FI)) {
4895 // Can't change the alignment. FIXME: It's possible to compute
4896 // the exact stack offset and reference FI + adjust offset instead.
4897 // If someone *really* cares about this. That's the way to implement it.
4900 MFI->setObjectAlignment(FI, RequiredAlign);
4904 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4905 // Ptr + (Offset & ~15).
4908 if ((Offset % RequiredAlign) & 3)
4910 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4912 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4913 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4915 int EltNo = (Offset - StartOffset) >> 2;
4916 unsigned NumElems = VT.getVectorNumElements();
4918 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4919 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4920 LD->getPointerInfo().getWithOffset(StartOffset),
4921 false, false, false, 0);
4923 SmallVector<int, 8> Mask;
4924 for (unsigned i = 0; i != NumElems; ++i)
4925 Mask.push_back(EltNo);
4927 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4933 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4934 /// vector of type 'VT', see if the elements can be replaced by a single large
4935 /// load which has the same value as a build_vector whose operands are 'elts'.
4937 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4939 /// FIXME: we'd also like to handle the case where the last elements are zero
4940 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4941 /// There's even a handy isZeroNode for that purpose.
4942 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4943 DebugLoc &DL, SelectionDAG &DAG) {
4944 EVT EltVT = VT.getVectorElementType();
4945 unsigned NumElems = Elts.size();
4947 LoadSDNode *LDBase = NULL;
4948 unsigned LastLoadedElt = -1U;
4950 // For each element in the initializer, see if we've found a load or an undef.
4951 // If we don't find an initial load element, or later load elements are
4952 // non-consecutive, bail out.
4953 for (unsigned i = 0; i < NumElems; ++i) {
4954 SDValue Elt = Elts[i];
4956 if (!Elt.getNode() ||
4957 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4960 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4962 LDBase = cast<LoadSDNode>(Elt.getNode());
4966 if (Elt.getOpcode() == ISD::UNDEF)
4969 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4970 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4975 // If we have found an entire vector of loads and undefs, then return a large
4976 // load of the entire vector width starting at the base pointer. If we found
4977 // consecutive loads for the low half, generate a vzext_load node.
4978 if (LastLoadedElt == NumElems - 1) {
4979 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4980 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4981 LDBase->getPointerInfo(),
4982 LDBase->isVolatile(), LDBase->isNonTemporal(),
4983 LDBase->isInvariant(), 0);
4984 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4985 LDBase->getPointerInfo(),
4986 LDBase->isVolatile(), LDBase->isNonTemporal(),
4987 LDBase->isInvariant(), LDBase->getAlignment());
4989 if (NumElems == 4 && LastLoadedElt == 1 &&
4990 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4991 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4992 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4994 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4995 LDBase->getPointerInfo(),
4996 LDBase->getAlignment(),
4997 false/*isVolatile*/, true/*ReadMem*/,
5000 // Make sure the newly-created LOAD is in the same position as LDBase in
5001 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5002 // update uses of LDBase's output chain to use the TokenFactor.
5003 if (LDBase->hasAnyUseOfValue(1)) {
5004 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5005 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5006 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5007 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5008 SDValue(ResNode.getNode(), 1));
5011 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5016 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5017 /// to generate a splat value for the following cases:
5018 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5019 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5020 /// a scalar load, or a constant.
5021 /// The VBROADCAST node is returned when a pattern is found,
5022 /// or SDValue() otherwise.
5024 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5025 if (!Subtarget->hasAVX())
5028 EVT VT = Op.getValueType();
5029 DebugLoc dl = Op.getDebugLoc();
5031 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5032 "Unsupported vector type for broadcast.");
5037 switch (Op.getOpcode()) {
5039 // Unknown pattern found.
5042 case ISD::BUILD_VECTOR: {
5043 // The BUILD_VECTOR node must be a splat.
5044 if (!isSplatVector(Op.getNode()))
5047 Ld = Op.getOperand(0);
5048 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5049 Ld.getOpcode() == ISD::ConstantFP);
5051 // The suspected load node has several users. Make sure that all
5052 // of its users are from the BUILD_VECTOR node.
5053 // Constants may have multiple users.
5054 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5059 case ISD::VECTOR_SHUFFLE: {
5060 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5062 // Shuffles must have a splat mask where the first element is
5064 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5067 SDValue Sc = Op.getOperand(0);
5068 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5069 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5071 if (!Subtarget->hasAVX2())
5074 // Use the register form of the broadcast instruction available on AVX2.
5075 if (VT.is256BitVector())
5076 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5077 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5080 Ld = Sc.getOperand(0);
5081 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5082 Ld.getOpcode() == ISD::ConstantFP);
5084 // The scalar_to_vector node and the suspected
5085 // load node must have exactly one user.
5086 // Constants may have multiple users.
5087 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5093 bool Is256 = VT.is256BitVector();
5095 // Handle the broadcasting a single constant scalar from the constant pool
5096 // into a vector. On Sandybridge it is still better to load a constant vector
5097 // from the constant pool and not to broadcast it from a scalar.
5098 if (ConstSplatVal && Subtarget->hasAVX2()) {
5099 EVT CVT = Ld.getValueType();
5100 assert(!CVT.isVector() && "Must not broadcast a vector type");
5101 unsigned ScalarSize = CVT.getSizeInBits();
5103 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5104 const Constant *C = 0;
5105 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5106 C = CI->getConstantIntValue();
5107 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5108 C = CF->getConstantFPValue();
5110 assert(C && "Invalid constant type");
5112 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5113 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5114 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5115 MachinePointerInfo::getConstantPool(),
5116 false, false, false, Alignment);
5118 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5122 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5123 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5125 // Handle AVX2 in-register broadcasts.
5126 if (!IsLoad && Subtarget->hasAVX2() &&
5127 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5128 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5130 // The scalar source must be a normal load.
5134 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5135 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5137 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5138 // double since there is no vbroadcastsd xmm
5139 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5140 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5141 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5144 // Unsupported broadcast.
5148 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5149 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5150 // constraint of matching input/output vector elements.
5152 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5153 DebugLoc DL = Op.getDebugLoc();
5154 SDNode *N = Op.getNode();
5155 EVT VT = Op.getValueType();
5156 unsigned NumElts = Op.getNumOperands();
5158 // Check supported types and sub-targets.
5160 // Only v2f32 -> v2f64 needs special handling.
5161 if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5166 SmallVector<int, 8> Mask;
5167 EVT SrcVT = MVT::Other;
5169 // Check the patterns could be translated into X86vfpext.
5170 for (unsigned i = 0; i < NumElts; ++i) {
5171 SDValue In = N->getOperand(i);
5172 unsigned Opcode = In.getOpcode();
5174 // Skip if the element is undefined.
5175 if (Opcode == ISD::UNDEF) {
5180 // Quit if one of the elements is not defined from 'fpext'.
5181 if (Opcode != ISD::FP_EXTEND)
5184 // Check how the source of 'fpext' is defined.
5185 SDValue L2In = In.getOperand(0);
5186 EVT L2InVT = L2In.getValueType();
5188 // Check the original type
5189 if (SrcVT == MVT::Other)
5191 else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5194 // Check whether the value being 'fpext'ed is extracted from the same
5196 Opcode = L2In.getOpcode();
5198 // Quit if it's not extracted with a constant index.
5199 if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5200 !isa<ConstantSDNode>(L2In.getOperand(1)))
5203 SDValue ExtractedFromVec = L2In.getOperand(0);
5205 if (VecIn.getNode() == 0) {
5206 VecIn = ExtractedFromVec;
5207 VecInVT = ExtractedFromVec.getValueType();
5208 } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5211 Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5214 // Quit if all operands of BUILD_VECTOR are undefined.
5215 if (!VecIn.getNode())
5218 // Fill the remaining mask as undef.
5219 for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5222 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5223 DAG.getVectorShuffle(VecInVT, DL,
5224 VecIn, DAG.getUNDEF(VecInVT),
5229 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5230 DebugLoc dl = Op.getDebugLoc();
5232 EVT VT = Op.getValueType();
5233 EVT ExtVT = VT.getVectorElementType();
5234 unsigned NumElems = Op.getNumOperands();
5236 // Vectors containing all zeros can be matched by pxor and xorps later
5237 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5238 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5239 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5240 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5243 return getZeroVector(VT, Subtarget, DAG, dl);
5246 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5247 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5248 // vpcmpeqd on 256-bit vectors.
5249 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5250 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5253 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5256 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5257 if (Broadcast.getNode())
5260 SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5261 if (FpExt.getNode())
5264 unsigned EVTBits = ExtVT.getSizeInBits();
5266 unsigned NumZero = 0;
5267 unsigned NumNonZero = 0;
5268 unsigned NonZeros = 0;
5269 bool IsAllConstants = true;
5270 SmallSet<SDValue, 8> Values;
5271 for (unsigned i = 0; i < NumElems; ++i) {
5272 SDValue Elt = Op.getOperand(i);
5273 if (Elt.getOpcode() == ISD::UNDEF)
5276 if (Elt.getOpcode() != ISD::Constant &&
5277 Elt.getOpcode() != ISD::ConstantFP)
5278 IsAllConstants = false;
5279 if (X86::isZeroNode(Elt))
5282 NonZeros |= (1 << i);
5287 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5288 if (NumNonZero == 0)
5289 return DAG.getUNDEF(VT);
5291 // Special case for single non-zero, non-undef, element.
5292 if (NumNonZero == 1) {
5293 unsigned Idx = CountTrailingZeros_32(NonZeros);
5294 SDValue Item = Op.getOperand(Idx);
5296 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5297 // the value are obviously zero, truncate the value to i32 and do the
5298 // insertion that way. Only do this if the value is non-constant or if the
5299 // value is a constant being inserted into element 0. It is cheaper to do
5300 // a constant pool load than it is to do a movd + shuffle.
5301 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5302 (!IsAllConstants || Idx == 0)) {
5303 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5305 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5306 EVT VecVT = MVT::v4i32;
5307 unsigned VecElts = 4;
5309 // Truncate the value (which may itself be a constant) to i32, and
5310 // convert it to a vector with movd (S2V+shuffle to zero extend).
5311 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5312 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5313 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5315 // Now we have our 32-bit value zero extended in the low element of
5316 // a vector. If Idx != 0, swizzle it into place.
5318 SmallVector<int, 4> Mask;
5319 Mask.push_back(Idx);
5320 for (unsigned i = 1; i != VecElts; ++i)
5322 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5325 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5329 // If we have a constant or non-constant insertion into the low element of
5330 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5331 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5332 // depending on what the source datatype is.
5335 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5337 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5338 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5339 if (VT.is256BitVector()) {
5340 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5341 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5342 Item, DAG.getIntPtrConstant(0));
5344 assert(VT.is128BitVector() && "Expected an SSE value type!");
5345 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5346 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5347 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5350 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5351 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5352 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5353 if (VT.is256BitVector()) {
5354 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5355 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5357 assert(VT.is128BitVector() && "Expected an SSE value type!");
5358 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5360 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5364 // Is it a vector logical left shift?
5365 if (NumElems == 2 && Idx == 1 &&
5366 X86::isZeroNode(Op.getOperand(0)) &&
5367 !X86::isZeroNode(Op.getOperand(1))) {
5368 unsigned NumBits = VT.getSizeInBits();
5369 return getVShift(true, VT,
5370 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5371 VT, Op.getOperand(1)),
5372 NumBits/2, DAG, *this, dl);
5375 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5378 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5379 // is a non-constant being inserted into an element other than the low one,
5380 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5381 // movd/movss) to move this into the low element, then shuffle it into
5383 if (EVTBits == 32) {
5384 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5386 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5387 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5388 SmallVector<int, 8> MaskVec;
5389 for (unsigned i = 0; i != NumElems; ++i)
5390 MaskVec.push_back(i == Idx ? 0 : 1);
5391 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5395 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5396 if (Values.size() == 1) {
5397 if (EVTBits == 32) {
5398 // Instead of a shuffle like this:
5399 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5400 // Check if it's possible to issue this instead.
5401 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5402 unsigned Idx = CountTrailingZeros_32(NonZeros);
5403 SDValue Item = Op.getOperand(Idx);
5404 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5405 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5410 // A vector full of immediates; various special cases are already
5411 // handled, so this is best done with a single constant-pool load.
5415 // For AVX-length vectors, build the individual 128-bit pieces and use
5416 // shuffles to put them in place.
5417 if (VT.is256BitVector()) {
5418 SmallVector<SDValue, 32> V;
5419 for (unsigned i = 0; i != NumElems; ++i)
5420 V.push_back(Op.getOperand(i));
5422 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5424 // Build both the lower and upper subvector.
5425 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5426 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5429 // Recreate the wider vector with the lower and upper part.
5430 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5433 // Let legalizer expand 2-wide build_vectors.
5434 if (EVTBits == 64) {
5435 if (NumNonZero == 1) {
5436 // One half is zero or undef.
5437 unsigned Idx = CountTrailingZeros_32(NonZeros);
5438 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5439 Op.getOperand(Idx));
5440 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5445 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5446 if (EVTBits == 8 && NumElems == 16) {
5447 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5449 if (V.getNode()) return V;
5452 if (EVTBits == 16 && NumElems == 8) {
5453 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5455 if (V.getNode()) return V;
5458 // If element VT is == 32 bits, turn it into a number of shuffles.
5459 SmallVector<SDValue, 8> V(NumElems);
5460 if (NumElems == 4 && NumZero > 0) {
5461 for (unsigned i = 0; i < 4; ++i) {
5462 bool isZero = !(NonZeros & (1 << i));
5464 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5466 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5469 for (unsigned i = 0; i < 2; ++i) {
5470 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5473 V[i] = V[i*2]; // Must be a zero vector.
5476 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5479 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5482 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5487 bool Reverse1 = (NonZeros & 0x3) == 2;
5488 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5492 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5493 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5495 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5498 if (Values.size() > 1 && VT.is128BitVector()) {
5499 // Check for a build vector of consecutive loads.
5500 for (unsigned i = 0; i < NumElems; ++i)
5501 V[i] = Op.getOperand(i);
5503 // Check for elements which are consecutive loads.
5504 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5508 // For SSE 4.1, use insertps to put the high elements into the low element.
5509 if (getSubtarget()->hasSSE41()) {
5511 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5512 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5514 Result = DAG.getUNDEF(VT);
5516 for (unsigned i = 1; i < NumElems; ++i) {
5517 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5518 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5519 Op.getOperand(i), DAG.getIntPtrConstant(i));
5524 // Otherwise, expand into a number of unpckl*, start by extending each of
5525 // our (non-undef) elements to the full vector width with the element in the
5526 // bottom slot of the vector (which generates no code for SSE).
5527 for (unsigned i = 0; i < NumElems; ++i) {
5528 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5529 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5531 V[i] = DAG.getUNDEF(VT);
5534 // Next, we iteratively mix elements, e.g. for v4f32:
5535 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5536 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5537 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5538 unsigned EltStride = NumElems >> 1;
5539 while (EltStride != 0) {
5540 for (unsigned i = 0; i < EltStride; ++i) {
5541 // If V[i+EltStride] is undef and this is the first round of mixing,
5542 // then it is safe to just drop this shuffle: V[i] is already in the
5543 // right place, the one element (since it's the first round) being
5544 // inserted as undef can be dropped. This isn't safe for successive
5545 // rounds because they will permute elements within both vectors.
5546 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5547 EltStride == NumElems/2)
5550 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5559 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5560 // to create 256-bit vectors from two other 128-bit ones.
5561 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5562 DebugLoc dl = Op.getDebugLoc();
5563 EVT ResVT = Op.getValueType();
5565 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5567 SDValue V1 = Op.getOperand(0);
5568 SDValue V2 = Op.getOperand(1);
5569 unsigned NumElems = ResVT.getVectorNumElements();
5571 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5574 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5575 assert(Op.getNumOperands() == 2);
5577 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5578 // from two other 128-bit ones.
5579 return LowerAVXCONCAT_VECTORS(Op, DAG);
5582 // Try to lower a shuffle node into a simple blend instruction.
5584 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5585 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5586 SDValue V1 = SVOp->getOperand(0);
5587 SDValue V2 = SVOp->getOperand(1);
5588 DebugLoc dl = SVOp->getDebugLoc();
5589 MVT VT = SVOp->getValueType(0).getSimpleVT();
5590 unsigned NumElems = VT.getVectorNumElements();
5592 if (!Subtarget->hasSSE41())
5598 switch (VT.SimpleTy) {
5599 default: return SDValue();
5601 ISDNo = X86ISD::BLENDPW;
5606 ISDNo = X86ISD::BLENDPS;
5611 ISDNo = X86ISD::BLENDPD;
5616 if (!Subtarget->hasAVX())
5618 ISDNo = X86ISD::BLENDPS;
5623 if (!Subtarget->hasAVX())
5625 ISDNo = X86ISD::BLENDPD;
5629 assert(ISDNo && "Invalid Op Number");
5631 unsigned MaskVals = 0;
5633 for (unsigned i = 0; i != NumElems; ++i) {
5634 int EltIdx = SVOp->getMaskElt(i);
5635 if (EltIdx == (int)i || EltIdx < 0)
5637 else if (EltIdx == (int)(i + NumElems))
5638 continue; // Bit is set to zero;
5643 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5644 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5645 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5646 DAG.getConstant(MaskVals, MVT::i32));
5647 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5650 // v8i16 shuffles - Prefer shuffles in the following order:
5651 // 1. [all] pshuflw, pshufhw, optional move
5652 // 2. [ssse3] 1 x pshufb
5653 // 3. [ssse3] 2 x pshufb + 1 x por
5654 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5656 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5657 SelectionDAG &DAG) {
5658 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5659 SDValue V1 = SVOp->getOperand(0);
5660 SDValue V2 = SVOp->getOperand(1);
5661 DebugLoc dl = SVOp->getDebugLoc();
5662 SmallVector<int, 8> MaskVals;
5664 // Determine if more than 1 of the words in each of the low and high quadwords
5665 // of the result come from the same quadword of one of the two inputs. Undef
5666 // mask values count as coming from any quadword, for better codegen.
5667 unsigned LoQuad[] = { 0, 0, 0, 0 };
5668 unsigned HiQuad[] = { 0, 0, 0, 0 };
5669 std::bitset<4> InputQuads;
5670 for (unsigned i = 0; i < 8; ++i) {
5671 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5672 int EltIdx = SVOp->getMaskElt(i);
5673 MaskVals.push_back(EltIdx);
5682 InputQuads.set(EltIdx / 4);
5685 int BestLoQuad = -1;
5686 unsigned MaxQuad = 1;
5687 for (unsigned i = 0; i < 4; ++i) {
5688 if (LoQuad[i] > MaxQuad) {
5690 MaxQuad = LoQuad[i];
5694 int BestHiQuad = -1;
5696 for (unsigned i = 0; i < 4; ++i) {
5697 if (HiQuad[i] > MaxQuad) {
5699 MaxQuad = HiQuad[i];
5703 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5704 // of the two input vectors, shuffle them into one input vector so only a
5705 // single pshufb instruction is necessary. If There are more than 2 input
5706 // quads, disable the next transformation since it does not help SSSE3.
5707 bool V1Used = InputQuads[0] || InputQuads[1];
5708 bool V2Used = InputQuads[2] || InputQuads[3];
5709 if (Subtarget->hasSSSE3()) {
5710 if (InputQuads.count() == 2 && V1Used && V2Used) {
5711 BestLoQuad = InputQuads[0] ? 0 : 1;
5712 BestHiQuad = InputQuads[2] ? 2 : 3;
5714 if (InputQuads.count() > 2) {
5720 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5721 // the shuffle mask. If a quad is scored as -1, that means that it contains
5722 // words from all 4 input quadwords.
5724 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5726 BestLoQuad < 0 ? 0 : BestLoQuad,
5727 BestHiQuad < 0 ? 1 : BestHiQuad
5729 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5730 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5731 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5732 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5734 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5735 // source words for the shuffle, to aid later transformations.
5736 bool AllWordsInNewV = true;
5737 bool InOrder[2] = { true, true };
5738 for (unsigned i = 0; i != 8; ++i) {
5739 int idx = MaskVals[i];
5741 InOrder[i/4] = false;
5742 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5744 AllWordsInNewV = false;
5748 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5749 if (AllWordsInNewV) {
5750 for (int i = 0; i != 8; ++i) {
5751 int idx = MaskVals[i];
5754 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5755 if ((idx != i) && idx < 4)
5757 if ((idx != i) && idx > 3)
5766 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5767 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5768 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5769 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5770 unsigned TargetMask = 0;
5771 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5772 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5773 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5774 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5775 getShufflePSHUFLWImmediate(SVOp);
5776 V1 = NewV.getOperand(0);
5777 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5781 // If we have SSSE3, and all words of the result are from 1 input vector,
5782 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5783 // is present, fall back to case 4.
5784 if (Subtarget->hasSSSE3()) {
5785 SmallVector<SDValue,16> pshufbMask;
5787 // If we have elements from both input vectors, set the high bit of the
5788 // shuffle mask element to zero out elements that come from V2 in the V1
5789 // mask, and elements that come from V1 in the V2 mask, so that the two
5790 // results can be OR'd together.
5791 bool TwoInputs = V1Used && V2Used;
5792 for (unsigned i = 0; i != 8; ++i) {
5793 int EltIdx = MaskVals[i] * 2;
5794 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5795 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5796 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5797 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5799 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5800 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5801 DAG.getNode(ISD::BUILD_VECTOR, dl,
5802 MVT::v16i8, &pshufbMask[0], 16));
5804 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5806 // Calculate the shuffle mask for the second input, shuffle it, and
5807 // OR it with the first shuffled input.
5809 for (unsigned i = 0; i != 8; ++i) {
5810 int EltIdx = MaskVals[i] * 2;
5811 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5812 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5813 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5814 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5816 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5817 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5818 DAG.getNode(ISD::BUILD_VECTOR, dl,
5819 MVT::v16i8, &pshufbMask[0], 16));
5820 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5821 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5824 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5825 // and update MaskVals with new element order.
5826 std::bitset<8> InOrder;
5827 if (BestLoQuad >= 0) {
5828 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5829 for (int i = 0; i != 4; ++i) {
5830 int idx = MaskVals[i];
5833 } else if ((idx / 4) == BestLoQuad) {
5838 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5841 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5842 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5843 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5845 getShufflePSHUFLWImmediate(SVOp), DAG);
5849 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5850 // and update MaskVals with the new element order.
5851 if (BestHiQuad >= 0) {
5852 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5853 for (unsigned i = 4; i != 8; ++i) {
5854 int idx = MaskVals[i];
5857 } else if ((idx / 4) == BestHiQuad) {
5858 MaskV[i] = (idx & 3) + 4;
5862 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5865 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5866 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5867 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5869 getShufflePSHUFHWImmediate(SVOp), DAG);
5873 // In case BestHi & BestLo were both -1, which means each quadword has a word
5874 // from each of the four input quadwords, calculate the InOrder bitvector now
5875 // before falling through to the insert/extract cleanup.
5876 if (BestLoQuad == -1 && BestHiQuad == -1) {
5878 for (int i = 0; i != 8; ++i)
5879 if (MaskVals[i] < 0 || MaskVals[i] == i)
5883 // The other elements are put in the right place using pextrw and pinsrw.
5884 for (unsigned i = 0; i != 8; ++i) {
5887 int EltIdx = MaskVals[i];
5890 SDValue ExtOp = (EltIdx < 8) ?
5891 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5892 DAG.getIntPtrConstant(EltIdx)) :
5893 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5894 DAG.getIntPtrConstant(EltIdx - 8));
5895 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5896 DAG.getIntPtrConstant(i));
5901 // v16i8 shuffles - Prefer shuffles in the following order:
5902 // 1. [ssse3] 1 x pshufb
5903 // 2. [ssse3] 2 x pshufb + 1 x por
5904 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5906 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5908 const X86TargetLowering &TLI) {
5909 SDValue V1 = SVOp->getOperand(0);
5910 SDValue V2 = SVOp->getOperand(1);
5911 DebugLoc dl = SVOp->getDebugLoc();
5912 ArrayRef<int> MaskVals = SVOp->getMask();
5914 // If we have SSSE3, case 1 is generated when all result bytes come from
5915 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5916 // present, fall back to case 3.
5918 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5919 if (TLI.getSubtarget()->hasSSSE3()) {
5920 SmallVector<SDValue,16> pshufbMask;
5922 // If all result elements are from one input vector, then only translate
5923 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5925 // Otherwise, we have elements from both input vectors, and must zero out
5926 // elements that come from V2 in the first mask, and V1 in the second mask
5927 // so that we can OR them together.
5928 for (unsigned i = 0; i != 16; ++i) {
5929 int EltIdx = MaskVals[i];
5930 if (EltIdx < 0 || EltIdx >= 16)
5932 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5934 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5935 DAG.getNode(ISD::BUILD_VECTOR, dl,
5936 MVT::v16i8, &pshufbMask[0], 16));
5938 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5939 // the 2nd operand if it's undefined or zero.
5940 if (V2.getOpcode() == ISD::UNDEF ||
5941 ISD::isBuildVectorAllZeros(V2.getNode()))
5944 // Calculate the shuffle mask for the second input, shuffle it, and
5945 // OR it with the first shuffled input.
5947 for (unsigned i = 0; i != 16; ++i) {
5948 int EltIdx = MaskVals[i];
5949 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5950 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5952 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5953 DAG.getNode(ISD::BUILD_VECTOR, dl,
5954 MVT::v16i8, &pshufbMask[0], 16));
5955 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5958 // No SSSE3 - Calculate in place words and then fix all out of place words
5959 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5960 // the 16 different words that comprise the two doublequadword input vectors.
5961 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5962 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5964 for (int i = 0; i != 8; ++i) {
5965 int Elt0 = MaskVals[i*2];
5966 int Elt1 = MaskVals[i*2+1];
5968 // This word of the result is all undef, skip it.
5969 if (Elt0 < 0 && Elt1 < 0)
5972 // This word of the result is already in the correct place, skip it.
5973 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5976 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5977 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5980 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5981 // using a single extract together, load it and store it.
5982 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5983 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5984 DAG.getIntPtrConstant(Elt1 / 2));
5985 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5986 DAG.getIntPtrConstant(i));
5990 // If Elt1 is defined, extract it from the appropriate source. If the
5991 // source byte is not also odd, shift the extracted word left 8 bits
5992 // otherwise clear the bottom 8 bits if we need to do an or.
5994 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5995 DAG.getIntPtrConstant(Elt1 / 2));
5996 if ((Elt1 & 1) == 0)
5997 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5999 TLI.getShiftAmountTy(InsElt.getValueType())));
6001 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6002 DAG.getConstant(0xFF00, MVT::i16));
6004 // If Elt0 is defined, extract it from the appropriate source. If the
6005 // source byte is not also even, shift the extracted word right 8 bits. If
6006 // Elt1 was also defined, OR the extracted values together before
6007 // inserting them in the result.
6009 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6010 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6011 if ((Elt0 & 1) != 0)
6012 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6014 TLI.getShiftAmountTy(InsElt0.getValueType())));
6016 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6017 DAG.getConstant(0x00FF, MVT::i16));
6018 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6021 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6022 DAG.getIntPtrConstant(i));
6024 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6027 // v32i8 shuffles - Translate to VPSHUFB if possible.
6029 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6030 const X86Subtarget *Subtarget,
6031 SelectionDAG &DAG) {
6032 EVT VT = SVOp->getValueType(0);
6033 SDValue V1 = SVOp->getOperand(0);
6034 SDValue V2 = SVOp->getOperand(1);
6035 DebugLoc dl = SVOp->getDebugLoc();
6036 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6038 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6039 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6040 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6042 // VPSHUFB may be generated if
6043 // (1) one of input vector is undefined or zeroinitializer.
6044 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6045 // And (2) the mask indexes don't cross the 128-bit lane.
6046 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6047 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6050 if (V1IsAllZero && !V2IsAllZero) {
6051 CommuteVectorShuffleMask(MaskVals, 32);
6054 SmallVector<SDValue, 32> pshufbMask;
6055 for (unsigned i = 0; i != 32; i++) {
6056 int EltIdx = MaskVals[i];
6057 if (EltIdx < 0 || EltIdx >= 32)
6060 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6061 // Cross lane is not allowed.
6065 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6067 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6068 DAG.getNode(ISD::BUILD_VECTOR, dl,
6069 MVT::v32i8, &pshufbMask[0], 32));
6072 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6073 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6074 /// done when every pair / quad of shuffle mask elements point to elements in
6075 /// the right sequence. e.g.
6076 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6078 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6079 SelectionDAG &DAG, DebugLoc dl) {
6080 MVT VT = SVOp->getValueType(0).getSimpleVT();
6081 unsigned NumElems = VT.getVectorNumElements();
6084 switch (VT.SimpleTy) {
6085 default: llvm_unreachable("Unexpected!");
6086 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6087 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6088 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6089 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6090 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6091 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6094 SmallVector<int, 8> MaskVec;
6095 for (unsigned i = 0; i != NumElems; i += Scale) {
6097 for (unsigned j = 0; j != Scale; ++j) {
6098 int EltIdx = SVOp->getMaskElt(i+j);
6102 StartIdx = (EltIdx / Scale);
6103 if (EltIdx != (int)(StartIdx*Scale + j))
6106 MaskVec.push_back(StartIdx);
6109 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6110 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6111 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6114 /// getVZextMovL - Return a zero-extending vector move low node.
6116 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6117 SDValue SrcOp, SelectionDAG &DAG,
6118 const X86Subtarget *Subtarget, DebugLoc dl) {
6119 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6120 LoadSDNode *LD = NULL;
6121 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6122 LD = dyn_cast<LoadSDNode>(SrcOp);
6124 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6126 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6127 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6128 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6129 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6130 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6132 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6133 return DAG.getNode(ISD::BITCAST, dl, VT,
6134 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6135 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6143 return DAG.getNode(ISD::BITCAST, dl, VT,
6144 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6145 DAG.getNode(ISD::BITCAST, dl,
6149 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6150 /// which could not be matched by any known target speficic shuffle
6152 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6154 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6155 if (NewOp.getNode())
6158 EVT VT = SVOp->getValueType(0);
6160 unsigned NumElems = VT.getVectorNumElements();
6161 unsigned NumLaneElems = NumElems / 2;
6163 DebugLoc dl = SVOp->getDebugLoc();
6164 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6165 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6168 SmallVector<int, 16> Mask;
6169 for (unsigned l = 0; l < 2; ++l) {
6170 // Build a shuffle mask for the output, discovering on the fly which
6171 // input vectors to use as shuffle operands (recorded in InputUsed).
6172 // If building a suitable shuffle vector proves too hard, then bail
6173 // out with UseBuildVector set.
6174 bool UseBuildVector = false;
6175 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6176 unsigned LaneStart = l * NumLaneElems;
6177 for (unsigned i = 0; i != NumLaneElems; ++i) {
6178 // The mask element. This indexes into the input.
6179 int Idx = SVOp->getMaskElt(i+LaneStart);
6181 // the mask element does not index into any input vector.
6186 // The input vector this mask element indexes into.
6187 int Input = Idx / NumLaneElems;
6189 // Turn the index into an offset from the start of the input vector.
6190 Idx -= Input * NumLaneElems;
6192 // Find or create a shuffle vector operand to hold this input.
6194 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6195 if (InputUsed[OpNo] == Input)
6196 // This input vector is already an operand.
6198 if (InputUsed[OpNo] < 0) {
6199 // Create a new operand for this input vector.
6200 InputUsed[OpNo] = Input;
6205 if (OpNo >= array_lengthof(InputUsed)) {
6206 // More than two input vectors used! Give up on trying to create a
6207 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6208 UseBuildVector = true;
6212 // Add the mask index for the new shuffle vector.
6213 Mask.push_back(Idx + OpNo * NumLaneElems);
6216 if (UseBuildVector) {
6217 SmallVector<SDValue, 16> SVOps;
6218 for (unsigned i = 0; i != NumLaneElems; ++i) {
6219 // The mask element. This indexes into the input.
6220 int Idx = SVOp->getMaskElt(i+LaneStart);
6222 SVOps.push_back(DAG.getUNDEF(EltVT));
6226 // The input vector this mask element indexes into.
6227 int Input = Idx / NumElems;
6229 // Turn the index into an offset from the start of the input vector.
6230 Idx -= Input * NumElems;
6232 // Extract the vector element by hand.
6233 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6234 SVOp->getOperand(Input),
6235 DAG.getIntPtrConstant(Idx)));
6238 // Construct the output using a BUILD_VECTOR.
6239 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6241 } else if (InputUsed[0] < 0) {
6242 // No input vectors were used! The result is undefined.
6243 Output[l] = DAG.getUNDEF(NVT);
6245 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6246 (InputUsed[0] % 2) * NumLaneElems,
6248 // If only one input was used, use an undefined vector for the other.
6249 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6250 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6251 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6252 // At least one input vector was used. Create a new shuffle vector.
6253 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6259 // Concatenate the result back
6260 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6263 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6264 /// 4 elements, and match them with several different shuffle types.
6266 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6267 SDValue V1 = SVOp->getOperand(0);
6268 SDValue V2 = SVOp->getOperand(1);
6269 DebugLoc dl = SVOp->getDebugLoc();
6270 EVT VT = SVOp->getValueType(0);
6272 assert(VT.is128BitVector() && "Unsupported vector size");
6274 std::pair<int, int> Locs[4];
6275 int Mask1[] = { -1, -1, -1, -1 };
6276 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6280 for (unsigned i = 0; i != 4; ++i) {
6281 int Idx = PermMask[i];
6283 Locs[i] = std::make_pair(-1, -1);
6285 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6287 Locs[i] = std::make_pair(0, NumLo);
6291 Locs[i] = std::make_pair(1, NumHi);
6293 Mask1[2+NumHi] = Idx;
6299 if (NumLo <= 2 && NumHi <= 2) {
6300 // If no more than two elements come from either vector. This can be
6301 // implemented with two shuffles. First shuffle gather the elements.
6302 // The second shuffle, which takes the first shuffle as both of its
6303 // vector operands, put the elements into the right order.
6304 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6306 int Mask2[] = { -1, -1, -1, -1 };
6308 for (unsigned i = 0; i != 4; ++i)
6309 if (Locs[i].first != -1) {
6310 unsigned Idx = (i < 2) ? 0 : 4;
6311 Idx += Locs[i].first * 2 + Locs[i].second;
6315 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6318 if (NumLo == 3 || NumHi == 3) {
6319 // Otherwise, we must have three elements from one vector, call it X, and
6320 // one element from the other, call it Y. First, use a shufps to build an
6321 // intermediate vector with the one element from Y and the element from X
6322 // that will be in the same half in the final destination (the indexes don't
6323 // matter). Then, use a shufps to build the final vector, taking the half
6324 // containing the element from Y from the intermediate, and the other half
6327 // Normalize it so the 3 elements come from V1.
6328 CommuteVectorShuffleMask(PermMask, 4);
6332 // Find the element from V2.
6334 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6335 int Val = PermMask[HiIndex];
6342 Mask1[0] = PermMask[HiIndex];
6344 Mask1[2] = PermMask[HiIndex^1];
6346 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6349 Mask1[0] = PermMask[0];
6350 Mask1[1] = PermMask[1];
6351 Mask1[2] = HiIndex & 1 ? 6 : 4;
6352 Mask1[3] = HiIndex & 1 ? 4 : 6;
6353 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6356 Mask1[0] = HiIndex & 1 ? 2 : 0;
6357 Mask1[1] = HiIndex & 1 ? 0 : 2;
6358 Mask1[2] = PermMask[2];
6359 Mask1[3] = PermMask[3];
6364 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6367 // Break it into (shuffle shuffle_hi, shuffle_lo).
6368 int LoMask[] = { -1, -1, -1, -1 };
6369 int HiMask[] = { -1, -1, -1, -1 };
6371 int *MaskPtr = LoMask;
6372 unsigned MaskIdx = 0;
6375 for (unsigned i = 0; i != 4; ++i) {
6382 int Idx = PermMask[i];
6384 Locs[i] = std::make_pair(-1, -1);
6385 } else if (Idx < 4) {
6386 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6387 MaskPtr[LoIdx] = Idx;
6390 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6391 MaskPtr[HiIdx] = Idx;
6396 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6397 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6398 int MaskOps[] = { -1, -1, -1, -1 };
6399 for (unsigned i = 0; i != 4; ++i)
6400 if (Locs[i].first != -1)
6401 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6402 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6405 static bool MayFoldVectorLoad(SDValue V) {
6406 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6407 V = V.getOperand(0);
6408 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6409 V = V.getOperand(0);
6410 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6411 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6412 // BUILD_VECTOR (load), undef
6413 V = V.getOperand(0);
6419 // FIXME: the version above should always be used. Since there's
6420 // a bug where several vector shuffles can't be folded because the
6421 // DAG is not updated during lowering and a node claims to have two
6422 // uses while it only has one, use this version, and let isel match
6423 // another instruction if the load really happens to have more than
6424 // one use. Remove this version after this bug get fixed.
6425 // rdar://8434668, PR8156
6426 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6427 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6428 V = V.getOperand(0);
6429 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6430 V = V.getOperand(0);
6431 if (ISD::isNormalLoad(V.getNode()))
6437 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6438 EVT VT = Op.getValueType();
6440 // Canonizalize to v2f64.
6441 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6442 return DAG.getNode(ISD::BITCAST, dl, VT,
6443 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6448 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6450 SDValue V1 = Op.getOperand(0);
6451 SDValue V2 = Op.getOperand(1);
6452 EVT VT = Op.getValueType();
6454 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6456 if (HasSSE2 && VT == MVT::v2f64)
6457 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6459 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6460 return DAG.getNode(ISD::BITCAST, dl, VT,
6461 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6462 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6463 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6467 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6468 SDValue V1 = Op.getOperand(0);
6469 SDValue V2 = Op.getOperand(1);
6470 EVT VT = Op.getValueType();
6472 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6473 "unsupported shuffle type");
6475 if (V2.getOpcode() == ISD::UNDEF)
6479 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6483 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6484 SDValue V1 = Op.getOperand(0);
6485 SDValue V2 = Op.getOperand(1);
6486 EVT VT = Op.getValueType();
6487 unsigned NumElems = VT.getVectorNumElements();
6489 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6490 // operand of these instructions is only memory, so check if there's a
6491 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6493 bool CanFoldLoad = false;
6495 // Trivial case, when V2 comes from a load.
6496 if (MayFoldVectorLoad(V2))
6499 // When V1 is a load, it can be folded later into a store in isel, example:
6500 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6502 // (MOVLPSmr addr:$src1, VR128:$src2)
6503 // So, recognize this potential and also use MOVLPS or MOVLPD
6504 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6507 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6509 if (HasSSE2 && NumElems == 2)
6510 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6513 // If we don't care about the second element, proceed to use movss.
6514 if (SVOp->getMaskElt(1) != -1)
6515 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6518 // movl and movlp will both match v2i64, but v2i64 is never matched by
6519 // movl earlier because we make it strict to avoid messing with the movlp load
6520 // folding logic (see the code above getMOVLP call). Match it here then,
6521 // this is horrible, but will stay like this until we move all shuffle
6522 // matching to x86 specific nodes. Note that for the 1st condition all
6523 // types are matched with movsd.
6525 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6526 // as to remove this logic from here, as much as possible
6527 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6528 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6529 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6532 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6534 // Invert the operand order and use SHUFPS to match it.
6535 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6536 getShuffleSHUFImmediate(SVOp), DAG);
6540 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6541 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6542 EVT VT = Op.getValueType();
6543 DebugLoc dl = Op.getDebugLoc();
6544 SDValue V1 = Op.getOperand(0);
6545 SDValue V2 = Op.getOperand(1);
6547 if (isZeroShuffle(SVOp))
6548 return getZeroVector(VT, Subtarget, DAG, dl);
6550 // Handle splat operations
6551 if (SVOp->isSplat()) {
6552 unsigned NumElem = VT.getVectorNumElements();
6553 int Size = VT.getSizeInBits();
6555 // Use vbroadcast whenever the splat comes from a foldable load
6556 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6557 if (Broadcast.getNode())
6560 // Handle splats by matching through known shuffle masks
6561 if ((Size == 128 && NumElem <= 4) ||
6562 (Size == 256 && NumElem < 8))
6565 // All remaning splats are promoted to target supported vector shuffles.
6566 return PromoteSplat(SVOp, DAG);
6569 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6571 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6572 VT == MVT::v16i16 || VT == MVT::v32i8) {
6573 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6574 if (NewOp.getNode())
6575 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6576 } else if ((VT == MVT::v4i32 ||
6577 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6578 // FIXME: Figure out a cleaner way to do this.
6579 // Try to make use of movq to zero out the top part.
6580 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6581 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6582 if (NewOp.getNode()) {
6583 EVT NewVT = NewOp.getValueType();
6584 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6585 NewVT, true, false))
6586 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6587 DAG, Subtarget, dl);
6589 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6590 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6591 if (NewOp.getNode()) {
6592 EVT NewVT = NewOp.getValueType();
6593 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6594 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6595 DAG, Subtarget, dl);
6603 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6604 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6605 SDValue V1 = Op.getOperand(0);
6606 SDValue V2 = Op.getOperand(1);
6607 EVT VT = Op.getValueType();
6608 DebugLoc dl = Op.getDebugLoc();
6609 unsigned NumElems = VT.getVectorNumElements();
6610 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6611 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6612 bool V1IsSplat = false;
6613 bool V2IsSplat = false;
6614 bool HasSSE2 = Subtarget->hasSSE2();
6615 bool HasAVX = Subtarget->hasAVX();
6616 bool HasAVX2 = Subtarget->hasAVX2();
6617 MachineFunction &MF = DAG.getMachineFunction();
6618 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6620 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6622 if (V1IsUndef && V2IsUndef)
6623 return DAG.getUNDEF(VT);
6625 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6627 // Vector shuffle lowering takes 3 steps:
6629 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6630 // narrowing and commutation of operands should be handled.
6631 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6633 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6634 // so the shuffle can be broken into other shuffles and the legalizer can
6635 // try the lowering again.
6637 // The general idea is that no vector_shuffle operation should be left to
6638 // be matched during isel, all of them must be converted to a target specific
6641 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6642 // narrowing and commutation of operands should be handled. The actual code
6643 // doesn't include all of those, work in progress...
6644 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6645 if (NewOp.getNode())
6648 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6650 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6651 // unpckh_undef). Only use pshufd if speed is more important than size.
6652 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6653 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6654 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6655 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6657 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6658 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6659 return getMOVDDup(Op, dl, V1, DAG);
6661 if (isMOVHLPS_v_undef_Mask(M, VT))
6662 return getMOVHighToLow(Op, dl, DAG);
6664 // Use to match splats
6665 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6666 (VT == MVT::v2f64 || VT == MVT::v2i64))
6667 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6669 if (isPSHUFDMask(M, VT)) {
6670 // The actual implementation will match the mask in the if above and then
6671 // during isel it can match several different instructions, not only pshufd
6672 // as its name says, sad but true, emulate the behavior for now...
6673 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6674 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6676 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6678 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6679 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6681 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6682 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6684 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6688 // Check if this can be converted into a logical shift.
6689 bool isLeft = false;
6692 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6693 if (isShift && ShVal.hasOneUse()) {
6694 // If the shifted value has multiple uses, it may be cheaper to use
6695 // v_set0 + movlhps or movhlps, etc.
6696 EVT EltVT = VT.getVectorElementType();
6697 ShAmt *= EltVT.getSizeInBits();
6698 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6701 if (isMOVLMask(M, VT)) {
6702 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6703 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6704 if (!isMOVLPMask(M, VT)) {
6705 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6706 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6708 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6709 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6713 // FIXME: fold these into legal mask.
6714 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6715 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6717 if (isMOVHLPSMask(M, VT))
6718 return getMOVHighToLow(Op, dl, DAG);
6720 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6721 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6723 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6724 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6726 if (isMOVLPMask(M, VT))
6727 return getMOVLP(Op, dl, DAG, HasSSE2);
6729 if (ShouldXformToMOVHLPS(M, VT) ||
6730 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6731 return CommuteVectorShuffle(SVOp, DAG);
6734 // No better options. Use a vshldq / vsrldq.
6735 EVT EltVT = VT.getVectorElementType();
6736 ShAmt *= EltVT.getSizeInBits();
6737 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6740 bool Commuted = false;
6741 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6742 // 1,1,1,1 -> v8i16 though.
6743 V1IsSplat = isSplatVector(V1.getNode());
6744 V2IsSplat = isSplatVector(V2.getNode());
6746 // Canonicalize the splat or undef, if present, to be on the RHS.
6747 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6748 CommuteVectorShuffleMask(M, NumElems);
6750 std::swap(V1IsSplat, V2IsSplat);
6754 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6755 // Shuffling low element of v1 into undef, just return v1.
6758 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6759 // the instruction selector will not match, so get a canonical MOVL with
6760 // swapped operands to undo the commute.
6761 return getMOVL(DAG, dl, VT, V2, V1);
6764 if (isUNPCKLMask(M, VT, HasAVX2))
6765 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6767 if (isUNPCKHMask(M, VT, HasAVX2))
6768 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6771 // Normalize mask so all entries that point to V2 points to its first
6772 // element then try to match unpck{h|l} again. If match, return a
6773 // new vector_shuffle with the corrected mask.p
6774 SmallVector<int, 8> NewMask(M.begin(), M.end());
6775 NormalizeMask(NewMask, NumElems);
6776 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6777 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6778 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6779 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6783 // Commute is back and try unpck* again.
6784 // FIXME: this seems wrong.
6785 CommuteVectorShuffleMask(M, NumElems);
6787 std::swap(V1IsSplat, V2IsSplat);
6790 if (isUNPCKLMask(M, VT, HasAVX2))
6791 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6793 if (isUNPCKHMask(M, VT, HasAVX2))
6794 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6797 // Normalize the node to match x86 shuffle ops if needed
6798 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6799 return CommuteVectorShuffle(SVOp, DAG);
6801 // The checks below are all present in isShuffleMaskLegal, but they are
6802 // inlined here right now to enable us to directly emit target specific
6803 // nodes, and remove one by one until they don't return Op anymore.
6805 if (isPALIGNRMask(M, VT, Subtarget))
6806 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6807 getShufflePALIGNRImmediate(SVOp),
6810 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6811 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6812 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6813 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6816 if (isPSHUFHWMask(M, VT, HasAVX2))
6817 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6818 getShufflePSHUFHWImmediate(SVOp),
6821 if (isPSHUFLWMask(M, VT, HasAVX2))
6822 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6823 getShufflePSHUFLWImmediate(SVOp),
6826 if (isSHUFPMask(M, VT, HasAVX))
6827 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6828 getShuffleSHUFImmediate(SVOp), DAG);
6830 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6831 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6832 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6833 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6835 //===--------------------------------------------------------------------===//
6836 // Generate target specific nodes for 128 or 256-bit shuffles only
6837 // supported in the AVX instruction set.
6840 // Handle VMOVDDUPY permutations
6841 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6842 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6844 // Handle VPERMILPS/D* permutations
6845 if (isVPERMILPMask(M, VT, HasAVX)) {
6846 if (HasAVX2 && VT == MVT::v8i32)
6847 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6848 getShuffleSHUFImmediate(SVOp), DAG);
6849 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6850 getShuffleSHUFImmediate(SVOp), DAG);
6853 // Handle VPERM2F128/VPERM2I128 permutations
6854 if (isVPERM2X128Mask(M, VT, HasAVX))
6855 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6856 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6858 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6859 if (BlendOp.getNode())
6862 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6863 SmallVector<SDValue, 8> permclMask;
6864 for (unsigned i = 0; i != 8; ++i) {
6865 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6867 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6869 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6870 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6871 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6874 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6875 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6876 getShuffleCLImmediate(SVOp), DAG);
6879 //===--------------------------------------------------------------------===//
6880 // Since no target specific shuffle was selected for this generic one,
6881 // lower it into other known shuffles. FIXME: this isn't true yet, but
6882 // this is the plan.
6885 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6886 if (VT == MVT::v8i16) {
6887 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6888 if (NewOp.getNode())
6892 if (VT == MVT::v16i8) {
6893 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6894 if (NewOp.getNode())
6898 if (VT == MVT::v32i8) {
6899 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6900 if (NewOp.getNode())
6904 // Handle all 128-bit wide vectors with 4 elements, and match them with
6905 // several different shuffle types.
6906 if (NumElems == 4 && VT.is128BitVector())
6907 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6909 // Handle general 256-bit shuffles
6910 if (VT.is256BitVector())
6911 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6917 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6918 SelectionDAG &DAG) const {
6919 EVT VT = Op.getValueType();
6920 DebugLoc dl = Op.getDebugLoc();
6922 if (!Op.getOperand(0).getValueType().is128BitVector())
6925 if (VT.getSizeInBits() == 8) {
6926 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6927 Op.getOperand(0), Op.getOperand(1));
6928 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6929 DAG.getValueType(VT));
6930 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6933 if (VT.getSizeInBits() == 16) {
6934 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6935 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6937 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6938 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6939 DAG.getNode(ISD::BITCAST, dl,
6943 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6944 Op.getOperand(0), Op.getOperand(1));
6945 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6946 DAG.getValueType(VT));
6947 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6950 if (VT == MVT::f32) {
6951 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6952 // the result back to FR32 register. It's only worth matching if the
6953 // result has a single use which is a store or a bitcast to i32. And in
6954 // the case of a store, it's not worth it if the index is a constant 0,
6955 // because a MOVSSmr can be used instead, which is smaller and faster.
6956 if (!Op.hasOneUse())
6958 SDNode *User = *Op.getNode()->use_begin();
6959 if ((User->getOpcode() != ISD::STORE ||
6960 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6961 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6962 (User->getOpcode() != ISD::BITCAST ||
6963 User->getValueType(0) != MVT::i32))
6965 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6966 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6969 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6972 if (VT == MVT::i32 || VT == MVT::i64) {
6973 // ExtractPS/pextrq works with constant index.
6974 if (isa<ConstantSDNode>(Op.getOperand(1)))
6982 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6983 SelectionDAG &DAG) const {
6984 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6987 SDValue Vec = Op.getOperand(0);
6988 EVT VecVT = Vec.getValueType();
6990 // If this is a 256-bit vector result, first extract the 128-bit vector and
6991 // then extract the element from the 128-bit vector.
6992 if (VecVT.is256BitVector()) {
6993 DebugLoc dl = Op.getNode()->getDebugLoc();
6994 unsigned NumElems = VecVT.getVectorNumElements();
6995 SDValue Idx = Op.getOperand(1);
6996 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6998 // Get the 128-bit vector.
6999 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7001 if (IdxVal >= NumElems/2)
7002 IdxVal -= NumElems/2;
7003 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7004 DAG.getConstant(IdxVal, MVT::i32));
7007 assert(VecVT.is128BitVector() && "Unexpected vector length");
7009 if (Subtarget->hasSSE41()) {
7010 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7015 EVT VT = Op.getValueType();
7016 DebugLoc dl = Op.getDebugLoc();
7017 // TODO: handle v16i8.
7018 if (VT.getSizeInBits() == 16) {
7019 SDValue Vec = Op.getOperand(0);
7020 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7022 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7023 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7024 DAG.getNode(ISD::BITCAST, dl,
7027 // Transform it so it match pextrw which produces a 32-bit result.
7028 EVT EltVT = MVT::i32;
7029 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7030 Op.getOperand(0), Op.getOperand(1));
7031 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7032 DAG.getValueType(VT));
7033 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7036 if (VT.getSizeInBits() == 32) {
7037 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7041 // SHUFPS the element to the lowest double word, then movss.
7042 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7043 EVT VVT = Op.getOperand(0).getValueType();
7044 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7045 DAG.getUNDEF(VVT), Mask);
7046 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7047 DAG.getIntPtrConstant(0));
7050 if (VT.getSizeInBits() == 64) {
7051 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7052 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7053 // to match extract_elt for f64.
7054 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7058 // UNPCKHPD the element to the lowest double word, then movsd.
7059 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7060 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7061 int Mask[2] = { 1, -1 };
7062 EVT VVT = Op.getOperand(0).getValueType();
7063 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7064 DAG.getUNDEF(VVT), Mask);
7065 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7066 DAG.getIntPtrConstant(0));
7073 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7074 SelectionDAG &DAG) const {
7075 EVT VT = Op.getValueType();
7076 EVT EltVT = VT.getVectorElementType();
7077 DebugLoc dl = Op.getDebugLoc();
7079 SDValue N0 = Op.getOperand(0);
7080 SDValue N1 = Op.getOperand(1);
7081 SDValue N2 = Op.getOperand(2);
7083 if (!VT.is128BitVector())
7086 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7087 isa<ConstantSDNode>(N2)) {
7089 if (VT == MVT::v8i16)
7090 Opc = X86ISD::PINSRW;
7091 else if (VT == MVT::v16i8)
7092 Opc = X86ISD::PINSRB;
7094 Opc = X86ISD::PINSRB;
7096 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7098 if (N1.getValueType() != MVT::i32)
7099 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7100 if (N2.getValueType() != MVT::i32)
7101 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7102 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7105 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7106 // Bits [7:6] of the constant are the source select. This will always be
7107 // zero here. The DAG Combiner may combine an extract_elt index into these
7108 // bits. For example (insert (extract, 3), 2) could be matched by putting
7109 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7110 // Bits [5:4] of the constant are the destination select. This is the
7111 // value of the incoming immediate.
7112 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7113 // combine either bitwise AND or insert of float 0.0 to set these bits.
7114 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7115 // Create this as a scalar to vector..
7116 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7117 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7120 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7121 // PINSR* works with constant index.
7128 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7129 EVT VT = Op.getValueType();
7130 EVT EltVT = VT.getVectorElementType();
7132 DebugLoc dl = Op.getDebugLoc();
7133 SDValue N0 = Op.getOperand(0);
7134 SDValue N1 = Op.getOperand(1);
7135 SDValue N2 = Op.getOperand(2);
7137 // If this is a 256-bit vector result, first extract the 128-bit vector,
7138 // insert the element into the extracted half and then place it back.
7139 if (VT.is256BitVector()) {
7140 if (!isa<ConstantSDNode>(N2))
7143 // Get the desired 128-bit vector half.
7144 unsigned NumElems = VT.getVectorNumElements();
7145 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7146 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7148 // Insert the element into the desired half.
7149 bool Upper = IdxVal >= NumElems/2;
7150 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7151 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7153 // Insert the changed part back to the 256-bit vector
7154 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7157 if (Subtarget->hasSSE41())
7158 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7160 if (EltVT == MVT::i8)
7163 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7164 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7165 // as its second argument.
7166 if (N1.getValueType() != MVT::i32)
7167 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7168 if (N2.getValueType() != MVT::i32)
7169 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7170 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7175 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7176 LLVMContext *Context = DAG.getContext();
7177 DebugLoc dl = Op.getDebugLoc();
7178 EVT OpVT = Op.getValueType();
7180 // If this is a 256-bit vector result, first insert into a 128-bit
7181 // vector and then insert into the 256-bit vector.
7182 if (!OpVT.is128BitVector()) {
7183 // Insert into a 128-bit vector.
7184 EVT VT128 = EVT::getVectorVT(*Context,
7185 OpVT.getVectorElementType(),
7186 OpVT.getVectorNumElements() / 2);
7188 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7190 // Insert the 128-bit vector.
7191 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7194 if (OpVT == MVT::v1i64 &&
7195 Op.getOperand(0).getValueType() == MVT::i64)
7196 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7198 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7199 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7200 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7201 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7204 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7205 // a simple subregister reference or explicit instructions to grab
7206 // upper bits of a vector.
7207 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7208 SelectionDAG &DAG) {
7209 if (Subtarget->hasAVX()) {
7210 DebugLoc dl = Op.getNode()->getDebugLoc();
7211 SDValue Vec = Op.getNode()->getOperand(0);
7212 SDValue Idx = Op.getNode()->getOperand(1);
7214 if (Op.getNode()->getValueType(0).is128BitVector() &&
7215 Vec.getNode()->getValueType(0).is256BitVector() &&
7216 isa<ConstantSDNode>(Idx)) {
7217 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7218 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7224 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7225 // simple superregister reference or explicit instructions to insert
7226 // the upper bits of a vector.
7227 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7228 SelectionDAG &DAG) {
7229 if (Subtarget->hasAVX()) {
7230 DebugLoc dl = Op.getNode()->getDebugLoc();
7231 SDValue Vec = Op.getNode()->getOperand(0);
7232 SDValue SubVec = Op.getNode()->getOperand(1);
7233 SDValue Idx = Op.getNode()->getOperand(2);
7235 if (Op.getNode()->getValueType(0).is256BitVector() &&
7236 SubVec.getNode()->getValueType(0).is128BitVector() &&
7237 isa<ConstantSDNode>(Idx)) {
7238 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7239 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7245 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7246 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7247 // one of the above mentioned nodes. It has to be wrapped because otherwise
7248 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7249 // be used to form addressing mode. These wrapped nodes will be selected
7252 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7253 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7255 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7257 unsigned char OpFlag = 0;
7258 unsigned WrapperKind = X86ISD::Wrapper;
7259 CodeModel::Model M = getTargetMachine().getCodeModel();
7261 if (Subtarget->isPICStyleRIPRel() &&
7262 (M == CodeModel::Small || M == CodeModel::Kernel))
7263 WrapperKind = X86ISD::WrapperRIP;
7264 else if (Subtarget->isPICStyleGOT())
7265 OpFlag = X86II::MO_GOTOFF;
7266 else if (Subtarget->isPICStyleStubPIC())
7267 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7269 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7271 CP->getOffset(), OpFlag);
7272 DebugLoc DL = CP->getDebugLoc();
7273 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7274 // With PIC, the address is actually $g + Offset.
7276 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7277 DAG.getNode(X86ISD::GlobalBaseReg,
7278 DebugLoc(), getPointerTy()),
7285 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7286 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7288 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7290 unsigned char OpFlag = 0;
7291 unsigned WrapperKind = X86ISD::Wrapper;
7292 CodeModel::Model M = getTargetMachine().getCodeModel();
7294 if (Subtarget->isPICStyleRIPRel() &&
7295 (M == CodeModel::Small || M == CodeModel::Kernel))
7296 WrapperKind = X86ISD::WrapperRIP;
7297 else if (Subtarget->isPICStyleGOT())
7298 OpFlag = X86II::MO_GOTOFF;
7299 else if (Subtarget->isPICStyleStubPIC())
7300 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7302 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7304 DebugLoc DL = JT->getDebugLoc();
7305 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7307 // With PIC, the address is actually $g + Offset.
7309 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7310 DAG.getNode(X86ISD::GlobalBaseReg,
7311 DebugLoc(), getPointerTy()),
7318 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7319 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7321 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7323 unsigned char OpFlag = 0;
7324 unsigned WrapperKind = X86ISD::Wrapper;
7325 CodeModel::Model M = getTargetMachine().getCodeModel();
7327 if (Subtarget->isPICStyleRIPRel() &&
7328 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7329 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7330 OpFlag = X86II::MO_GOTPCREL;
7331 WrapperKind = X86ISD::WrapperRIP;
7332 } else if (Subtarget->isPICStyleGOT()) {
7333 OpFlag = X86II::MO_GOT;
7334 } else if (Subtarget->isPICStyleStubPIC()) {
7335 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7336 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7337 OpFlag = X86II::MO_DARWIN_NONLAZY;
7340 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7342 DebugLoc DL = Op.getDebugLoc();
7343 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7346 // With PIC, the address is actually $g + Offset.
7347 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7348 !Subtarget->is64Bit()) {
7349 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7350 DAG.getNode(X86ISD::GlobalBaseReg,
7351 DebugLoc(), getPointerTy()),
7355 // For symbols that require a load from a stub to get the address, emit the
7357 if (isGlobalStubReference(OpFlag))
7358 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7359 MachinePointerInfo::getGOT(), false, false, false, 0);
7365 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7366 // Create the TargetBlockAddressAddress node.
7367 unsigned char OpFlags =
7368 Subtarget->ClassifyBlockAddressReference();
7369 CodeModel::Model M = getTargetMachine().getCodeModel();
7370 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7371 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7372 DebugLoc dl = Op.getDebugLoc();
7373 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7376 if (Subtarget->isPICStyleRIPRel() &&
7377 (M == CodeModel::Small || M == CodeModel::Kernel))
7378 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7380 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7382 // With PIC, the address is actually $g + Offset.
7383 if (isGlobalRelativeToPICBase(OpFlags)) {
7384 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7385 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7393 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7395 SelectionDAG &DAG) const {
7396 // Create the TargetGlobalAddress node, folding in the constant
7397 // offset if it is legal.
7398 unsigned char OpFlags =
7399 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7400 CodeModel::Model M = getTargetMachine().getCodeModel();
7402 if (OpFlags == X86II::MO_NO_FLAG &&
7403 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7404 // A direct static reference to a global.
7405 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7408 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7411 if (Subtarget->isPICStyleRIPRel() &&
7412 (M == CodeModel::Small || M == CodeModel::Kernel))
7413 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7415 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7417 // With PIC, the address is actually $g + Offset.
7418 if (isGlobalRelativeToPICBase(OpFlags)) {
7419 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7420 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7424 // For globals that require a load from a stub to get the address, emit the
7426 if (isGlobalStubReference(OpFlags))
7427 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7428 MachinePointerInfo::getGOT(), false, false, false, 0);
7430 // If there was a non-zero offset that we didn't fold, create an explicit
7433 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7434 DAG.getConstant(Offset, getPointerTy()));
7440 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7441 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7442 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7443 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7447 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7448 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7449 unsigned char OperandFlags, bool LocalDynamic = false) {
7450 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7451 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7452 DebugLoc dl = GA->getDebugLoc();
7453 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7454 GA->getValueType(0),
7458 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7462 SDValue Ops[] = { Chain, TGA, *InFlag };
7463 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7465 SDValue Ops[] = { Chain, TGA };
7466 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7469 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7470 MFI->setAdjustsStack(true);
7472 SDValue Flag = Chain.getValue(1);
7473 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7476 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7478 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7481 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7482 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7483 DAG.getNode(X86ISD::GlobalBaseReg,
7484 DebugLoc(), PtrVT), InFlag);
7485 InFlag = Chain.getValue(1);
7487 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7490 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7492 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7494 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7495 X86::RAX, X86II::MO_TLSGD);
7498 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7502 DebugLoc dl = GA->getDebugLoc();
7504 // Get the start address of the TLS block for this module.
7505 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7506 .getInfo<X86MachineFunctionInfo>();
7507 MFI->incNumLocalDynamicTLSAccesses();
7511 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7512 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7515 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7516 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7517 InFlag = Chain.getValue(1);
7518 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7519 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7522 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7526 unsigned char OperandFlags = X86II::MO_DTPOFF;
7527 unsigned WrapperKind = X86ISD::Wrapper;
7528 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7529 GA->getValueType(0),
7530 GA->getOffset(), OperandFlags);
7531 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7533 // Add x@dtpoff with the base.
7534 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7537 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7538 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7539 const EVT PtrVT, TLSModel::Model model,
7540 bool is64Bit, bool isPIC) {
7541 DebugLoc dl = GA->getDebugLoc();
7543 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7544 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7545 is64Bit ? 257 : 256));
7547 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7548 DAG.getIntPtrConstant(0),
7549 MachinePointerInfo(Ptr),
7550 false, false, false, 0);
7552 unsigned char OperandFlags = 0;
7553 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7555 unsigned WrapperKind = X86ISD::Wrapper;
7556 if (model == TLSModel::LocalExec) {
7557 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7558 } else if (model == TLSModel::InitialExec) {
7560 OperandFlags = X86II::MO_GOTTPOFF;
7561 WrapperKind = X86ISD::WrapperRIP;
7563 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7566 llvm_unreachable("Unexpected model");
7569 // emit "addl x@ntpoff,%eax" (local exec)
7570 // or "addl x@indntpoff,%eax" (initial exec)
7571 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7572 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7573 GA->getValueType(0),
7574 GA->getOffset(), OperandFlags);
7575 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7577 if (model == TLSModel::InitialExec) {
7578 if (isPIC && !is64Bit) {
7579 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7580 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7584 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7585 MachinePointerInfo::getGOT(), false, false, false,
7589 // The address of the thread local variable is the add of the thread
7590 // pointer with the offset of the variable.
7591 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7595 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7597 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7598 const GlobalValue *GV = GA->getGlobal();
7600 if (Subtarget->isTargetELF()) {
7601 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7604 case TLSModel::GeneralDynamic:
7605 if (Subtarget->is64Bit())
7606 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7607 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7608 case TLSModel::LocalDynamic:
7609 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7610 Subtarget->is64Bit());
7611 case TLSModel::InitialExec:
7612 case TLSModel::LocalExec:
7613 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7614 Subtarget->is64Bit(),
7615 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7617 llvm_unreachable("Unknown TLS model.");
7620 if (Subtarget->isTargetDarwin()) {
7621 // Darwin only has one model of TLS. Lower to that.
7622 unsigned char OpFlag = 0;
7623 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7624 X86ISD::WrapperRIP : X86ISD::Wrapper;
7626 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7628 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7629 !Subtarget->is64Bit();
7631 OpFlag = X86II::MO_TLVP_PIC_BASE;
7633 OpFlag = X86II::MO_TLVP;
7634 DebugLoc DL = Op.getDebugLoc();
7635 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7636 GA->getValueType(0),
7637 GA->getOffset(), OpFlag);
7638 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7640 // With PIC32, the address is actually $g + Offset.
7642 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7643 DAG.getNode(X86ISD::GlobalBaseReg,
7644 DebugLoc(), getPointerTy()),
7647 // Lowering the machine isd will make sure everything is in the right
7649 SDValue Chain = DAG.getEntryNode();
7650 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7651 SDValue Args[] = { Chain, Offset };
7652 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7654 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7655 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7656 MFI->setAdjustsStack(true);
7658 // And our return value (tls address) is in the standard call return value
7660 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7661 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7665 if (Subtarget->isTargetWindows()) {
7666 // Just use the implicit TLS architecture
7667 // Need to generate someting similar to:
7668 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7670 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7671 // mov rcx, qword [rdx+rcx*8]
7672 // mov eax, .tls$:tlsvar
7673 // [rax+rcx] contains the address
7674 // Windows 64bit: gs:0x58
7675 // Windows 32bit: fs:__tls_array
7677 // If GV is an alias then use the aliasee for determining
7678 // thread-localness.
7679 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7680 GV = GA->resolveAliasedGlobal(false);
7681 DebugLoc dl = GA->getDebugLoc();
7682 SDValue Chain = DAG.getEntryNode();
7684 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7685 // %gs:0x58 (64-bit).
7686 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7687 ? Type::getInt8PtrTy(*DAG.getContext(),
7689 : Type::getInt32PtrTy(*DAG.getContext(),
7692 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7693 Subtarget->is64Bit()
7694 ? DAG.getIntPtrConstant(0x58)
7695 : DAG.getExternalSymbol("_tls_array",
7697 MachinePointerInfo(Ptr),
7698 false, false, false, 0);
7700 // Load the _tls_index variable
7701 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7702 if (Subtarget->is64Bit())
7703 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7704 IDX, MachinePointerInfo(), MVT::i32,
7707 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7708 false, false, false, 0);
7710 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7712 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7714 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7715 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7716 false, false, false, 0);
7718 // Get the offset of start of .tls section
7719 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7720 GA->getValueType(0),
7721 GA->getOffset(), X86II::MO_SECREL);
7722 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7724 // The address of the thread local variable is the add of the thread
7725 // pointer with the offset of the variable.
7726 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7729 llvm_unreachable("TLS not implemented for this target.");
7733 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7734 /// and take a 2 x i32 value to shift plus a shift amount.
7735 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7736 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7737 EVT VT = Op.getValueType();
7738 unsigned VTBits = VT.getSizeInBits();
7739 DebugLoc dl = Op.getDebugLoc();
7740 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7741 SDValue ShOpLo = Op.getOperand(0);
7742 SDValue ShOpHi = Op.getOperand(1);
7743 SDValue ShAmt = Op.getOperand(2);
7744 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7745 DAG.getConstant(VTBits - 1, MVT::i8))
7746 : DAG.getConstant(0, VT);
7749 if (Op.getOpcode() == ISD::SHL_PARTS) {
7750 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7751 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7753 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7754 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7757 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7758 DAG.getConstant(VTBits, MVT::i8));
7759 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7760 AndNode, DAG.getConstant(0, MVT::i8));
7763 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7764 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7765 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7767 if (Op.getOpcode() == ISD::SHL_PARTS) {
7768 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7769 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7771 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7772 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7775 SDValue Ops[2] = { Lo, Hi };
7776 return DAG.getMergeValues(Ops, 2, dl);
7779 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7780 SelectionDAG &DAG) const {
7781 EVT SrcVT = Op.getOperand(0).getValueType();
7783 if (SrcVT.isVector())
7786 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7787 "Unknown SINT_TO_FP to lower!");
7789 // These are really Legal; return the operand so the caller accepts it as
7791 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7793 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7794 Subtarget->is64Bit()) {
7798 DebugLoc dl = Op.getDebugLoc();
7799 unsigned Size = SrcVT.getSizeInBits()/8;
7800 MachineFunction &MF = DAG.getMachineFunction();
7801 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7802 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7803 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7805 MachinePointerInfo::getFixedStack(SSFI),
7807 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7810 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7812 SelectionDAG &DAG) const {
7814 DebugLoc DL = Op.getDebugLoc();
7816 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7818 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7820 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7822 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7824 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7825 MachineMemOperand *MMO;
7827 int SSFI = FI->getIndex();
7829 DAG.getMachineFunction()
7830 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7831 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7833 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7834 StackSlot = StackSlot.getOperand(1);
7836 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7837 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7839 Tys, Ops, array_lengthof(Ops),
7843 Chain = Result.getValue(1);
7844 SDValue InFlag = Result.getValue(2);
7846 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7847 // shouldn't be necessary except that RFP cannot be live across
7848 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7849 MachineFunction &MF = DAG.getMachineFunction();
7850 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7851 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7852 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7853 Tys = DAG.getVTList(MVT::Other);
7855 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7857 MachineMemOperand *MMO =
7858 DAG.getMachineFunction()
7859 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7860 MachineMemOperand::MOStore, SSFISize, SSFISize);
7862 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7863 Ops, array_lengthof(Ops),
7864 Op.getValueType(), MMO);
7865 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7866 MachinePointerInfo::getFixedStack(SSFI),
7867 false, false, false, 0);
7873 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7874 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7875 SelectionDAG &DAG) const {
7876 // This algorithm is not obvious. Here it is what we're trying to output:
7879 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7880 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7884 pshufd $0x4e, %xmm0, %xmm1
7889 DebugLoc dl = Op.getDebugLoc();
7890 LLVMContext *Context = DAG.getContext();
7892 // Build some magic constants.
7893 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7894 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7895 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7897 SmallVector<Constant*,2> CV1;
7899 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7901 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7902 Constant *C1 = ConstantVector::get(CV1);
7903 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7905 // Load the 64-bit value into an XMM register.
7906 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7908 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7909 MachinePointerInfo::getConstantPool(),
7910 false, false, false, 16);
7911 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7912 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7915 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7916 MachinePointerInfo::getConstantPool(),
7917 false, false, false, 16);
7918 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7919 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7922 if (Subtarget->hasSSE3()) {
7923 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7924 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7926 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7927 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7929 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7930 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7935 DAG.getIntPtrConstant(0));
7938 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7939 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7940 SelectionDAG &DAG) const {
7941 DebugLoc dl = Op.getDebugLoc();
7942 // FP constant to bias correct the final result.
7943 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7946 // Load the 32-bit value into an XMM register.
7947 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7950 // Zero out the upper parts of the register.
7951 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7953 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7954 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7955 DAG.getIntPtrConstant(0));
7957 // Or the load with the bias.
7958 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7959 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7960 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7962 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7963 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7964 MVT::v2f64, Bias)));
7965 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7966 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7967 DAG.getIntPtrConstant(0));
7969 // Subtract the bias.
7970 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7972 // Handle final rounding.
7973 EVT DestVT = Op.getValueType();
7975 if (DestVT.bitsLT(MVT::f64))
7976 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7977 DAG.getIntPtrConstant(0));
7978 if (DestVT.bitsGT(MVT::f64))
7979 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7981 // Handle final rounding.
7985 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7986 SelectionDAG &DAG) const {
7987 SDValue N0 = Op.getOperand(0);
7988 DebugLoc dl = Op.getDebugLoc();
7990 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7991 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7992 // the optimization here.
7993 if (DAG.SignBitIsZero(N0))
7994 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7996 EVT SrcVT = N0.getValueType();
7997 EVT DstVT = Op.getValueType();
7998 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7999 return LowerUINT_TO_FP_i64(Op, DAG);
8000 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8001 return LowerUINT_TO_FP_i32(Op, DAG);
8002 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8005 // Make a 64-bit buffer, and use it to build an FILD.
8006 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8007 if (SrcVT == MVT::i32) {
8008 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8009 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8010 getPointerTy(), StackSlot, WordOff);
8011 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8012 StackSlot, MachinePointerInfo(),
8014 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8015 OffsetSlot, MachinePointerInfo(),
8017 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8021 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8022 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8023 StackSlot, MachinePointerInfo(),
8025 // For i64 source, we need to add the appropriate power of 2 if the input
8026 // was negative. This is the same as the optimization in
8027 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8028 // we must be careful to do the computation in x87 extended precision, not
8029 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8030 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8031 MachineMemOperand *MMO =
8032 DAG.getMachineFunction()
8033 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8034 MachineMemOperand::MOLoad, 8, 8);
8036 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8037 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8038 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8041 APInt FF(32, 0x5F800000ULL);
8043 // Check whether the sign bit is set.
8044 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8045 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8048 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8049 SDValue FudgePtr = DAG.getConstantPool(
8050 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8053 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8054 SDValue Zero = DAG.getIntPtrConstant(0);
8055 SDValue Four = DAG.getIntPtrConstant(4);
8056 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8058 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8060 // Load the value out, extending it from f32 to f80.
8061 // FIXME: Avoid the extend by constructing the right constant pool?
8062 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8063 FudgePtr, MachinePointerInfo::getConstantPool(),
8064 MVT::f32, false, false, 4);
8065 // Extend everything to 80 bits to force it to be done on x87.
8066 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8067 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8070 std::pair<SDValue,SDValue> X86TargetLowering::
8071 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8072 DebugLoc DL = Op.getDebugLoc();
8074 EVT DstTy = Op.getValueType();
8076 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8077 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8081 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8082 DstTy.getSimpleVT() >= MVT::i16 &&
8083 "Unknown FP_TO_INT to lower!");
8085 // These are really Legal.
8086 if (DstTy == MVT::i32 &&
8087 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8088 return std::make_pair(SDValue(), SDValue());
8089 if (Subtarget->is64Bit() &&
8090 DstTy == MVT::i64 &&
8091 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8092 return std::make_pair(SDValue(), SDValue());
8094 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8095 // stack slot, or into the FTOL runtime function.
8096 MachineFunction &MF = DAG.getMachineFunction();
8097 unsigned MemSize = DstTy.getSizeInBits()/8;
8098 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8099 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8102 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8103 Opc = X86ISD::WIN_FTOL;
8105 switch (DstTy.getSimpleVT().SimpleTy) {
8106 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8107 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8108 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8109 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8112 SDValue Chain = DAG.getEntryNode();
8113 SDValue Value = Op.getOperand(0);
8114 EVT TheVT = Op.getOperand(0).getValueType();
8115 // FIXME This causes a redundant load/store if the SSE-class value is already
8116 // in memory, such as if it is on the callstack.
8117 if (isScalarFPTypeInSSEReg(TheVT)) {
8118 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8119 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8120 MachinePointerInfo::getFixedStack(SSFI),
8122 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8124 Chain, StackSlot, DAG.getValueType(TheVT)
8127 MachineMemOperand *MMO =
8128 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8129 MachineMemOperand::MOLoad, MemSize, MemSize);
8130 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8132 Chain = Value.getValue(1);
8133 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8134 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8137 MachineMemOperand *MMO =
8138 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8139 MachineMemOperand::MOStore, MemSize, MemSize);
8141 if (Opc != X86ISD::WIN_FTOL) {
8142 // Build the FP_TO_INT*_IN_MEM
8143 SDValue Ops[] = { Chain, Value, StackSlot };
8144 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8145 Ops, 3, DstTy, MMO);
8146 return std::make_pair(FIST, StackSlot);
8148 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8149 DAG.getVTList(MVT::Other, MVT::Glue),
8151 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8152 MVT::i32, ftol.getValue(1));
8153 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8154 MVT::i32, eax.getValue(2));
8155 SDValue Ops[] = { eax, edx };
8156 SDValue pair = IsReplace
8157 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8158 : DAG.getMergeValues(Ops, 2, DL);
8159 return std::make_pair(pair, SDValue());
8163 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8164 SelectionDAG &DAG) const {
8165 if (Op.getValueType().isVector())
8168 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8169 /*IsSigned=*/ true, /*IsReplace=*/ false);
8170 SDValue FIST = Vals.first, StackSlot = Vals.second;
8171 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8172 if (FIST.getNode() == 0) return Op;
8174 if (StackSlot.getNode())
8176 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8177 FIST, StackSlot, MachinePointerInfo(),
8178 false, false, false, 0);
8180 // The node is the result.
8184 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8185 SelectionDAG &DAG) const {
8186 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8187 /*IsSigned=*/ false, /*IsReplace=*/ false);
8188 SDValue FIST = Vals.first, StackSlot = Vals.second;
8189 assert(FIST.getNode() && "Unexpected failure");
8191 if (StackSlot.getNode())
8193 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8194 FIST, StackSlot, MachinePointerInfo(),
8195 false, false, false, 0);
8197 // The node is the result.
8201 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8202 LLVMContext *Context = DAG.getContext();
8203 DebugLoc dl = Op.getDebugLoc();
8204 EVT VT = Op.getValueType();
8206 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8207 if (VT.isVector()) {
8208 EltVT = VT.getVectorElementType();
8209 NumElts = VT.getVectorNumElements();
8212 if (EltVT == MVT::f64)
8213 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8215 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8216 C = ConstantVector::getSplat(NumElts, C);
8217 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8218 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8219 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8220 MachinePointerInfo::getConstantPool(),
8221 false, false, false, Alignment);
8222 if (VT.isVector()) {
8223 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8224 return DAG.getNode(ISD::BITCAST, dl, VT,
8225 DAG.getNode(ISD::AND, dl, ANDVT,
8226 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8228 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8230 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8233 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8234 LLVMContext *Context = DAG.getContext();
8235 DebugLoc dl = Op.getDebugLoc();
8236 EVT VT = Op.getValueType();
8238 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8239 if (VT.isVector()) {
8240 EltVT = VT.getVectorElementType();
8241 NumElts = VT.getVectorNumElements();
8244 if (EltVT == MVT::f64)
8245 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8247 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8248 C = ConstantVector::getSplat(NumElts, C);
8249 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8250 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8251 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8252 MachinePointerInfo::getConstantPool(),
8253 false, false, false, Alignment);
8254 if (VT.isVector()) {
8255 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8256 return DAG.getNode(ISD::BITCAST, dl, VT,
8257 DAG.getNode(ISD::XOR, dl, XORVT,
8258 DAG.getNode(ISD::BITCAST, dl, XORVT,
8260 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8263 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8266 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8267 LLVMContext *Context = DAG.getContext();
8268 SDValue Op0 = Op.getOperand(0);
8269 SDValue Op1 = Op.getOperand(1);
8270 DebugLoc dl = Op.getDebugLoc();
8271 EVT VT = Op.getValueType();
8272 EVT SrcVT = Op1.getValueType();
8274 // If second operand is smaller, extend it first.
8275 if (SrcVT.bitsLT(VT)) {
8276 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8279 // And if it is bigger, shrink it first.
8280 if (SrcVT.bitsGT(VT)) {
8281 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8285 // At this point the operands and the result should have the same
8286 // type, and that won't be f80 since that is not custom lowered.
8288 // First get the sign bit of second operand.
8289 SmallVector<Constant*,4> CV;
8290 if (SrcVT == MVT::f64) {
8291 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8292 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8294 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8295 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8296 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8297 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8299 Constant *C = ConstantVector::get(CV);
8300 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8301 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8302 MachinePointerInfo::getConstantPool(),
8303 false, false, false, 16);
8304 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8306 // Shift sign bit right or left if the two operands have different types.
8307 if (SrcVT.bitsGT(VT)) {
8308 // Op0 is MVT::f32, Op1 is MVT::f64.
8309 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8310 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8311 DAG.getConstant(32, MVT::i32));
8312 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8313 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8314 DAG.getIntPtrConstant(0));
8317 // Clear first operand sign bit.
8319 if (VT == MVT::f64) {
8320 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8321 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8323 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8324 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8325 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8326 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8328 C = ConstantVector::get(CV);
8329 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8330 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8331 MachinePointerInfo::getConstantPool(),
8332 false, false, false, 16);
8333 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8335 // Or the value with the sign bit.
8336 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8339 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8340 SDValue N0 = Op.getOperand(0);
8341 DebugLoc dl = Op.getDebugLoc();
8342 EVT VT = Op.getValueType();
8344 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8345 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8346 DAG.getConstant(1, VT));
8347 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8350 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8352 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8353 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8355 if (!Subtarget->hasSSE41())
8358 if (!Op->hasOneUse())
8361 SDNode *N = Op.getNode();
8362 DebugLoc DL = N->getDebugLoc();
8364 SmallVector<SDValue, 8> Opnds;
8365 DenseMap<SDValue, unsigned> VecInMap;
8366 EVT VT = MVT::Other;
8368 // Recognize a special case where a vector is casted into wide integer to
8370 Opnds.push_back(N->getOperand(0));
8371 Opnds.push_back(N->getOperand(1));
8373 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8374 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8375 // BFS traverse all OR'd operands.
8376 if (I->getOpcode() == ISD::OR) {
8377 Opnds.push_back(I->getOperand(0));
8378 Opnds.push_back(I->getOperand(1));
8379 // Re-evaluate the number of nodes to be traversed.
8380 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8384 // Quit if a non-EXTRACT_VECTOR_ELT
8385 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8388 // Quit if without a constant index.
8389 SDValue Idx = I->getOperand(1);
8390 if (!isa<ConstantSDNode>(Idx))
8393 SDValue ExtractedFromVec = I->getOperand(0);
8394 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8395 if (M == VecInMap.end()) {
8396 VT = ExtractedFromVec.getValueType();
8397 // Quit if not 128/256-bit vector.
8398 if (!VT.is128BitVector() && !VT.is256BitVector())
8400 // Quit if not the same type.
8401 if (VecInMap.begin() != VecInMap.end() &&
8402 VT != VecInMap.begin()->first.getValueType())
8404 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8406 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8409 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8410 "Not extracted from 128-/256-bit vector.");
8412 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8413 SmallVector<SDValue, 8> VecIns;
8415 for (DenseMap<SDValue, unsigned>::const_iterator
8416 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8417 // Quit if not all elements are used.
8418 if (I->second != FullMask)
8420 VecIns.push_back(I->first);
8423 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8425 // Cast all vectors into TestVT for PTEST.
8426 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8427 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8429 // If more than one full vectors are evaluated, OR them first before PTEST.
8430 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8431 // Each iteration will OR 2 nodes and append the result until there is only
8432 // 1 node left, i.e. the final OR'd value of all vectors.
8433 SDValue LHS = VecIns[Slot];
8434 SDValue RHS = VecIns[Slot + 1];
8435 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8438 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8439 VecIns.back(), VecIns.back());
8442 /// Emit nodes that will be selected as "test Op0,Op0", or something
8444 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8445 SelectionDAG &DAG) const {
8446 DebugLoc dl = Op.getDebugLoc();
8448 // CF and OF aren't always set the way we want. Determine which
8449 // of these we need.
8450 bool NeedCF = false;
8451 bool NeedOF = false;
8454 case X86::COND_A: case X86::COND_AE:
8455 case X86::COND_B: case X86::COND_BE:
8458 case X86::COND_G: case X86::COND_GE:
8459 case X86::COND_L: case X86::COND_LE:
8460 case X86::COND_O: case X86::COND_NO:
8465 // See if we can use the EFLAGS value from the operand instead of
8466 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8467 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8468 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8469 // Emit a CMP with 0, which is the TEST pattern.
8470 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8471 DAG.getConstant(0, Op.getValueType()));
8473 unsigned Opcode = 0;
8474 unsigned NumOperands = 0;
8476 // Truncate operations may prevent the merge of the SETCC instruction
8477 // and the arithmetic intruction before it. Attempt to truncate the operands
8478 // of the arithmetic instruction and use a reduced bit-width instruction.
8479 bool NeedTruncation = false;
8480 SDValue ArithOp = Op;
8481 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8482 SDValue Arith = Op->getOperand(0);
8483 // Both the trunc and the arithmetic op need to have one user each.
8484 if (Arith->hasOneUse())
8485 switch (Arith.getOpcode()) {
8492 NeedTruncation = true;
8498 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8499 // which may be the result of a CAST. We use the variable 'Op', which is the
8500 // non-casted variable when we check for possible users.
8501 switch (ArithOp.getOpcode()) {
8503 // Due to an isel shortcoming, be conservative if this add is likely to be
8504 // selected as part of a load-modify-store instruction. When the root node
8505 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8506 // uses of other nodes in the match, such as the ADD in this case. This
8507 // leads to the ADD being left around and reselected, with the result being
8508 // two adds in the output. Alas, even if none our users are stores, that
8509 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8510 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8511 // climbing the DAG back to the root, and it doesn't seem to be worth the
8513 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8514 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8515 if (UI->getOpcode() != ISD::CopyToReg &&
8516 UI->getOpcode() != ISD::SETCC &&
8517 UI->getOpcode() != ISD::STORE)
8520 if (ConstantSDNode *C =
8521 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8522 // An add of one will be selected as an INC.
8523 if (C->getAPIntValue() == 1) {
8524 Opcode = X86ISD::INC;
8529 // An add of negative one (subtract of one) will be selected as a DEC.
8530 if (C->getAPIntValue().isAllOnesValue()) {
8531 Opcode = X86ISD::DEC;
8537 // Otherwise use a regular EFLAGS-setting add.
8538 Opcode = X86ISD::ADD;
8542 // If the primary and result isn't used, don't bother using X86ISD::AND,
8543 // because a TEST instruction will be better.
8544 bool NonFlagUse = false;
8545 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8546 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8548 unsigned UOpNo = UI.getOperandNo();
8549 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8550 // Look pass truncate.
8551 UOpNo = User->use_begin().getOperandNo();
8552 User = *User->use_begin();
8555 if (User->getOpcode() != ISD::BRCOND &&
8556 User->getOpcode() != ISD::SETCC &&
8557 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8570 // Due to the ISEL shortcoming noted above, be conservative if this op is
8571 // likely to be selected as part of a load-modify-store instruction.
8572 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8573 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8574 if (UI->getOpcode() == ISD::STORE)
8577 // Otherwise use a regular EFLAGS-setting instruction.
8578 switch (ArithOp.getOpcode()) {
8579 default: llvm_unreachable("unexpected operator!");
8580 case ISD::SUB: Opcode = X86ISD::SUB; break;
8581 case ISD::XOR: Opcode = X86ISD::XOR; break;
8582 case ISD::AND: Opcode = X86ISD::AND; break;
8584 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8585 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8586 if (EFLAGS.getNode())
8589 Opcode = X86ISD::OR;
8603 return SDValue(Op.getNode(), 1);
8609 // If we found that truncation is beneficial, perform the truncation and
8611 if (NeedTruncation) {
8612 EVT VT = Op.getValueType();
8613 SDValue WideVal = Op->getOperand(0);
8614 EVT WideVT = WideVal.getValueType();
8615 unsigned ConvertedOp = 0;
8616 // Use a target machine opcode to prevent further DAGCombine
8617 // optimizations that may separate the arithmetic operations
8618 // from the setcc node.
8619 switch (WideVal.getOpcode()) {
8621 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8622 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8623 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8624 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8625 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8629 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8630 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8631 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8632 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8633 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8639 // Emit a CMP with 0, which is the TEST pattern.
8640 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8641 DAG.getConstant(0, Op.getValueType()));
8643 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8644 SmallVector<SDValue, 4> Ops;
8645 for (unsigned i = 0; i != NumOperands; ++i)
8646 Ops.push_back(Op.getOperand(i));
8648 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8649 DAG.ReplaceAllUsesWith(Op, New);
8650 return SDValue(New.getNode(), 1);
8653 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8655 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8656 SelectionDAG &DAG) const {
8657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8658 if (C->getAPIntValue() == 0)
8659 return EmitTest(Op0, X86CC, DAG);
8661 DebugLoc dl = Op0.getDebugLoc();
8662 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8663 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8664 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8665 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8666 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8668 return SDValue(Sub.getNode(), 1);
8670 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8673 /// Convert a comparison if required by the subtarget.
8674 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8675 SelectionDAG &DAG) const {
8676 // If the subtarget does not support the FUCOMI instruction, floating-point
8677 // comparisons have to be converted.
8678 if (Subtarget->hasCMov() ||
8679 Cmp.getOpcode() != X86ISD::CMP ||
8680 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8681 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8684 // The instruction selector will select an FUCOM instruction instead of
8685 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8686 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8687 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8688 DebugLoc dl = Cmp.getDebugLoc();
8689 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8690 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8691 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8692 DAG.getConstant(8, MVT::i8));
8693 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8694 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8697 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8698 /// if it's possible.
8699 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8700 DebugLoc dl, SelectionDAG &DAG) const {
8701 SDValue Op0 = And.getOperand(0);
8702 SDValue Op1 = And.getOperand(1);
8703 if (Op0.getOpcode() == ISD::TRUNCATE)
8704 Op0 = Op0.getOperand(0);
8705 if (Op1.getOpcode() == ISD::TRUNCATE)
8706 Op1 = Op1.getOperand(0);
8709 if (Op1.getOpcode() == ISD::SHL)
8710 std::swap(Op0, Op1);
8711 if (Op0.getOpcode() == ISD::SHL) {
8712 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8713 if (And00C->getZExtValue() == 1) {
8714 // If we looked past a truncate, check that it's only truncating away
8716 unsigned BitWidth = Op0.getValueSizeInBits();
8717 unsigned AndBitWidth = And.getValueSizeInBits();
8718 if (BitWidth > AndBitWidth) {
8720 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8721 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8725 RHS = Op0.getOperand(1);
8727 } else if (Op1.getOpcode() == ISD::Constant) {
8728 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8729 uint64_t AndRHSVal = AndRHS->getZExtValue();
8730 SDValue AndLHS = Op0;
8732 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8733 LHS = AndLHS.getOperand(0);
8734 RHS = AndLHS.getOperand(1);
8737 // Use BT if the immediate can't be encoded in a TEST instruction.
8738 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8740 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8744 if (LHS.getNode()) {
8745 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8746 // instruction. Since the shift amount is in-range-or-undefined, we know
8747 // that doing a bittest on the i32 value is ok. We extend to i32 because
8748 // the encoding for the i16 version is larger than the i32 version.
8749 // Also promote i16 to i32 for performance / code size reason.
8750 if (LHS.getValueType() == MVT::i8 ||
8751 LHS.getValueType() == MVT::i16)
8752 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8754 // If the operand types disagree, extend the shift amount to match. Since
8755 // BT ignores high bits (like shifts) we can use anyextend.
8756 if (LHS.getValueType() != RHS.getValueType())
8757 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8759 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8760 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8761 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8762 DAG.getConstant(Cond, MVT::i8), BT);
8768 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8770 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8772 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8773 SDValue Op0 = Op.getOperand(0);
8774 SDValue Op1 = Op.getOperand(1);
8775 DebugLoc dl = Op.getDebugLoc();
8776 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8778 // Optimize to BT if possible.
8779 // Lower (X & (1 << N)) == 0 to BT(X, N).
8780 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8781 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8782 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8783 Op1.getOpcode() == ISD::Constant &&
8784 cast<ConstantSDNode>(Op1)->isNullValue() &&
8785 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8786 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8787 if (NewSetCC.getNode())
8791 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8793 if (Op1.getOpcode() == ISD::Constant &&
8794 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8795 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8796 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8798 // If the input is a setcc, then reuse the input setcc or use a new one with
8799 // the inverted condition.
8800 if (Op0.getOpcode() == X86ISD::SETCC) {
8801 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8802 bool Invert = (CC == ISD::SETNE) ^
8803 cast<ConstantSDNode>(Op1)->isNullValue();
8804 if (!Invert) return Op0;
8806 CCode = X86::GetOppositeBranchCondition(CCode);
8807 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8808 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8812 bool isFP = Op1.getValueType().isFloatingPoint();
8813 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8814 if (X86CC == X86::COND_INVALID)
8817 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8818 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8819 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8820 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8823 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8824 // ones, and then concatenate the result back.
8825 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8826 EVT VT = Op.getValueType();
8828 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8829 "Unsupported value type for operation");
8831 unsigned NumElems = VT.getVectorNumElements();
8832 DebugLoc dl = Op.getDebugLoc();
8833 SDValue CC = Op.getOperand(2);
8835 // Extract the LHS vectors
8836 SDValue LHS = Op.getOperand(0);
8837 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8838 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8840 // Extract the RHS vectors
8841 SDValue RHS = Op.getOperand(1);
8842 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8843 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8845 // Issue the operation on the smaller types and concatenate the result back
8846 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8847 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8848 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8849 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8850 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8854 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8856 SDValue Op0 = Op.getOperand(0);
8857 SDValue Op1 = Op.getOperand(1);
8858 SDValue CC = Op.getOperand(2);
8859 EVT VT = Op.getValueType();
8860 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8861 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8862 DebugLoc dl = Op.getDebugLoc();
8866 EVT EltVT = Op0.getValueType().getVectorElementType();
8867 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8873 // SSE Condition code mapping:
8882 switch (SetCCOpcode) {
8883 default: llvm_unreachable("Unexpected SETCC condition");
8885 case ISD::SETEQ: SSECC = 0; break;
8887 case ISD::SETGT: Swap = true; // Fallthrough
8889 case ISD::SETOLT: SSECC = 1; break;
8891 case ISD::SETGE: Swap = true; // Fallthrough
8893 case ISD::SETOLE: SSECC = 2; break;
8894 case ISD::SETUO: SSECC = 3; break;
8896 case ISD::SETNE: SSECC = 4; break;
8897 case ISD::SETULE: Swap = true; // Fallthrough
8898 case ISD::SETUGE: SSECC = 5; break;
8899 case ISD::SETULT: Swap = true; // Fallthrough
8900 case ISD::SETUGT: SSECC = 6; break;
8901 case ISD::SETO: SSECC = 7; break;
8903 case ISD::SETONE: SSECC = 8; break;
8906 std::swap(Op0, Op1);
8908 // In the two special cases we can't handle, emit two comparisons.
8911 unsigned CombineOpc;
8912 if (SetCCOpcode == ISD::SETUEQ) {
8913 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8915 assert(SetCCOpcode == ISD::SETONE);
8916 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8919 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8920 DAG.getConstant(CC0, MVT::i8));
8921 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8922 DAG.getConstant(CC1, MVT::i8));
8923 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8925 // Handle all other FP comparisons here.
8926 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8927 DAG.getConstant(SSECC, MVT::i8));
8930 // Break 256-bit integer vector compare into smaller ones.
8931 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8932 return Lower256IntVSETCC(Op, DAG);
8934 // We are handling one of the integer comparisons here. Since SSE only has
8935 // GT and EQ comparisons for integer, swapping operands and multiple
8936 // operations may be required for some comparisons.
8938 bool Swap = false, Invert = false, FlipSigns = false;
8940 switch (SetCCOpcode) {
8941 default: llvm_unreachable("Unexpected SETCC condition");
8942 case ISD::SETNE: Invert = true;
8943 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8944 case ISD::SETLT: Swap = true;
8945 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8946 case ISD::SETGE: Swap = true;
8947 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8948 case ISD::SETULT: Swap = true;
8949 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8950 case ISD::SETUGE: Swap = true;
8951 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8954 std::swap(Op0, Op1);
8956 // Check that the operation in question is available (most are plain SSE2,
8957 // but PCMPGTQ and PCMPEQQ have different requirements).
8958 if (VT == MVT::v2i64) {
8959 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8961 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8965 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8966 // bits of the inputs before performing those operations.
8968 EVT EltVT = VT.getVectorElementType();
8969 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8971 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8972 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8974 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8975 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8978 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8980 // If the logical-not of the result is required, perform that now.
8982 Result = DAG.getNOT(dl, Result, VT);
8987 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8988 static bool isX86LogicalCmp(SDValue Op) {
8989 unsigned Opc = Op.getNode()->getOpcode();
8990 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8991 Opc == X86ISD::SAHF)
8993 if (Op.getResNo() == 1 &&
8994 (Opc == X86ISD::ADD ||
8995 Opc == X86ISD::SUB ||
8996 Opc == X86ISD::ADC ||
8997 Opc == X86ISD::SBB ||
8998 Opc == X86ISD::SMUL ||
8999 Opc == X86ISD::UMUL ||
9000 Opc == X86ISD::INC ||
9001 Opc == X86ISD::DEC ||
9002 Opc == X86ISD::OR ||
9003 Opc == X86ISD::XOR ||
9004 Opc == X86ISD::AND))
9007 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9013 static bool isZero(SDValue V) {
9014 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9015 return C && C->isNullValue();
9018 static bool isAllOnes(SDValue V) {
9019 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9020 return C && C->isAllOnesValue();
9023 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9024 if (V.getOpcode() != ISD::TRUNCATE)
9027 SDValue VOp0 = V.getOperand(0);
9028 unsigned InBits = VOp0.getValueSizeInBits();
9029 unsigned Bits = V.getValueSizeInBits();
9030 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9033 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9034 bool addTest = true;
9035 SDValue Cond = Op.getOperand(0);
9036 SDValue Op1 = Op.getOperand(1);
9037 SDValue Op2 = Op.getOperand(2);
9038 DebugLoc DL = Op.getDebugLoc();
9041 if (Cond.getOpcode() == ISD::SETCC) {
9042 SDValue NewCond = LowerSETCC(Cond, DAG);
9043 if (NewCond.getNode())
9047 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9048 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9049 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9050 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9051 if (Cond.getOpcode() == X86ISD::SETCC &&
9052 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9053 isZero(Cond.getOperand(1).getOperand(1))) {
9054 SDValue Cmp = Cond.getOperand(1);
9056 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9058 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9059 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9060 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9062 SDValue CmpOp0 = Cmp.getOperand(0);
9063 // Apply further optimizations for special cases
9064 // (select (x != 0), -1, 0) -> neg & sbb
9065 // (select (x == 0), 0, -1) -> neg & sbb
9066 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9067 if (YC->isNullValue() &&
9068 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9069 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9070 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9071 DAG.getConstant(0, CmpOp0.getValueType()),
9073 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9074 DAG.getConstant(X86::COND_B, MVT::i8),
9075 SDValue(Neg.getNode(), 1));
9079 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9080 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9081 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9083 SDValue Res = // Res = 0 or -1.
9084 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9085 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9087 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9088 Res = DAG.getNOT(DL, Res, Res.getValueType());
9090 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9091 if (N2C == 0 || !N2C->isNullValue())
9092 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9097 // Look past (and (setcc_carry (cmp ...)), 1).
9098 if (Cond.getOpcode() == ISD::AND &&
9099 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9100 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9101 if (C && C->getAPIntValue() == 1)
9102 Cond = Cond.getOperand(0);
9105 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9106 // setting operand in place of the X86ISD::SETCC.
9107 unsigned CondOpcode = Cond.getOpcode();
9108 if (CondOpcode == X86ISD::SETCC ||
9109 CondOpcode == X86ISD::SETCC_CARRY) {
9110 CC = Cond.getOperand(0);
9112 SDValue Cmp = Cond.getOperand(1);
9113 unsigned Opc = Cmp.getOpcode();
9114 EVT VT = Op.getValueType();
9116 bool IllegalFPCMov = false;
9117 if (VT.isFloatingPoint() && !VT.isVector() &&
9118 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9119 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9121 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9122 Opc == X86ISD::BT) { // FIXME
9126 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9127 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9128 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9129 Cond.getOperand(0).getValueType() != MVT::i8)) {
9130 SDValue LHS = Cond.getOperand(0);
9131 SDValue RHS = Cond.getOperand(1);
9135 switch (CondOpcode) {
9136 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9137 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9138 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9139 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9140 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9141 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9142 default: llvm_unreachable("unexpected overflowing operator");
9144 if (CondOpcode == ISD::UMULO)
9145 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9148 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9150 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9152 if (CondOpcode == ISD::UMULO)
9153 Cond = X86Op.getValue(2);
9155 Cond = X86Op.getValue(1);
9157 CC = DAG.getConstant(X86Cond, MVT::i8);
9162 // Look pass the truncate if the high bits are known zero.
9163 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9164 Cond = Cond.getOperand(0);
9166 // We know the result of AND is compared against zero. Try to match
9168 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9169 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9170 if (NewSetCC.getNode()) {
9171 CC = NewSetCC.getOperand(0);
9172 Cond = NewSetCC.getOperand(1);
9179 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9180 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9183 // a < b ? -1 : 0 -> RES = ~setcc_carry
9184 // a < b ? 0 : -1 -> RES = setcc_carry
9185 // a >= b ? -1 : 0 -> RES = setcc_carry
9186 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9187 if (Cond.getOpcode() == X86ISD::SUB) {
9188 Cond = ConvertCmpIfNecessary(Cond, DAG);
9189 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9191 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9192 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9193 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9194 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9195 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9196 return DAG.getNOT(DL, Res, Res.getValueType());
9201 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9202 // condition is true.
9203 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9204 SDValue Ops[] = { Op2, Op1, CC, Cond };
9205 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9208 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9209 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9210 // from the AND / OR.
9211 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9212 Opc = Op.getOpcode();
9213 if (Opc != ISD::OR && Opc != ISD::AND)
9215 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9216 Op.getOperand(0).hasOneUse() &&
9217 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9218 Op.getOperand(1).hasOneUse());
9221 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9222 // 1 and that the SETCC node has a single use.
9223 static bool isXor1OfSetCC(SDValue Op) {
9224 if (Op.getOpcode() != ISD::XOR)
9226 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9227 if (N1C && N1C->getAPIntValue() == 1) {
9228 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9229 Op.getOperand(0).hasOneUse();
9234 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9235 bool addTest = true;
9236 SDValue Chain = Op.getOperand(0);
9237 SDValue Cond = Op.getOperand(1);
9238 SDValue Dest = Op.getOperand(2);
9239 DebugLoc dl = Op.getDebugLoc();
9241 bool Inverted = false;
9243 if (Cond.getOpcode() == ISD::SETCC) {
9244 // Check for setcc([su]{add,sub,mul}o == 0).
9245 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9246 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9247 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9248 Cond.getOperand(0).getResNo() == 1 &&
9249 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9250 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9251 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9252 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9253 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9254 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9256 Cond = Cond.getOperand(0);
9258 SDValue NewCond = LowerSETCC(Cond, DAG);
9259 if (NewCond.getNode())
9264 // FIXME: LowerXALUO doesn't handle these!!
9265 else if (Cond.getOpcode() == X86ISD::ADD ||
9266 Cond.getOpcode() == X86ISD::SUB ||
9267 Cond.getOpcode() == X86ISD::SMUL ||
9268 Cond.getOpcode() == X86ISD::UMUL)
9269 Cond = LowerXALUO(Cond, DAG);
9272 // Look pass (and (setcc_carry (cmp ...)), 1).
9273 if (Cond.getOpcode() == ISD::AND &&
9274 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9276 if (C && C->getAPIntValue() == 1)
9277 Cond = Cond.getOperand(0);
9280 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9281 // setting operand in place of the X86ISD::SETCC.
9282 unsigned CondOpcode = Cond.getOpcode();
9283 if (CondOpcode == X86ISD::SETCC ||
9284 CondOpcode == X86ISD::SETCC_CARRY) {
9285 CC = Cond.getOperand(0);
9287 SDValue Cmp = Cond.getOperand(1);
9288 unsigned Opc = Cmp.getOpcode();
9289 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9290 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9294 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9298 // These can only come from an arithmetic instruction with overflow,
9299 // e.g. SADDO, UADDO.
9300 Cond = Cond.getNode()->getOperand(1);
9306 CondOpcode = Cond.getOpcode();
9307 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9308 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9309 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9310 Cond.getOperand(0).getValueType() != MVT::i8)) {
9311 SDValue LHS = Cond.getOperand(0);
9312 SDValue RHS = Cond.getOperand(1);
9316 switch (CondOpcode) {
9317 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9318 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9319 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9320 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9321 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9322 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9323 default: llvm_unreachable("unexpected overflowing operator");
9326 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9327 if (CondOpcode == ISD::UMULO)
9328 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9331 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9333 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9335 if (CondOpcode == ISD::UMULO)
9336 Cond = X86Op.getValue(2);
9338 Cond = X86Op.getValue(1);
9340 CC = DAG.getConstant(X86Cond, MVT::i8);
9344 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9345 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9346 if (CondOpc == ISD::OR) {
9347 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9348 // two branches instead of an explicit OR instruction with a
9350 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9351 isX86LogicalCmp(Cmp)) {
9352 CC = Cond.getOperand(0).getOperand(0);
9353 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9354 Chain, Dest, CC, Cmp);
9355 CC = Cond.getOperand(1).getOperand(0);
9359 } else { // ISD::AND
9360 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9361 // two branches instead of an explicit AND instruction with a
9362 // separate test. However, we only do this if this block doesn't
9363 // have a fall-through edge, because this requires an explicit
9364 // jmp when the condition is false.
9365 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9366 isX86LogicalCmp(Cmp) &&
9367 Op.getNode()->hasOneUse()) {
9368 X86::CondCode CCode =
9369 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9370 CCode = X86::GetOppositeBranchCondition(CCode);
9371 CC = DAG.getConstant(CCode, MVT::i8);
9372 SDNode *User = *Op.getNode()->use_begin();
9373 // Look for an unconditional branch following this conditional branch.
9374 // We need this because we need to reverse the successors in order
9375 // to implement FCMP_OEQ.
9376 if (User->getOpcode() == ISD::BR) {
9377 SDValue FalseBB = User->getOperand(1);
9379 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9380 assert(NewBR == User);
9384 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9385 Chain, Dest, CC, Cmp);
9386 X86::CondCode CCode =
9387 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9388 CCode = X86::GetOppositeBranchCondition(CCode);
9389 CC = DAG.getConstant(CCode, MVT::i8);
9395 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9396 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9397 // It should be transformed during dag combiner except when the condition
9398 // is set by a arithmetics with overflow node.
9399 X86::CondCode CCode =
9400 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9401 CCode = X86::GetOppositeBranchCondition(CCode);
9402 CC = DAG.getConstant(CCode, MVT::i8);
9403 Cond = Cond.getOperand(0).getOperand(1);
9405 } else if (Cond.getOpcode() == ISD::SETCC &&
9406 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9407 // For FCMP_OEQ, we can emit
9408 // two branches instead of an explicit AND instruction with a
9409 // separate test. However, we only do this if this block doesn't
9410 // have a fall-through edge, because this requires an explicit
9411 // jmp when the condition is false.
9412 if (Op.getNode()->hasOneUse()) {
9413 SDNode *User = *Op.getNode()->use_begin();
9414 // Look for an unconditional branch following this conditional branch.
9415 // We need this because we need to reverse the successors in order
9416 // to implement FCMP_OEQ.
9417 if (User->getOpcode() == ISD::BR) {
9418 SDValue FalseBB = User->getOperand(1);
9420 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9421 assert(NewBR == User);
9425 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9426 Cond.getOperand(0), Cond.getOperand(1));
9427 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9428 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9429 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9430 Chain, Dest, CC, Cmp);
9431 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9436 } else if (Cond.getOpcode() == ISD::SETCC &&
9437 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9438 // For FCMP_UNE, we can emit
9439 // two branches instead of an explicit AND instruction with a
9440 // separate test. However, we only do this if this block doesn't
9441 // have a fall-through edge, because this requires an explicit
9442 // jmp when the condition is false.
9443 if (Op.getNode()->hasOneUse()) {
9444 SDNode *User = *Op.getNode()->use_begin();
9445 // Look for an unconditional branch following this conditional branch.
9446 // We need this because we need to reverse the successors in order
9447 // to implement FCMP_UNE.
9448 if (User->getOpcode() == ISD::BR) {
9449 SDValue FalseBB = User->getOperand(1);
9451 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9452 assert(NewBR == User);
9455 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9456 Cond.getOperand(0), Cond.getOperand(1));
9457 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9458 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9459 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9460 Chain, Dest, CC, Cmp);
9461 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9471 // Look pass the truncate if the high bits are known zero.
9472 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9473 Cond = Cond.getOperand(0);
9475 // We know the result of AND is compared against zero. Try to match
9477 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9478 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9479 if (NewSetCC.getNode()) {
9480 CC = NewSetCC.getOperand(0);
9481 Cond = NewSetCC.getOperand(1);
9488 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9489 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9491 Cond = ConvertCmpIfNecessary(Cond, DAG);
9492 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9493 Chain, Dest, CC, Cond);
9497 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9498 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9499 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9500 // that the guard pages used by the OS virtual memory manager are allocated in
9501 // correct sequence.
9503 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9504 SelectionDAG &DAG) const {
9505 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9506 getTargetMachine().Options.EnableSegmentedStacks) &&
9507 "This should be used only on Windows targets or when segmented stacks "
9509 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9510 DebugLoc dl = Op.getDebugLoc();
9513 SDValue Chain = Op.getOperand(0);
9514 SDValue Size = Op.getOperand(1);
9515 // FIXME: Ensure alignment here
9517 bool Is64Bit = Subtarget->is64Bit();
9518 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9520 if (getTargetMachine().Options.EnableSegmentedStacks) {
9521 MachineFunction &MF = DAG.getMachineFunction();
9522 MachineRegisterInfo &MRI = MF.getRegInfo();
9525 // The 64 bit implementation of segmented stacks needs to clobber both r10
9526 // r11. This makes it impossible to use it along with nested parameters.
9527 const Function *F = MF.getFunction();
9529 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9531 if (I->hasNestAttr())
9532 report_fatal_error("Cannot use segmented stacks with functions that "
9533 "have nested arguments.");
9536 const TargetRegisterClass *AddrRegClass =
9537 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9538 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9539 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9540 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9541 DAG.getRegister(Vreg, SPTy));
9542 SDValue Ops1[2] = { Value, Chain };
9543 return DAG.getMergeValues(Ops1, 2, dl);
9546 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9548 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9549 Flag = Chain.getValue(1);
9550 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9552 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9553 Flag = Chain.getValue(1);
9555 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9557 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9558 return DAG.getMergeValues(Ops1, 2, dl);
9562 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9563 MachineFunction &MF = DAG.getMachineFunction();
9564 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9566 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9567 DebugLoc DL = Op.getDebugLoc();
9569 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9570 // vastart just stores the address of the VarArgsFrameIndex slot into the
9571 // memory location argument.
9572 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9574 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9575 MachinePointerInfo(SV), false, false, 0);
9579 // gp_offset (0 - 6 * 8)
9580 // fp_offset (48 - 48 + 8 * 16)
9581 // overflow_arg_area (point to parameters coming in memory).
9583 SmallVector<SDValue, 8> MemOps;
9584 SDValue FIN = Op.getOperand(1);
9586 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9587 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9589 FIN, MachinePointerInfo(SV), false, false, 0);
9590 MemOps.push_back(Store);
9593 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9594 FIN, DAG.getIntPtrConstant(4));
9595 Store = DAG.getStore(Op.getOperand(0), DL,
9596 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9598 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9599 MemOps.push_back(Store);
9601 // Store ptr to overflow_arg_area
9602 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9603 FIN, DAG.getIntPtrConstant(4));
9604 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9606 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9607 MachinePointerInfo(SV, 8),
9609 MemOps.push_back(Store);
9611 // Store ptr to reg_save_area.
9612 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9613 FIN, DAG.getIntPtrConstant(8));
9614 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9616 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9617 MachinePointerInfo(SV, 16), false, false, 0);
9618 MemOps.push_back(Store);
9619 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9620 &MemOps[0], MemOps.size());
9623 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9624 assert(Subtarget->is64Bit() &&
9625 "LowerVAARG only handles 64-bit va_arg!");
9626 assert((Subtarget->isTargetLinux() ||
9627 Subtarget->isTargetDarwin()) &&
9628 "Unhandled target in LowerVAARG");
9629 assert(Op.getNode()->getNumOperands() == 4);
9630 SDValue Chain = Op.getOperand(0);
9631 SDValue SrcPtr = Op.getOperand(1);
9632 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9633 unsigned Align = Op.getConstantOperandVal(3);
9634 DebugLoc dl = Op.getDebugLoc();
9636 EVT ArgVT = Op.getNode()->getValueType(0);
9637 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9638 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9641 // Decide which area this value should be read from.
9642 // TODO: Implement the AMD64 ABI in its entirety. This simple
9643 // selection mechanism works only for the basic types.
9644 if (ArgVT == MVT::f80) {
9645 llvm_unreachable("va_arg for f80 not yet implemented");
9646 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9647 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9648 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9649 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9651 llvm_unreachable("Unhandled argument type in LowerVAARG");
9655 // Sanity Check: Make sure using fp_offset makes sense.
9656 assert(!getTargetMachine().Options.UseSoftFloat &&
9657 !(DAG.getMachineFunction()
9658 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9659 Subtarget->hasSSE1());
9662 // Insert VAARG_64 node into the DAG
9663 // VAARG_64 returns two values: Variable Argument Address, Chain
9664 SmallVector<SDValue, 11> InstOps;
9665 InstOps.push_back(Chain);
9666 InstOps.push_back(SrcPtr);
9667 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9668 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9669 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9670 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9671 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9672 VTs, &InstOps[0], InstOps.size(),
9674 MachinePointerInfo(SV),
9679 Chain = VAARG.getValue(1);
9681 // Load the next argument and return it
9682 return DAG.getLoad(ArgVT, dl,
9685 MachinePointerInfo(),
9686 false, false, false, 0);
9689 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9690 SelectionDAG &DAG) {
9691 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9692 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9693 SDValue Chain = Op.getOperand(0);
9694 SDValue DstPtr = Op.getOperand(1);
9695 SDValue SrcPtr = Op.getOperand(2);
9696 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9697 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9698 DebugLoc DL = Op.getDebugLoc();
9700 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9701 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9703 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9706 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9707 // may or may not be a constant. Takes immediate version of shift as input.
9708 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9709 SDValue SrcOp, SDValue ShAmt,
9710 SelectionDAG &DAG) {
9711 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9713 if (isa<ConstantSDNode>(ShAmt)) {
9714 // Constant may be a TargetConstant. Use a regular constant.
9715 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9717 default: llvm_unreachable("Unknown target vector shift node");
9721 return DAG.getNode(Opc, dl, VT, SrcOp,
9722 DAG.getConstant(ShiftAmt, MVT::i32));
9726 // Change opcode to non-immediate version
9728 default: llvm_unreachable("Unknown target vector shift node");
9729 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9730 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9731 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9734 // Need to build a vector containing shift amount
9735 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9738 ShOps[1] = DAG.getConstant(0, MVT::i32);
9739 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9740 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9742 // The return type has to be a 128-bit type with the same element
9743 // type as the input type.
9744 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9745 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9747 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9748 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9751 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9752 DebugLoc dl = Op.getDebugLoc();
9753 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9755 default: return SDValue(); // Don't custom lower most intrinsics.
9756 // Comparison intrinsics.
9757 case Intrinsic::x86_sse_comieq_ss:
9758 case Intrinsic::x86_sse_comilt_ss:
9759 case Intrinsic::x86_sse_comile_ss:
9760 case Intrinsic::x86_sse_comigt_ss:
9761 case Intrinsic::x86_sse_comige_ss:
9762 case Intrinsic::x86_sse_comineq_ss:
9763 case Intrinsic::x86_sse_ucomieq_ss:
9764 case Intrinsic::x86_sse_ucomilt_ss:
9765 case Intrinsic::x86_sse_ucomile_ss:
9766 case Intrinsic::x86_sse_ucomigt_ss:
9767 case Intrinsic::x86_sse_ucomige_ss:
9768 case Intrinsic::x86_sse_ucomineq_ss:
9769 case Intrinsic::x86_sse2_comieq_sd:
9770 case Intrinsic::x86_sse2_comilt_sd:
9771 case Intrinsic::x86_sse2_comile_sd:
9772 case Intrinsic::x86_sse2_comigt_sd:
9773 case Intrinsic::x86_sse2_comige_sd:
9774 case Intrinsic::x86_sse2_comineq_sd:
9775 case Intrinsic::x86_sse2_ucomieq_sd:
9776 case Intrinsic::x86_sse2_ucomilt_sd:
9777 case Intrinsic::x86_sse2_ucomile_sd:
9778 case Intrinsic::x86_sse2_ucomigt_sd:
9779 case Intrinsic::x86_sse2_ucomige_sd:
9780 case Intrinsic::x86_sse2_ucomineq_sd: {
9784 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9785 case Intrinsic::x86_sse_comieq_ss:
9786 case Intrinsic::x86_sse2_comieq_sd:
9790 case Intrinsic::x86_sse_comilt_ss:
9791 case Intrinsic::x86_sse2_comilt_sd:
9795 case Intrinsic::x86_sse_comile_ss:
9796 case Intrinsic::x86_sse2_comile_sd:
9800 case Intrinsic::x86_sse_comigt_ss:
9801 case Intrinsic::x86_sse2_comigt_sd:
9805 case Intrinsic::x86_sse_comige_ss:
9806 case Intrinsic::x86_sse2_comige_sd:
9810 case Intrinsic::x86_sse_comineq_ss:
9811 case Intrinsic::x86_sse2_comineq_sd:
9815 case Intrinsic::x86_sse_ucomieq_ss:
9816 case Intrinsic::x86_sse2_ucomieq_sd:
9817 Opc = X86ISD::UCOMI;
9820 case Intrinsic::x86_sse_ucomilt_ss:
9821 case Intrinsic::x86_sse2_ucomilt_sd:
9822 Opc = X86ISD::UCOMI;
9825 case Intrinsic::x86_sse_ucomile_ss:
9826 case Intrinsic::x86_sse2_ucomile_sd:
9827 Opc = X86ISD::UCOMI;
9830 case Intrinsic::x86_sse_ucomigt_ss:
9831 case Intrinsic::x86_sse2_ucomigt_sd:
9832 Opc = X86ISD::UCOMI;
9835 case Intrinsic::x86_sse_ucomige_ss:
9836 case Intrinsic::x86_sse2_ucomige_sd:
9837 Opc = X86ISD::UCOMI;
9840 case Intrinsic::x86_sse_ucomineq_ss:
9841 case Intrinsic::x86_sse2_ucomineq_sd:
9842 Opc = X86ISD::UCOMI;
9847 SDValue LHS = Op.getOperand(1);
9848 SDValue RHS = Op.getOperand(2);
9849 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9850 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9851 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9852 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9853 DAG.getConstant(X86CC, MVT::i8), Cond);
9854 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9857 // Arithmetic intrinsics.
9858 case Intrinsic::x86_sse2_pmulu_dq:
9859 case Intrinsic::x86_avx2_pmulu_dq:
9860 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9861 Op.getOperand(1), Op.getOperand(2));
9863 // SSE3/AVX horizontal add/sub intrinsics
9864 case Intrinsic::x86_sse3_hadd_ps:
9865 case Intrinsic::x86_sse3_hadd_pd:
9866 case Intrinsic::x86_avx_hadd_ps_256:
9867 case Intrinsic::x86_avx_hadd_pd_256:
9868 case Intrinsic::x86_sse3_hsub_ps:
9869 case Intrinsic::x86_sse3_hsub_pd:
9870 case Intrinsic::x86_avx_hsub_ps_256:
9871 case Intrinsic::x86_avx_hsub_pd_256:
9872 case Intrinsic::x86_ssse3_phadd_w_128:
9873 case Intrinsic::x86_ssse3_phadd_d_128:
9874 case Intrinsic::x86_avx2_phadd_w:
9875 case Intrinsic::x86_avx2_phadd_d:
9876 case Intrinsic::x86_ssse3_phsub_w_128:
9877 case Intrinsic::x86_ssse3_phsub_d_128:
9878 case Intrinsic::x86_avx2_phsub_w:
9879 case Intrinsic::x86_avx2_phsub_d: {
9882 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9883 case Intrinsic::x86_sse3_hadd_ps:
9884 case Intrinsic::x86_sse3_hadd_pd:
9885 case Intrinsic::x86_avx_hadd_ps_256:
9886 case Intrinsic::x86_avx_hadd_pd_256:
9887 Opcode = X86ISD::FHADD;
9889 case Intrinsic::x86_sse3_hsub_ps:
9890 case Intrinsic::x86_sse3_hsub_pd:
9891 case Intrinsic::x86_avx_hsub_ps_256:
9892 case Intrinsic::x86_avx_hsub_pd_256:
9893 Opcode = X86ISD::FHSUB;
9895 case Intrinsic::x86_ssse3_phadd_w_128:
9896 case Intrinsic::x86_ssse3_phadd_d_128:
9897 case Intrinsic::x86_avx2_phadd_w:
9898 case Intrinsic::x86_avx2_phadd_d:
9899 Opcode = X86ISD::HADD;
9901 case Intrinsic::x86_ssse3_phsub_w_128:
9902 case Intrinsic::x86_ssse3_phsub_d_128:
9903 case Intrinsic::x86_avx2_phsub_w:
9904 case Intrinsic::x86_avx2_phsub_d:
9905 Opcode = X86ISD::HSUB;
9908 return DAG.getNode(Opcode, dl, Op.getValueType(),
9909 Op.getOperand(1), Op.getOperand(2));
9912 // AVX2 variable shift intrinsics
9913 case Intrinsic::x86_avx2_psllv_d:
9914 case Intrinsic::x86_avx2_psllv_q:
9915 case Intrinsic::x86_avx2_psllv_d_256:
9916 case Intrinsic::x86_avx2_psllv_q_256:
9917 case Intrinsic::x86_avx2_psrlv_d:
9918 case Intrinsic::x86_avx2_psrlv_q:
9919 case Intrinsic::x86_avx2_psrlv_d_256:
9920 case Intrinsic::x86_avx2_psrlv_q_256:
9921 case Intrinsic::x86_avx2_psrav_d:
9922 case Intrinsic::x86_avx2_psrav_d_256: {
9925 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9926 case Intrinsic::x86_avx2_psllv_d:
9927 case Intrinsic::x86_avx2_psllv_q:
9928 case Intrinsic::x86_avx2_psllv_d_256:
9929 case Intrinsic::x86_avx2_psllv_q_256:
9932 case Intrinsic::x86_avx2_psrlv_d:
9933 case Intrinsic::x86_avx2_psrlv_q:
9934 case Intrinsic::x86_avx2_psrlv_d_256:
9935 case Intrinsic::x86_avx2_psrlv_q_256:
9938 case Intrinsic::x86_avx2_psrav_d:
9939 case Intrinsic::x86_avx2_psrav_d_256:
9943 return DAG.getNode(Opcode, dl, Op.getValueType(),
9944 Op.getOperand(1), Op.getOperand(2));
9947 case Intrinsic::x86_ssse3_pshuf_b_128:
9948 case Intrinsic::x86_avx2_pshuf_b:
9949 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9950 Op.getOperand(1), Op.getOperand(2));
9952 case Intrinsic::x86_ssse3_psign_b_128:
9953 case Intrinsic::x86_ssse3_psign_w_128:
9954 case Intrinsic::x86_ssse3_psign_d_128:
9955 case Intrinsic::x86_avx2_psign_b:
9956 case Intrinsic::x86_avx2_psign_w:
9957 case Intrinsic::x86_avx2_psign_d:
9958 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9959 Op.getOperand(1), Op.getOperand(2));
9961 case Intrinsic::x86_sse41_insertps:
9962 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9963 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9965 case Intrinsic::x86_avx_vperm2f128_ps_256:
9966 case Intrinsic::x86_avx_vperm2f128_pd_256:
9967 case Intrinsic::x86_avx_vperm2f128_si_256:
9968 case Intrinsic::x86_avx2_vperm2i128:
9969 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9970 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9972 case Intrinsic::x86_avx2_permd:
9973 case Intrinsic::x86_avx2_permps:
9974 // Operands intentionally swapped. Mask is last operand to intrinsic,
9975 // but second operand for node/intruction.
9976 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9977 Op.getOperand(2), Op.getOperand(1));
9979 // ptest and testp intrinsics. The intrinsic these come from are designed to
9980 // return an integer value, not just an instruction so lower it to the ptest
9981 // or testp pattern and a setcc for the result.
9982 case Intrinsic::x86_sse41_ptestz:
9983 case Intrinsic::x86_sse41_ptestc:
9984 case Intrinsic::x86_sse41_ptestnzc:
9985 case Intrinsic::x86_avx_ptestz_256:
9986 case Intrinsic::x86_avx_ptestc_256:
9987 case Intrinsic::x86_avx_ptestnzc_256:
9988 case Intrinsic::x86_avx_vtestz_ps:
9989 case Intrinsic::x86_avx_vtestc_ps:
9990 case Intrinsic::x86_avx_vtestnzc_ps:
9991 case Intrinsic::x86_avx_vtestz_pd:
9992 case Intrinsic::x86_avx_vtestc_pd:
9993 case Intrinsic::x86_avx_vtestnzc_pd:
9994 case Intrinsic::x86_avx_vtestz_ps_256:
9995 case Intrinsic::x86_avx_vtestc_ps_256:
9996 case Intrinsic::x86_avx_vtestnzc_ps_256:
9997 case Intrinsic::x86_avx_vtestz_pd_256:
9998 case Intrinsic::x86_avx_vtestc_pd_256:
9999 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10000 bool IsTestPacked = false;
10003 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10004 case Intrinsic::x86_avx_vtestz_ps:
10005 case Intrinsic::x86_avx_vtestz_pd:
10006 case Intrinsic::x86_avx_vtestz_ps_256:
10007 case Intrinsic::x86_avx_vtestz_pd_256:
10008 IsTestPacked = true; // Fallthrough
10009 case Intrinsic::x86_sse41_ptestz:
10010 case Intrinsic::x86_avx_ptestz_256:
10012 X86CC = X86::COND_E;
10014 case Intrinsic::x86_avx_vtestc_ps:
10015 case Intrinsic::x86_avx_vtestc_pd:
10016 case Intrinsic::x86_avx_vtestc_ps_256:
10017 case Intrinsic::x86_avx_vtestc_pd_256:
10018 IsTestPacked = true; // Fallthrough
10019 case Intrinsic::x86_sse41_ptestc:
10020 case Intrinsic::x86_avx_ptestc_256:
10022 X86CC = X86::COND_B;
10024 case Intrinsic::x86_avx_vtestnzc_ps:
10025 case Intrinsic::x86_avx_vtestnzc_pd:
10026 case Intrinsic::x86_avx_vtestnzc_ps_256:
10027 case Intrinsic::x86_avx_vtestnzc_pd_256:
10028 IsTestPacked = true; // Fallthrough
10029 case Intrinsic::x86_sse41_ptestnzc:
10030 case Intrinsic::x86_avx_ptestnzc_256:
10032 X86CC = X86::COND_A;
10036 SDValue LHS = Op.getOperand(1);
10037 SDValue RHS = Op.getOperand(2);
10038 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10039 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10040 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10041 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10042 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10045 // SSE/AVX shift intrinsics
10046 case Intrinsic::x86_sse2_psll_w:
10047 case Intrinsic::x86_sse2_psll_d:
10048 case Intrinsic::x86_sse2_psll_q:
10049 case Intrinsic::x86_avx2_psll_w:
10050 case Intrinsic::x86_avx2_psll_d:
10051 case Intrinsic::x86_avx2_psll_q:
10052 case Intrinsic::x86_sse2_psrl_w:
10053 case Intrinsic::x86_sse2_psrl_d:
10054 case Intrinsic::x86_sse2_psrl_q:
10055 case Intrinsic::x86_avx2_psrl_w:
10056 case Intrinsic::x86_avx2_psrl_d:
10057 case Intrinsic::x86_avx2_psrl_q:
10058 case Intrinsic::x86_sse2_psra_w:
10059 case Intrinsic::x86_sse2_psra_d:
10060 case Intrinsic::x86_avx2_psra_w:
10061 case Intrinsic::x86_avx2_psra_d: {
10064 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10065 case Intrinsic::x86_sse2_psll_w:
10066 case Intrinsic::x86_sse2_psll_d:
10067 case Intrinsic::x86_sse2_psll_q:
10068 case Intrinsic::x86_avx2_psll_w:
10069 case Intrinsic::x86_avx2_psll_d:
10070 case Intrinsic::x86_avx2_psll_q:
10071 Opcode = X86ISD::VSHL;
10073 case Intrinsic::x86_sse2_psrl_w:
10074 case Intrinsic::x86_sse2_psrl_d:
10075 case Intrinsic::x86_sse2_psrl_q:
10076 case Intrinsic::x86_avx2_psrl_w:
10077 case Intrinsic::x86_avx2_psrl_d:
10078 case Intrinsic::x86_avx2_psrl_q:
10079 Opcode = X86ISD::VSRL;
10081 case Intrinsic::x86_sse2_psra_w:
10082 case Intrinsic::x86_sse2_psra_d:
10083 case Intrinsic::x86_avx2_psra_w:
10084 case Intrinsic::x86_avx2_psra_d:
10085 Opcode = X86ISD::VSRA;
10088 return DAG.getNode(Opcode, dl, Op.getValueType(),
10089 Op.getOperand(1), Op.getOperand(2));
10092 // SSE/AVX immediate shift intrinsics
10093 case Intrinsic::x86_sse2_pslli_w:
10094 case Intrinsic::x86_sse2_pslli_d:
10095 case Intrinsic::x86_sse2_pslli_q:
10096 case Intrinsic::x86_avx2_pslli_w:
10097 case Intrinsic::x86_avx2_pslli_d:
10098 case Intrinsic::x86_avx2_pslli_q:
10099 case Intrinsic::x86_sse2_psrli_w:
10100 case Intrinsic::x86_sse2_psrli_d:
10101 case Intrinsic::x86_sse2_psrli_q:
10102 case Intrinsic::x86_avx2_psrli_w:
10103 case Intrinsic::x86_avx2_psrli_d:
10104 case Intrinsic::x86_avx2_psrli_q:
10105 case Intrinsic::x86_sse2_psrai_w:
10106 case Intrinsic::x86_sse2_psrai_d:
10107 case Intrinsic::x86_avx2_psrai_w:
10108 case Intrinsic::x86_avx2_psrai_d: {
10111 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10112 case Intrinsic::x86_sse2_pslli_w:
10113 case Intrinsic::x86_sse2_pslli_d:
10114 case Intrinsic::x86_sse2_pslli_q:
10115 case Intrinsic::x86_avx2_pslli_w:
10116 case Intrinsic::x86_avx2_pslli_d:
10117 case Intrinsic::x86_avx2_pslli_q:
10118 Opcode = X86ISD::VSHLI;
10120 case Intrinsic::x86_sse2_psrli_w:
10121 case Intrinsic::x86_sse2_psrli_d:
10122 case Intrinsic::x86_sse2_psrli_q:
10123 case Intrinsic::x86_avx2_psrli_w:
10124 case Intrinsic::x86_avx2_psrli_d:
10125 case Intrinsic::x86_avx2_psrli_q:
10126 Opcode = X86ISD::VSRLI;
10128 case Intrinsic::x86_sse2_psrai_w:
10129 case Intrinsic::x86_sse2_psrai_d:
10130 case Intrinsic::x86_avx2_psrai_w:
10131 case Intrinsic::x86_avx2_psrai_d:
10132 Opcode = X86ISD::VSRAI;
10135 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10136 Op.getOperand(1), Op.getOperand(2), DAG);
10139 case Intrinsic::x86_sse42_pcmpistria128:
10140 case Intrinsic::x86_sse42_pcmpestria128:
10141 case Intrinsic::x86_sse42_pcmpistric128:
10142 case Intrinsic::x86_sse42_pcmpestric128:
10143 case Intrinsic::x86_sse42_pcmpistrio128:
10144 case Intrinsic::x86_sse42_pcmpestrio128:
10145 case Intrinsic::x86_sse42_pcmpistris128:
10146 case Intrinsic::x86_sse42_pcmpestris128:
10147 case Intrinsic::x86_sse42_pcmpistriz128:
10148 case Intrinsic::x86_sse42_pcmpestriz128: {
10152 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10153 case Intrinsic::x86_sse42_pcmpistria128:
10154 Opcode = X86ISD::PCMPISTRI;
10155 X86CC = X86::COND_A;
10157 case Intrinsic::x86_sse42_pcmpestria128:
10158 Opcode = X86ISD::PCMPESTRI;
10159 X86CC = X86::COND_A;
10161 case Intrinsic::x86_sse42_pcmpistric128:
10162 Opcode = X86ISD::PCMPISTRI;
10163 X86CC = X86::COND_B;
10165 case Intrinsic::x86_sse42_pcmpestric128:
10166 Opcode = X86ISD::PCMPESTRI;
10167 X86CC = X86::COND_B;
10169 case Intrinsic::x86_sse42_pcmpistrio128:
10170 Opcode = X86ISD::PCMPISTRI;
10171 X86CC = X86::COND_O;
10173 case Intrinsic::x86_sse42_pcmpestrio128:
10174 Opcode = X86ISD::PCMPESTRI;
10175 X86CC = X86::COND_O;
10177 case Intrinsic::x86_sse42_pcmpistris128:
10178 Opcode = X86ISD::PCMPISTRI;
10179 X86CC = X86::COND_S;
10181 case Intrinsic::x86_sse42_pcmpestris128:
10182 Opcode = X86ISD::PCMPESTRI;
10183 X86CC = X86::COND_S;
10185 case Intrinsic::x86_sse42_pcmpistriz128:
10186 Opcode = X86ISD::PCMPISTRI;
10187 X86CC = X86::COND_E;
10189 case Intrinsic::x86_sse42_pcmpestriz128:
10190 Opcode = X86ISD::PCMPESTRI;
10191 X86CC = X86::COND_E;
10194 SmallVector<SDValue, 5> NewOps;
10195 NewOps.append(Op->op_begin()+1, Op->op_end());
10196 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10197 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10198 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10199 DAG.getConstant(X86CC, MVT::i8),
10200 SDValue(PCMP.getNode(), 1));
10201 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10204 case Intrinsic::x86_sse42_pcmpistri128:
10205 case Intrinsic::x86_sse42_pcmpestri128: {
10207 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10208 Opcode = X86ISD::PCMPISTRI;
10210 Opcode = X86ISD::PCMPESTRI;
10212 SmallVector<SDValue, 5> NewOps;
10213 NewOps.append(Op->op_begin()+1, Op->op_end());
10214 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10215 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10217 case Intrinsic::x86_fma_vfmadd_ps:
10218 case Intrinsic::x86_fma_vfmadd_pd:
10219 case Intrinsic::x86_fma_vfmsub_ps:
10220 case Intrinsic::x86_fma_vfmsub_pd:
10221 case Intrinsic::x86_fma_vfnmadd_ps:
10222 case Intrinsic::x86_fma_vfnmadd_pd:
10223 case Intrinsic::x86_fma_vfnmsub_ps:
10224 case Intrinsic::x86_fma_vfnmsub_pd:
10225 case Intrinsic::x86_fma_vfmaddsub_ps:
10226 case Intrinsic::x86_fma_vfmaddsub_pd:
10227 case Intrinsic::x86_fma_vfmsubadd_ps:
10228 case Intrinsic::x86_fma_vfmsubadd_pd:
10229 case Intrinsic::x86_fma_vfmadd_ps_256:
10230 case Intrinsic::x86_fma_vfmadd_pd_256:
10231 case Intrinsic::x86_fma_vfmsub_ps_256:
10232 case Intrinsic::x86_fma_vfmsub_pd_256:
10233 case Intrinsic::x86_fma_vfnmadd_ps_256:
10234 case Intrinsic::x86_fma_vfnmadd_pd_256:
10235 case Intrinsic::x86_fma_vfnmsub_ps_256:
10236 case Intrinsic::x86_fma_vfnmsub_pd_256:
10237 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10238 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10239 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10240 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10243 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10244 case Intrinsic::x86_fma_vfmadd_ps:
10245 case Intrinsic::x86_fma_vfmadd_pd:
10246 case Intrinsic::x86_fma_vfmadd_ps_256:
10247 case Intrinsic::x86_fma_vfmadd_pd_256:
10248 Opc = X86ISD::FMADD;
10250 case Intrinsic::x86_fma_vfmsub_ps:
10251 case Intrinsic::x86_fma_vfmsub_pd:
10252 case Intrinsic::x86_fma_vfmsub_ps_256:
10253 case Intrinsic::x86_fma_vfmsub_pd_256:
10254 Opc = X86ISD::FMSUB;
10256 case Intrinsic::x86_fma_vfnmadd_ps:
10257 case Intrinsic::x86_fma_vfnmadd_pd:
10258 case Intrinsic::x86_fma_vfnmadd_ps_256:
10259 case Intrinsic::x86_fma_vfnmadd_pd_256:
10260 Opc = X86ISD::FNMADD;
10262 case Intrinsic::x86_fma_vfnmsub_ps:
10263 case Intrinsic::x86_fma_vfnmsub_pd:
10264 case Intrinsic::x86_fma_vfnmsub_ps_256:
10265 case Intrinsic::x86_fma_vfnmsub_pd_256:
10266 Opc = X86ISD::FNMSUB;
10268 case Intrinsic::x86_fma_vfmaddsub_ps:
10269 case Intrinsic::x86_fma_vfmaddsub_pd:
10270 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10271 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10272 Opc = X86ISD::FMADDSUB;
10274 case Intrinsic::x86_fma_vfmsubadd_ps:
10275 case Intrinsic::x86_fma_vfmsubadd_pd:
10276 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10277 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10278 Opc = X86ISD::FMSUBADD;
10282 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10283 Op.getOperand(2), Op.getOperand(3));
10288 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10289 DebugLoc dl = Op.getDebugLoc();
10290 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10292 default: return SDValue(); // Don't custom lower most intrinsics.
10294 // RDRAND intrinsics.
10295 case Intrinsic::x86_rdrand_16:
10296 case Intrinsic::x86_rdrand_32:
10297 case Intrinsic::x86_rdrand_64: {
10298 // Emit the node with the right value type.
10299 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10300 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10302 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10303 // return the value from Rand, which is always 0, casted to i32.
10304 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10305 DAG.getConstant(1, Op->getValueType(1)),
10306 DAG.getConstant(X86::COND_B, MVT::i32),
10307 SDValue(Result.getNode(), 1) };
10308 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10309 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10312 // Return { result, isValid, chain }.
10313 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10314 SDValue(Result.getNode(), 2));
10319 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10320 SelectionDAG &DAG) const {
10321 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10322 MFI->setReturnAddressIsTaken(true);
10324 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10325 DebugLoc dl = Op.getDebugLoc();
10328 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10330 DAG.getConstant(TD->getPointerSize(),
10331 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10332 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10333 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10334 FrameAddr, Offset),
10335 MachinePointerInfo(), false, false, false, 0);
10338 // Just load the return address.
10339 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10340 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10341 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10344 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10345 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10346 MFI->setFrameAddressIsTaken(true);
10348 EVT VT = Op.getValueType();
10349 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10350 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10351 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10352 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10354 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10355 MachinePointerInfo(),
10356 false, false, false, 0);
10360 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10361 SelectionDAG &DAG) const {
10362 return DAG.getIntPtrConstant(2*TD->getPointerSize());
10365 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10366 SDValue Chain = Op.getOperand(0);
10367 SDValue Offset = Op.getOperand(1);
10368 SDValue Handler = Op.getOperand(2);
10369 DebugLoc dl = Op.getDebugLoc();
10371 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10372 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10374 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10376 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10377 DAG.getIntPtrConstant(TD->getPointerSize()));
10378 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10379 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10381 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10383 return DAG.getNode(X86ISD::EH_RETURN, dl,
10385 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10388 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10389 return Op.getOperand(0);
10392 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10393 SelectionDAG &DAG) const {
10394 SDValue Root = Op.getOperand(0);
10395 SDValue Trmp = Op.getOperand(1); // trampoline
10396 SDValue FPtr = Op.getOperand(2); // nested function
10397 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10398 DebugLoc dl = Op.getDebugLoc();
10400 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10402 if (Subtarget->is64Bit()) {
10403 SDValue OutChains[6];
10405 // Large code-model.
10406 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10407 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10409 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10410 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10412 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10414 // Load the pointer to the nested function into R11.
10415 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10416 SDValue Addr = Trmp;
10417 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10418 Addr, MachinePointerInfo(TrmpAddr),
10421 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10422 DAG.getConstant(2, MVT::i64));
10423 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10424 MachinePointerInfo(TrmpAddr, 2),
10427 // Load the 'nest' parameter value into R10.
10428 // R10 is specified in X86CallingConv.td
10429 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10430 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10431 DAG.getConstant(10, MVT::i64));
10432 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10433 Addr, MachinePointerInfo(TrmpAddr, 10),
10436 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10437 DAG.getConstant(12, MVT::i64));
10438 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10439 MachinePointerInfo(TrmpAddr, 12),
10442 // Jump to the nested function.
10443 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10444 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10445 DAG.getConstant(20, MVT::i64));
10446 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10447 Addr, MachinePointerInfo(TrmpAddr, 20),
10450 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10451 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10452 DAG.getConstant(22, MVT::i64));
10453 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10454 MachinePointerInfo(TrmpAddr, 22),
10457 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10459 const Function *Func =
10460 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10461 CallingConv::ID CC = Func->getCallingConv();
10466 llvm_unreachable("Unsupported calling convention");
10467 case CallingConv::C:
10468 case CallingConv::X86_StdCall: {
10469 // Pass 'nest' parameter in ECX.
10470 // Must be kept in sync with X86CallingConv.td
10471 NestReg = X86::ECX;
10473 // Check that ECX wasn't needed by an 'inreg' parameter.
10474 FunctionType *FTy = Func->getFunctionType();
10475 const AttrListPtr &Attrs = Func->getAttributes();
10477 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10478 unsigned InRegCount = 0;
10481 for (FunctionType::param_iterator I = FTy->param_begin(),
10482 E = FTy->param_end(); I != E; ++I, ++Idx)
10483 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10484 // FIXME: should only count parameters that are lowered to integers.
10485 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10487 if (InRegCount > 2) {
10488 report_fatal_error("Nest register in use - reduce number of inreg"
10494 case CallingConv::X86_FastCall:
10495 case CallingConv::X86_ThisCall:
10496 case CallingConv::Fast:
10497 // Pass 'nest' parameter in EAX.
10498 // Must be kept in sync with X86CallingConv.td
10499 NestReg = X86::EAX;
10503 SDValue OutChains[4];
10504 SDValue Addr, Disp;
10506 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10507 DAG.getConstant(10, MVT::i32));
10508 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10510 // This is storing the opcode for MOV32ri.
10511 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10512 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10513 OutChains[0] = DAG.getStore(Root, dl,
10514 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10515 Trmp, MachinePointerInfo(TrmpAddr),
10518 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10519 DAG.getConstant(1, MVT::i32));
10520 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10521 MachinePointerInfo(TrmpAddr, 1),
10524 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10525 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10526 DAG.getConstant(5, MVT::i32));
10527 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10528 MachinePointerInfo(TrmpAddr, 5),
10531 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10532 DAG.getConstant(6, MVT::i32));
10533 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10534 MachinePointerInfo(TrmpAddr, 6),
10537 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10541 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10542 SelectionDAG &DAG) const {
10544 The rounding mode is in bits 11:10 of FPSR, and has the following
10546 00 Round to nearest
10551 FLT_ROUNDS, on the other hand, expects the following:
10558 To perform the conversion, we do:
10559 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10562 MachineFunction &MF = DAG.getMachineFunction();
10563 const TargetMachine &TM = MF.getTarget();
10564 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10565 unsigned StackAlignment = TFI.getStackAlignment();
10566 EVT VT = Op.getValueType();
10567 DebugLoc DL = Op.getDebugLoc();
10569 // Save FP Control Word to stack slot
10570 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10571 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10574 MachineMemOperand *MMO =
10575 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10576 MachineMemOperand::MOStore, 2, 2);
10578 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10579 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10580 DAG.getVTList(MVT::Other),
10581 Ops, 2, MVT::i16, MMO);
10583 // Load FP Control Word from stack slot
10584 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10585 MachinePointerInfo(), false, false, false, 0);
10587 // Transform as necessary
10589 DAG.getNode(ISD::SRL, DL, MVT::i16,
10590 DAG.getNode(ISD::AND, DL, MVT::i16,
10591 CWD, DAG.getConstant(0x800, MVT::i16)),
10592 DAG.getConstant(11, MVT::i8));
10594 DAG.getNode(ISD::SRL, DL, MVT::i16,
10595 DAG.getNode(ISD::AND, DL, MVT::i16,
10596 CWD, DAG.getConstant(0x400, MVT::i16)),
10597 DAG.getConstant(9, MVT::i8));
10600 DAG.getNode(ISD::AND, DL, MVT::i16,
10601 DAG.getNode(ISD::ADD, DL, MVT::i16,
10602 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10603 DAG.getConstant(1, MVT::i16)),
10604 DAG.getConstant(3, MVT::i16));
10607 return DAG.getNode((VT.getSizeInBits() < 16 ?
10608 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10611 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10612 EVT VT = Op.getValueType();
10614 unsigned NumBits = VT.getSizeInBits();
10615 DebugLoc dl = Op.getDebugLoc();
10617 Op = Op.getOperand(0);
10618 if (VT == MVT::i8) {
10619 // Zero extend to i32 since there is not an i8 bsr.
10621 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10624 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10625 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10626 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10628 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10631 DAG.getConstant(NumBits+NumBits-1, OpVT),
10632 DAG.getConstant(X86::COND_E, MVT::i8),
10635 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10637 // Finally xor with NumBits-1.
10638 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10641 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10645 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10646 EVT VT = Op.getValueType();
10648 unsigned NumBits = VT.getSizeInBits();
10649 DebugLoc dl = Op.getDebugLoc();
10651 Op = Op.getOperand(0);
10652 if (VT == MVT::i8) {
10653 // Zero extend to i32 since there is not an i8 bsr.
10655 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10658 // Issue a bsr (scan bits in reverse).
10659 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10660 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10662 // And xor with NumBits-1.
10663 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10666 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10670 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10671 EVT VT = Op.getValueType();
10672 unsigned NumBits = VT.getSizeInBits();
10673 DebugLoc dl = Op.getDebugLoc();
10674 Op = Op.getOperand(0);
10676 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10677 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10678 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10680 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10683 DAG.getConstant(NumBits, VT),
10684 DAG.getConstant(X86::COND_E, MVT::i8),
10687 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10690 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10691 // ones, and then concatenate the result back.
10692 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10693 EVT VT = Op.getValueType();
10695 assert(VT.is256BitVector() && VT.isInteger() &&
10696 "Unsupported value type for operation");
10698 unsigned NumElems = VT.getVectorNumElements();
10699 DebugLoc dl = Op.getDebugLoc();
10701 // Extract the LHS vectors
10702 SDValue LHS = Op.getOperand(0);
10703 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10704 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10706 // Extract the RHS vectors
10707 SDValue RHS = Op.getOperand(1);
10708 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10709 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10711 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10712 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10714 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10715 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10716 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10719 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10720 assert(Op.getValueType().is256BitVector() &&
10721 Op.getValueType().isInteger() &&
10722 "Only handle AVX 256-bit vector integer operation");
10723 return Lower256IntArith(Op, DAG);
10726 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10727 assert(Op.getValueType().is256BitVector() &&
10728 Op.getValueType().isInteger() &&
10729 "Only handle AVX 256-bit vector integer operation");
10730 return Lower256IntArith(Op, DAG);
10733 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10734 SelectionDAG &DAG) {
10735 EVT VT = Op.getValueType();
10737 // Decompose 256-bit ops into smaller 128-bit ops.
10738 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10739 return Lower256IntArith(Op, DAG);
10741 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10742 "Only know how to lower V2I64/V4I64 multiply");
10744 DebugLoc dl = Op.getDebugLoc();
10746 // Ahi = psrlqi(a, 32);
10747 // Bhi = psrlqi(b, 32);
10749 // AloBlo = pmuludq(a, b);
10750 // AloBhi = pmuludq(a, Bhi);
10751 // AhiBlo = pmuludq(Ahi, b);
10753 // AloBhi = psllqi(AloBhi, 32);
10754 // AhiBlo = psllqi(AhiBlo, 32);
10755 // return AloBlo + AloBhi + AhiBlo;
10757 SDValue A = Op.getOperand(0);
10758 SDValue B = Op.getOperand(1);
10760 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10762 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10763 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10765 // Bit cast to 32-bit vectors for MULUDQ
10766 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10767 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10768 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10769 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10770 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10772 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10773 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10774 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10776 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10777 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10779 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10780 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10783 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10785 EVT VT = Op.getValueType();
10786 DebugLoc dl = Op.getDebugLoc();
10787 SDValue R = Op.getOperand(0);
10788 SDValue Amt = Op.getOperand(1);
10789 LLVMContext *Context = DAG.getContext();
10791 if (!Subtarget->hasSSE2())
10794 // Optimize shl/srl/sra with constant shift amount.
10795 if (isSplatVector(Amt.getNode())) {
10796 SDValue SclrAmt = Amt->getOperand(0);
10797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10798 uint64_t ShiftAmt = C->getZExtValue();
10800 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10801 (Subtarget->hasAVX2() &&
10802 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10803 if (Op.getOpcode() == ISD::SHL)
10804 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10805 DAG.getConstant(ShiftAmt, MVT::i32));
10806 if (Op.getOpcode() == ISD::SRL)
10807 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10808 DAG.getConstant(ShiftAmt, MVT::i32));
10809 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10810 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10811 DAG.getConstant(ShiftAmt, MVT::i32));
10814 if (VT == MVT::v16i8) {
10815 if (Op.getOpcode() == ISD::SHL) {
10816 // Make a large shift.
10817 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10818 DAG.getConstant(ShiftAmt, MVT::i32));
10819 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10820 // Zero out the rightmost bits.
10821 SmallVector<SDValue, 16> V(16,
10822 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10824 return DAG.getNode(ISD::AND, dl, VT, SHL,
10825 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10827 if (Op.getOpcode() == ISD::SRL) {
10828 // Make a large shift.
10829 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10830 DAG.getConstant(ShiftAmt, MVT::i32));
10831 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10832 // Zero out the leftmost bits.
10833 SmallVector<SDValue, 16> V(16,
10834 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10836 return DAG.getNode(ISD::AND, dl, VT, SRL,
10837 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10839 if (Op.getOpcode() == ISD::SRA) {
10840 if (ShiftAmt == 7) {
10841 // R s>> 7 === R s< 0
10842 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10843 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10846 // R s>> a === ((R u>> a) ^ m) - m
10847 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10848 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10850 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10851 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10852 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10855 llvm_unreachable("Unknown shift opcode.");
10858 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10859 if (Op.getOpcode() == ISD::SHL) {
10860 // Make a large shift.
10861 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10862 DAG.getConstant(ShiftAmt, MVT::i32));
10863 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10864 // Zero out the rightmost bits.
10865 SmallVector<SDValue, 32> V(32,
10866 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10868 return DAG.getNode(ISD::AND, dl, VT, SHL,
10869 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10871 if (Op.getOpcode() == ISD::SRL) {
10872 // Make a large shift.
10873 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10874 DAG.getConstant(ShiftAmt, MVT::i32));
10875 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10876 // Zero out the leftmost bits.
10877 SmallVector<SDValue, 32> V(32,
10878 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10880 return DAG.getNode(ISD::AND, dl, VT, SRL,
10881 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10883 if (Op.getOpcode() == ISD::SRA) {
10884 if (ShiftAmt == 7) {
10885 // R s>> 7 === R s< 0
10886 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10887 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10890 // R s>> a === ((R u>> a) ^ m) - m
10891 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10892 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10894 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10895 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10896 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10899 llvm_unreachable("Unknown shift opcode.");
10904 // Lower SHL with variable shift amount.
10905 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10906 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10907 DAG.getConstant(23, MVT::i32));
10909 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10910 Constant *C = ConstantDataVector::get(*Context, CV);
10911 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10912 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10913 MachinePointerInfo::getConstantPool(),
10914 false, false, false, 16);
10916 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10917 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10918 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10919 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10921 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10922 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10925 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10926 DAG.getConstant(5, MVT::i32));
10927 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10929 // Turn 'a' into a mask suitable for VSELECT
10930 SDValue VSelM = DAG.getConstant(0x80, VT);
10931 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10932 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10934 SDValue CM1 = DAG.getConstant(0x0f, VT);
10935 SDValue CM2 = DAG.getConstant(0x3f, VT);
10937 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10938 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10939 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10940 DAG.getConstant(4, MVT::i32), DAG);
10941 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10942 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10945 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10946 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10947 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10949 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10950 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10951 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10952 DAG.getConstant(2, MVT::i32), DAG);
10953 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10954 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10957 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10958 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10959 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10961 // return VSELECT(r, r+r, a);
10962 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10963 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10967 // Decompose 256-bit shifts into smaller 128-bit shifts.
10968 if (VT.is256BitVector()) {
10969 unsigned NumElems = VT.getVectorNumElements();
10970 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10971 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10973 // Extract the two vectors
10974 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10975 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10977 // Recreate the shift amount vectors
10978 SDValue Amt1, Amt2;
10979 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10980 // Constant shift amount
10981 SmallVector<SDValue, 4> Amt1Csts;
10982 SmallVector<SDValue, 4> Amt2Csts;
10983 for (unsigned i = 0; i != NumElems/2; ++i)
10984 Amt1Csts.push_back(Amt->getOperand(i));
10985 for (unsigned i = NumElems/2; i != NumElems; ++i)
10986 Amt2Csts.push_back(Amt->getOperand(i));
10988 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10989 &Amt1Csts[0], NumElems/2);
10990 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10991 &Amt2Csts[0], NumElems/2);
10993 // Variable shift amount
10994 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10995 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10998 // Issue new vector shifts for the smaller types
10999 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11000 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11002 // Concatenate the result back
11003 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11009 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11010 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11011 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11012 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11013 // has only one use.
11014 SDNode *N = Op.getNode();
11015 SDValue LHS = N->getOperand(0);
11016 SDValue RHS = N->getOperand(1);
11017 unsigned BaseOp = 0;
11019 DebugLoc DL = Op.getDebugLoc();
11020 switch (Op.getOpcode()) {
11021 default: llvm_unreachable("Unknown ovf instruction!");
11023 // A subtract of one will be selected as a INC. Note that INC doesn't
11024 // set CF, so we can't do this for UADDO.
11025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11027 BaseOp = X86ISD::INC;
11028 Cond = X86::COND_O;
11031 BaseOp = X86ISD::ADD;
11032 Cond = X86::COND_O;
11035 BaseOp = X86ISD::ADD;
11036 Cond = X86::COND_B;
11039 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11040 // set CF, so we can't do this for USUBO.
11041 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11043 BaseOp = X86ISD::DEC;
11044 Cond = X86::COND_O;
11047 BaseOp = X86ISD::SUB;
11048 Cond = X86::COND_O;
11051 BaseOp = X86ISD::SUB;
11052 Cond = X86::COND_B;
11055 BaseOp = X86ISD::SMUL;
11056 Cond = X86::COND_O;
11058 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11059 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11061 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11064 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11065 DAG.getConstant(X86::COND_O, MVT::i32),
11066 SDValue(Sum.getNode(), 2));
11068 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11072 // Also sets EFLAGS.
11073 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11074 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11077 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11078 DAG.getConstant(Cond, MVT::i32),
11079 SDValue(Sum.getNode(), 1));
11081 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11084 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11085 SelectionDAG &DAG) const {
11086 DebugLoc dl = Op.getDebugLoc();
11087 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11088 EVT VT = Op.getValueType();
11090 if (!Subtarget->hasSSE2() || !VT.isVector())
11093 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11094 ExtraVT.getScalarType().getSizeInBits();
11095 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11097 switch (VT.getSimpleVT().SimpleTy) {
11098 default: return SDValue();
11101 if (!Subtarget->hasAVX())
11103 if (!Subtarget->hasAVX2()) {
11104 // needs to be split
11105 unsigned NumElems = VT.getVectorNumElements();
11107 // Extract the LHS vectors
11108 SDValue LHS = Op.getOperand(0);
11109 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11110 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11112 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11113 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11115 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11116 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11117 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11119 SDValue Extra = DAG.getValueType(ExtraVT);
11121 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11122 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11124 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11129 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11130 Op.getOperand(0), ShAmt, DAG);
11131 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11137 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11138 SelectionDAG &DAG) {
11139 DebugLoc dl = Op.getDebugLoc();
11141 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11142 // There isn't any reason to disable it if the target processor supports it.
11143 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11144 SDValue Chain = Op.getOperand(0);
11145 SDValue Zero = DAG.getConstant(0, MVT::i32);
11147 DAG.getRegister(X86::ESP, MVT::i32), // Base
11148 DAG.getTargetConstant(1, MVT::i8), // Scale
11149 DAG.getRegister(0, MVT::i32), // Index
11150 DAG.getTargetConstant(0, MVT::i32), // Disp
11151 DAG.getRegister(0, MVT::i32), // Segment.
11156 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11157 array_lengthof(Ops));
11158 return SDValue(Res, 0);
11161 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11163 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11165 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11166 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11167 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11168 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11170 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11171 if (!Op1 && !Op2 && !Op3 && Op4)
11172 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11174 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11175 if (Op1 && !Op2 && !Op3 && !Op4)
11176 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11178 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11180 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11183 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11184 SelectionDAG &DAG) {
11185 DebugLoc dl = Op.getDebugLoc();
11186 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11187 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11188 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11189 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11191 // The only fence that needs an instruction is a sequentially-consistent
11192 // cross-thread fence.
11193 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11194 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11195 // no-sse2). There isn't any reason to disable it if the target processor
11197 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11198 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11200 SDValue Chain = Op.getOperand(0);
11201 SDValue Zero = DAG.getConstant(0, MVT::i32);
11203 DAG.getRegister(X86::ESP, MVT::i32), // Base
11204 DAG.getTargetConstant(1, MVT::i8), // Scale
11205 DAG.getRegister(0, MVT::i32), // Index
11206 DAG.getTargetConstant(0, MVT::i32), // Disp
11207 DAG.getRegister(0, MVT::i32), // Segment.
11212 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11213 array_lengthof(Ops));
11214 return SDValue(Res, 0);
11217 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11218 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11222 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11223 SelectionDAG &DAG) {
11224 EVT T = Op.getValueType();
11225 DebugLoc DL = Op.getDebugLoc();
11228 switch(T.getSimpleVT().SimpleTy) {
11229 default: llvm_unreachable("Invalid value type!");
11230 case MVT::i8: Reg = X86::AL; size = 1; break;
11231 case MVT::i16: Reg = X86::AX; size = 2; break;
11232 case MVT::i32: Reg = X86::EAX; size = 4; break;
11234 assert(Subtarget->is64Bit() && "Node not type legal!");
11235 Reg = X86::RAX; size = 8;
11238 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11239 Op.getOperand(2), SDValue());
11240 SDValue Ops[] = { cpIn.getValue(0),
11243 DAG.getTargetConstant(size, MVT::i8),
11244 cpIn.getValue(1) };
11245 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11246 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11247 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11250 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11254 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11255 SelectionDAG &DAG) {
11256 assert(Subtarget->is64Bit() && "Result not type legalized?");
11257 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11258 SDValue TheChain = Op.getOperand(0);
11259 DebugLoc dl = Op.getDebugLoc();
11260 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11261 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11262 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11264 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11265 DAG.getConstant(32, MVT::i8));
11267 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11270 return DAG.getMergeValues(Ops, 2, dl);
11273 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11274 EVT SrcVT = Op.getOperand(0).getValueType();
11275 EVT DstVT = Op.getValueType();
11276 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11277 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11278 assert((DstVT == MVT::i64 ||
11279 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11280 "Unexpected custom BITCAST");
11281 // i64 <=> MMX conversions are Legal.
11282 if (SrcVT==MVT::i64 && DstVT.isVector())
11284 if (DstVT==MVT::i64 && SrcVT.isVector())
11286 // MMX <=> MMX conversions are Legal.
11287 if (SrcVT.isVector() && DstVT.isVector())
11289 // All other conversions need to be expanded.
11293 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11294 SDNode *Node = Op.getNode();
11295 DebugLoc dl = Node->getDebugLoc();
11296 EVT T = Node->getValueType(0);
11297 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11298 DAG.getConstant(0, T), Node->getOperand(2));
11299 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11300 cast<AtomicSDNode>(Node)->getMemoryVT(),
11301 Node->getOperand(0),
11302 Node->getOperand(1), negOp,
11303 cast<AtomicSDNode>(Node)->getSrcValue(),
11304 cast<AtomicSDNode>(Node)->getAlignment(),
11305 cast<AtomicSDNode>(Node)->getOrdering(),
11306 cast<AtomicSDNode>(Node)->getSynchScope());
11309 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11310 SDNode *Node = Op.getNode();
11311 DebugLoc dl = Node->getDebugLoc();
11312 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11314 // Convert seq_cst store -> xchg
11315 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11316 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11317 // (The only way to get a 16-byte store is cmpxchg16b)
11318 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11319 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11320 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11321 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11322 cast<AtomicSDNode>(Node)->getMemoryVT(),
11323 Node->getOperand(0),
11324 Node->getOperand(1), Node->getOperand(2),
11325 cast<AtomicSDNode>(Node)->getMemOperand(),
11326 cast<AtomicSDNode>(Node)->getOrdering(),
11327 cast<AtomicSDNode>(Node)->getSynchScope());
11328 return Swap.getValue(1);
11330 // Other atomic stores have a simple pattern.
11334 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11335 EVT VT = Op.getNode()->getValueType(0);
11337 // Let legalize expand this if it isn't a legal type yet.
11338 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11341 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11344 bool ExtraOp = false;
11345 switch (Op.getOpcode()) {
11346 default: llvm_unreachable("Invalid code");
11347 case ISD::ADDC: Opc = X86ISD::ADD; break;
11348 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11349 case ISD::SUBC: Opc = X86ISD::SUB; break;
11350 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11354 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11356 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11357 Op.getOperand(1), Op.getOperand(2));
11360 /// LowerOperation - Provide custom lowering hooks for some operations.
11362 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11363 switch (Op.getOpcode()) {
11364 default: llvm_unreachable("Should not custom lower this!");
11365 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11366 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11367 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11368 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11369 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11370 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11371 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11372 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11373 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11374 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11375 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11376 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11377 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11378 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11379 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11380 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11381 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11382 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11383 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11384 case ISD::SHL_PARTS:
11385 case ISD::SRA_PARTS:
11386 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11387 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11388 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11389 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11390 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11391 case ISD::FABS: return LowerFABS(Op, DAG);
11392 case ISD::FNEG: return LowerFNEG(Op, DAG);
11393 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11394 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11395 case ISD::SETCC: return LowerSETCC(Op, DAG);
11396 case ISD::SELECT: return LowerSELECT(Op, DAG);
11397 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11398 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11399 case ISD::VASTART: return LowerVASTART(Op, DAG);
11400 case ISD::VAARG: return LowerVAARG(Op, DAG);
11401 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11402 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11403 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11404 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11405 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11406 case ISD::FRAME_TO_ARGS_OFFSET:
11407 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11408 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11409 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11410 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11411 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11412 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11413 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11414 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11415 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11416 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11419 case ISD::SHL: return LowerShift(Op, DAG);
11425 case ISD::UMULO: return LowerXALUO(Op, DAG);
11426 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11427 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11431 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11432 case ISD::ADD: return LowerADD(Op, DAG);
11433 case ISD::SUB: return LowerSUB(Op, DAG);
11437 static void ReplaceATOMIC_LOAD(SDNode *Node,
11438 SmallVectorImpl<SDValue> &Results,
11439 SelectionDAG &DAG) {
11440 DebugLoc dl = Node->getDebugLoc();
11441 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11443 // Convert wide load -> cmpxchg8b/cmpxchg16b
11444 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11445 // (The only way to get a 16-byte load is cmpxchg16b)
11446 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11447 SDValue Zero = DAG.getConstant(0, VT);
11448 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11449 Node->getOperand(0),
11450 Node->getOperand(1), Zero, Zero,
11451 cast<AtomicSDNode>(Node)->getMemOperand(),
11452 cast<AtomicSDNode>(Node)->getOrdering(),
11453 cast<AtomicSDNode>(Node)->getSynchScope());
11454 Results.push_back(Swap.getValue(0));
11455 Results.push_back(Swap.getValue(1));
11459 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11460 SelectionDAG &DAG, unsigned NewOp) {
11461 DebugLoc dl = Node->getDebugLoc();
11462 assert (Node->getValueType(0) == MVT::i64 &&
11463 "Only know how to expand i64 atomics");
11465 SDValue Chain = Node->getOperand(0);
11466 SDValue In1 = Node->getOperand(1);
11467 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11468 Node->getOperand(2), DAG.getIntPtrConstant(0));
11469 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11470 Node->getOperand(2), DAG.getIntPtrConstant(1));
11471 SDValue Ops[] = { Chain, In1, In2L, In2H };
11472 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11474 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11475 cast<MemSDNode>(Node)->getMemOperand());
11476 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11477 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11478 Results.push_back(Result.getValue(2));
11481 /// ReplaceNodeResults - Replace a node with an illegal result type
11482 /// with a new node built out of custom code.
11483 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11484 SmallVectorImpl<SDValue>&Results,
11485 SelectionDAG &DAG) const {
11486 DebugLoc dl = N->getDebugLoc();
11487 switch (N->getOpcode()) {
11489 llvm_unreachable("Do not know how to custom type legalize this operation!");
11490 case ISD::SIGN_EXTEND_INREG:
11495 // We don't want to expand or promote these.
11497 case ISD::FP_TO_SINT:
11498 case ISD::FP_TO_UINT: {
11499 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11501 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11504 std::pair<SDValue,SDValue> Vals =
11505 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11506 SDValue FIST = Vals.first, StackSlot = Vals.second;
11507 if (FIST.getNode() != 0) {
11508 EVT VT = N->getValueType(0);
11509 // Return a load from the stack slot.
11510 if (StackSlot.getNode() != 0)
11511 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11512 MachinePointerInfo(),
11513 false, false, false, 0));
11515 Results.push_back(FIST);
11519 case ISD::READCYCLECOUNTER: {
11520 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11521 SDValue TheChain = N->getOperand(0);
11522 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11523 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11525 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11527 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11528 SDValue Ops[] = { eax, edx };
11529 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11530 Results.push_back(edx.getValue(1));
11533 case ISD::ATOMIC_CMP_SWAP: {
11534 EVT T = N->getValueType(0);
11535 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11536 bool Regs64bit = T == MVT::i128;
11537 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11538 SDValue cpInL, cpInH;
11539 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11540 DAG.getConstant(0, HalfT));
11541 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11542 DAG.getConstant(1, HalfT));
11543 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11544 Regs64bit ? X86::RAX : X86::EAX,
11546 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11547 Regs64bit ? X86::RDX : X86::EDX,
11548 cpInH, cpInL.getValue(1));
11549 SDValue swapInL, swapInH;
11550 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11551 DAG.getConstant(0, HalfT));
11552 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11553 DAG.getConstant(1, HalfT));
11554 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11555 Regs64bit ? X86::RBX : X86::EBX,
11556 swapInL, cpInH.getValue(1));
11557 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11558 Regs64bit ? X86::RCX : X86::ECX,
11559 swapInH, swapInL.getValue(1));
11560 SDValue Ops[] = { swapInH.getValue(0),
11562 swapInH.getValue(1) };
11563 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11564 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11565 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11566 X86ISD::LCMPXCHG8_DAG;
11567 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11569 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11570 Regs64bit ? X86::RAX : X86::EAX,
11571 HalfT, Result.getValue(1));
11572 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11573 Regs64bit ? X86::RDX : X86::EDX,
11574 HalfT, cpOutL.getValue(2));
11575 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11576 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11577 Results.push_back(cpOutH.getValue(1));
11580 case ISD::ATOMIC_LOAD_ADD:
11581 case ISD::ATOMIC_LOAD_AND:
11582 case ISD::ATOMIC_LOAD_NAND:
11583 case ISD::ATOMIC_LOAD_OR:
11584 case ISD::ATOMIC_LOAD_SUB:
11585 case ISD::ATOMIC_LOAD_XOR:
11586 case ISD::ATOMIC_SWAP: {
11588 switch (N->getOpcode()) {
11589 default: llvm_unreachable("Unexpected opcode");
11590 case ISD::ATOMIC_LOAD_ADD:
11591 Opc = X86ISD::ATOMADD64_DAG;
11593 case ISD::ATOMIC_LOAD_AND:
11594 Opc = X86ISD::ATOMAND64_DAG;
11596 case ISD::ATOMIC_LOAD_NAND:
11597 Opc = X86ISD::ATOMNAND64_DAG;
11599 case ISD::ATOMIC_LOAD_OR:
11600 Opc = X86ISD::ATOMOR64_DAG;
11602 case ISD::ATOMIC_LOAD_SUB:
11603 Opc = X86ISD::ATOMSUB64_DAG;
11605 case ISD::ATOMIC_LOAD_XOR:
11606 Opc = X86ISD::ATOMXOR64_DAG;
11608 case ISD::ATOMIC_SWAP:
11609 Opc = X86ISD::ATOMSWAP64_DAG;
11612 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11615 case ISD::ATOMIC_LOAD:
11616 ReplaceATOMIC_LOAD(N, Results, DAG);
11620 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11622 default: return NULL;
11623 case X86ISD::BSF: return "X86ISD::BSF";
11624 case X86ISD::BSR: return "X86ISD::BSR";
11625 case X86ISD::SHLD: return "X86ISD::SHLD";
11626 case X86ISD::SHRD: return "X86ISD::SHRD";
11627 case X86ISD::FAND: return "X86ISD::FAND";
11628 case X86ISD::FOR: return "X86ISD::FOR";
11629 case X86ISD::FXOR: return "X86ISD::FXOR";
11630 case X86ISD::FSRL: return "X86ISD::FSRL";
11631 case X86ISD::FILD: return "X86ISD::FILD";
11632 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11633 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11634 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11635 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11636 case X86ISD::FLD: return "X86ISD::FLD";
11637 case X86ISD::FST: return "X86ISD::FST";
11638 case X86ISD::CALL: return "X86ISD::CALL";
11639 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11640 case X86ISD::BT: return "X86ISD::BT";
11641 case X86ISD::CMP: return "X86ISD::CMP";
11642 case X86ISD::COMI: return "X86ISD::COMI";
11643 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11644 case X86ISD::SETCC: return "X86ISD::SETCC";
11645 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11646 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11647 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11648 case X86ISD::CMOV: return "X86ISD::CMOV";
11649 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11650 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11651 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11652 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11653 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11654 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11655 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11656 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11657 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11658 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11659 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11660 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11661 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11662 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11663 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11664 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11665 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11666 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11667 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11668 case X86ISD::HADD: return "X86ISD::HADD";
11669 case X86ISD::HSUB: return "X86ISD::HSUB";
11670 case X86ISD::FHADD: return "X86ISD::FHADD";
11671 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11672 case X86ISD::FMAX: return "X86ISD::FMAX";
11673 case X86ISD::FMIN: return "X86ISD::FMIN";
11674 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11675 case X86ISD::FMINC: return "X86ISD::FMINC";
11676 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11677 case X86ISD::FRCP: return "X86ISD::FRCP";
11678 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11679 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11680 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11681 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11682 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11683 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11684 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11685 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11686 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11687 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11688 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11689 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11690 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11691 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11692 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11693 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11694 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11695 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11696 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11697 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11698 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11699 case X86ISD::VSHL: return "X86ISD::VSHL";
11700 case X86ISD::VSRL: return "X86ISD::VSRL";
11701 case X86ISD::VSRA: return "X86ISD::VSRA";
11702 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11703 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11704 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11705 case X86ISD::CMPP: return "X86ISD::CMPP";
11706 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11707 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11708 case X86ISD::ADD: return "X86ISD::ADD";
11709 case X86ISD::SUB: return "X86ISD::SUB";
11710 case X86ISD::ADC: return "X86ISD::ADC";
11711 case X86ISD::SBB: return "X86ISD::SBB";
11712 case X86ISD::SMUL: return "X86ISD::SMUL";
11713 case X86ISD::UMUL: return "X86ISD::UMUL";
11714 case X86ISD::INC: return "X86ISD::INC";
11715 case X86ISD::DEC: return "X86ISD::DEC";
11716 case X86ISD::OR: return "X86ISD::OR";
11717 case X86ISD::XOR: return "X86ISD::XOR";
11718 case X86ISD::AND: return "X86ISD::AND";
11719 case X86ISD::ANDN: return "X86ISD::ANDN";
11720 case X86ISD::BLSI: return "X86ISD::BLSI";
11721 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11722 case X86ISD::BLSR: return "X86ISD::BLSR";
11723 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11724 case X86ISD::PTEST: return "X86ISD::PTEST";
11725 case X86ISD::TESTP: return "X86ISD::TESTP";
11726 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11727 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11728 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11729 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11730 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11731 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11732 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11733 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11734 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11735 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11736 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11737 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11738 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11739 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11740 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11741 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11742 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11743 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11744 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11745 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11746 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11747 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11748 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11749 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11750 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11751 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11752 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11753 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11754 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11755 case X86ISD::SAHF: return "X86ISD::SAHF";
11756 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11757 case X86ISD::FMADD: return "X86ISD::FMADD";
11758 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11759 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11760 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11761 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11762 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11766 // isLegalAddressingMode - Return true if the addressing mode represented
11767 // by AM is legal for this target, for a load/store of the specified type.
11768 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11770 // X86 supports extremely general addressing modes.
11771 CodeModel::Model M = getTargetMachine().getCodeModel();
11772 Reloc::Model R = getTargetMachine().getRelocationModel();
11774 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11775 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11780 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11782 // If a reference to this global requires an extra load, we can't fold it.
11783 if (isGlobalStubReference(GVFlags))
11786 // If BaseGV requires a register for the PIC base, we cannot also have a
11787 // BaseReg specified.
11788 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11791 // If lower 4G is not available, then we must use rip-relative addressing.
11792 if ((M != CodeModel::Small || R != Reloc::Static) &&
11793 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11797 switch (AM.Scale) {
11803 // These scales always work.
11808 // These scales are formed with basereg+scalereg. Only accept if there is
11813 default: // Other stuff never works.
11821 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11822 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11824 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11825 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11826 if (NumBits1 <= NumBits2)
11831 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11832 return Imm == (int32_t)Imm;
11835 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11836 // Can also use sub to handle negated immediates.
11837 return Imm == (int32_t)Imm;
11840 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11841 if (!VT1.isInteger() || !VT2.isInteger())
11843 unsigned NumBits1 = VT1.getSizeInBits();
11844 unsigned NumBits2 = VT2.getSizeInBits();
11845 if (NumBits1 <= NumBits2)
11850 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11851 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11852 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11855 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11856 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11857 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11860 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11861 // i16 instructions are longer (0x66 prefix) and potentially slower.
11862 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11865 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11866 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11867 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11868 /// are assumed to be legal.
11870 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11872 // Very little shuffling can be done for 64-bit vectors right now.
11873 if (VT.getSizeInBits() == 64)
11876 // FIXME: pshufb, blends, shifts.
11877 return (VT.getVectorNumElements() == 2 ||
11878 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11879 isMOVLMask(M, VT) ||
11880 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11881 isPSHUFDMask(M, VT) ||
11882 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11883 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11884 isPALIGNRMask(M, VT, Subtarget) ||
11885 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11886 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11887 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11888 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11892 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11894 unsigned NumElts = VT.getVectorNumElements();
11895 // FIXME: This collection of masks seems suspect.
11898 if (NumElts == 4 && VT.is128BitVector()) {
11899 return (isMOVLMask(Mask, VT) ||
11900 isCommutedMOVLMask(Mask, VT, true) ||
11901 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11902 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11907 //===----------------------------------------------------------------------===//
11908 // X86 Scheduler Hooks
11909 //===----------------------------------------------------------------------===//
11911 // private utility function
11912 MachineBasicBlock *
11913 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11914 MachineBasicBlock *MBB,
11921 const TargetRegisterClass *RC,
11922 bool Invert) const {
11923 // For the atomic bitwise operator, we generate
11926 // ld t1 = [bitinstr.addr]
11927 // op t2 = t1, [bitinstr.val]
11928 // not t3 = t2 (if Invert)
11930 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11932 // fallthrough -->nextMBB
11933 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11934 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11935 MachineFunction::iterator MBBIter = MBB;
11938 /// First build the CFG
11939 MachineFunction *F = MBB->getParent();
11940 MachineBasicBlock *thisMBB = MBB;
11941 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11942 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11943 F->insert(MBBIter, newMBB);
11944 F->insert(MBBIter, nextMBB);
11946 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11947 nextMBB->splice(nextMBB->begin(), thisMBB,
11948 llvm::next(MachineBasicBlock::iterator(bInstr)),
11950 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11952 // Update thisMBB to fall through to newMBB
11953 thisMBB->addSuccessor(newMBB);
11955 // newMBB jumps to itself and fall through to nextMBB
11956 newMBB->addSuccessor(nextMBB);
11957 newMBB->addSuccessor(newMBB);
11959 // Insert instructions into newMBB based on incoming instruction
11960 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11961 "unexpected number of operands");
11962 DebugLoc dl = bInstr->getDebugLoc();
11963 MachineOperand& destOper = bInstr->getOperand(0);
11964 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11965 int numArgs = bInstr->getNumOperands() - 1;
11966 for (int i=0; i < numArgs; ++i)
11967 argOpers[i] = &bInstr->getOperand(i+1);
11969 // x86 address has 4 operands: base, index, scale, and displacement
11970 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11971 int valArgIndx = lastAddrIndx + 1;
11973 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11974 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11975 for (int i=0; i <= lastAddrIndx; ++i)
11976 (*MIB).addOperand(*argOpers[i]);
11978 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11979 assert((argOpers[valArgIndx]->isReg() ||
11980 argOpers[valArgIndx]->isImm()) &&
11981 "invalid operand");
11982 if (argOpers[valArgIndx]->isReg())
11983 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11985 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11987 (*MIB).addOperand(*argOpers[valArgIndx]);
11989 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11991 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11996 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11999 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
12000 for (int i=0; i <= lastAddrIndx; ++i)
12001 (*MIB).addOperand(*argOpers[i]);
12003 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12004 (*MIB).setMemRefs(bInstr->memoperands_begin(),
12005 bInstr->memoperands_end());
12007 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12008 MIB.addReg(EAXreg);
12011 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12013 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
12017 // private utility function: 64 bit atomics on 32 bit host.
12018 MachineBasicBlock *
12019 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
12020 MachineBasicBlock *MBB,
12025 bool Invert) const {
12026 // For the atomic bitwise operator, we generate
12027 // thisMBB (instructions are in pairs, except cmpxchg8b)
12028 // ld t1,t2 = [bitinstr.addr]
12030 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
12031 // op t5, t6 <- out1, out2, [bitinstr.val]
12032 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
12033 // neg t7, t8 < t5, t6 (if Invert)
12034 // mov ECX, EBX <- t5, t6
12035 // mov EAX, EDX <- t1, t2
12036 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
12037 // mov t3, t4 <- EAX, EDX
12039 // result in out1, out2
12040 // fallthrough -->nextMBB
12042 const TargetRegisterClass *RC = &X86::GR32RegClass;
12043 const unsigned LoadOpc = X86::MOV32rm;
12044 const unsigned NotOpc = X86::NOT32r;
12045 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12046 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12047 MachineFunction::iterator MBBIter = MBB;
12050 /// First build the CFG
12051 MachineFunction *F = MBB->getParent();
12052 MachineBasicBlock *thisMBB = MBB;
12053 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12054 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12055 F->insert(MBBIter, newMBB);
12056 F->insert(MBBIter, nextMBB);
12058 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12059 nextMBB->splice(nextMBB->begin(), thisMBB,
12060 llvm::next(MachineBasicBlock::iterator(bInstr)),
12062 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12064 // Update thisMBB to fall through to newMBB
12065 thisMBB->addSuccessor(newMBB);
12067 // newMBB jumps to itself and fall through to nextMBB
12068 newMBB->addSuccessor(nextMBB);
12069 newMBB->addSuccessor(newMBB);
12071 DebugLoc dl = bInstr->getDebugLoc();
12072 // Insert instructions into newMBB based on incoming instruction
12073 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
12074 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
12075 "unexpected number of operands");
12076 MachineOperand& dest1Oper = bInstr->getOperand(0);
12077 MachineOperand& dest2Oper = bInstr->getOperand(1);
12078 MachineOperand* argOpers[2 + X86::AddrNumOperands];
12079 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
12080 argOpers[i] = &bInstr->getOperand(i+2);
12082 // We use some of the operands multiple times, so conservatively just
12083 // clear any kill flags that might be present.
12084 if (argOpers[i]->isReg() && argOpers[i]->isUse())
12085 argOpers[i]->setIsKill(false);
12088 // x86 address has 5 operands: base, index, scale, displacement, and segment.
12089 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12091 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
12092 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
12093 for (int i=0; i <= lastAddrIndx; ++i)
12094 (*MIB).addOperand(*argOpers[i]);
12095 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
12096 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
12097 // add 4 to displacement.
12098 for (int i=0; i <= lastAddrIndx-2; ++i)
12099 (*MIB).addOperand(*argOpers[i]);
12100 MachineOperand newOp3 = *(argOpers[3]);
12101 if (newOp3.isImm())
12102 newOp3.setImm(newOp3.getImm()+4);
12104 newOp3.setOffset(newOp3.getOffset()+4);
12105 (*MIB).addOperand(newOp3);
12106 (*MIB).addOperand(*argOpers[lastAddrIndx]);
12108 // t3/4 are defined later, at the bottom of the loop
12109 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
12110 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
12111 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
12112 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
12113 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
12114 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
12116 // The subsequent operations should be using the destination registers of
12117 // the PHI instructions.
12118 t1 = dest1Oper.getReg();
12119 t2 = dest2Oper.getReg();
12121 int valArgIndx = lastAddrIndx + 1;
12122 assert((argOpers[valArgIndx]->isReg() ||
12123 argOpers[valArgIndx]->isImm()) &&
12124 "invalid operand");
12125 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12126 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12127 if (argOpers[valArgIndx]->isReg())
12128 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12130 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12131 if (regOpcL != X86::MOV32rr)
12133 (*MIB).addOperand(*argOpers[valArgIndx]);
12134 assert(argOpers[valArgIndx + 1]->isReg() ==
12135 argOpers[valArgIndx]->isReg());
12136 assert(argOpers[valArgIndx + 1]->isImm() ==
12137 argOpers[valArgIndx]->isImm());
12138 if (argOpers[valArgIndx + 1]->isReg())
12139 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12141 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12142 if (regOpcH != X86::MOV32rr)
12144 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12148 t7 = F->getRegInfo().createVirtualRegister(RC);
12149 t8 = F->getRegInfo().createVirtualRegister(RC);
12150 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12151 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12157 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12159 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12162 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12164 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12167 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12168 for (int i=0; i <= lastAddrIndx; ++i)
12169 (*MIB).addOperand(*argOpers[i]);
12171 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12172 (*MIB).setMemRefs(bInstr->memoperands_begin(),
12173 bInstr->memoperands_end());
12175 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12176 MIB.addReg(X86::EAX);
12177 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12178 MIB.addReg(X86::EDX);
12181 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12183 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
12187 // private utility function
12188 MachineBasicBlock *
12189 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12190 MachineBasicBlock *MBB,
12191 unsigned cmovOpc) const {
12192 // For the atomic min/max operator, we generate
12195 // ld t1 = [min/max.addr]
12196 // mov t2 = [min/max.val]
12198 // cmov[cond] t2 = t1
12200 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
12202 // fallthrough -->nextMBB
12204 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12205 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12206 MachineFunction::iterator MBBIter = MBB;
12209 /// First build the CFG
12210 MachineFunction *F = MBB->getParent();
12211 MachineBasicBlock *thisMBB = MBB;
12212 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12213 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12214 F->insert(MBBIter, newMBB);
12215 F->insert(MBBIter, nextMBB);
12217 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12218 nextMBB->splice(nextMBB->begin(), thisMBB,
12219 llvm::next(MachineBasicBlock::iterator(mInstr)),
12221 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12223 // Update thisMBB to fall through to newMBB
12224 thisMBB->addSuccessor(newMBB);
12226 // newMBB jumps to newMBB and fall through to nextMBB
12227 newMBB->addSuccessor(nextMBB);
12228 newMBB->addSuccessor(newMBB);
12230 DebugLoc dl = mInstr->getDebugLoc();
12231 // Insert instructions into newMBB based on incoming instruction
12232 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12233 "unexpected number of operands");
12234 MachineOperand& destOper = mInstr->getOperand(0);
12235 MachineOperand* argOpers[2 + X86::AddrNumOperands];
12236 int numArgs = mInstr->getNumOperands() - 1;
12237 for (int i=0; i < numArgs; ++i)
12238 argOpers[i] = &mInstr->getOperand(i+1);
12240 // x86 address has 4 operands: base, index, scale, and displacement
12241 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12242 int valArgIndx = lastAddrIndx + 1;
12244 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12245 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12246 for (int i=0; i <= lastAddrIndx; ++i)
12247 (*MIB).addOperand(*argOpers[i]);
12249 // We only support register and immediate values
12250 assert((argOpers[valArgIndx]->isReg() ||
12251 argOpers[valArgIndx]->isImm()) &&
12252 "invalid operand");
12254 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12255 if (argOpers[valArgIndx]->isReg())
12256 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12258 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12259 (*MIB).addOperand(*argOpers[valArgIndx]);
12261 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12264 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12269 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12270 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12274 // Cmp and exchange if none has modified the memory location
12275 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12276 for (int i=0; i <= lastAddrIndx; ++i)
12277 (*MIB).addOperand(*argOpers[i]);
12279 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12280 (*MIB).setMemRefs(mInstr->memoperands_begin(),
12281 mInstr->memoperands_end());
12283 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12284 MIB.addReg(X86::EAX);
12287 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12289 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
12293 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12294 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12295 // in the .td file.
12296 MachineBasicBlock *
12297 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12298 unsigned numArgs, bool memArg) const {
12299 assert(Subtarget->hasSSE42() &&
12300 "Target must have SSE4.2 or AVX features enabled");
12302 DebugLoc dl = MI->getDebugLoc();
12303 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12305 if (!Subtarget->hasAVX()) {
12307 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12309 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12312 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12314 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12317 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12318 for (unsigned i = 0; i < numArgs; ++i) {
12319 MachineOperand &Op = MI->getOperand(i+1);
12320 if (!(Op.isReg() && Op.isImplicit()))
12321 MIB.addOperand(Op);
12323 BuildMI(*BB, MI, dl,
12324 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12325 .addReg(X86::XMM0);
12327 MI->eraseFromParent();
12331 MachineBasicBlock *
12332 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12333 DebugLoc dl = MI->getDebugLoc();
12334 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12336 // Address into RAX/EAX, other two args into ECX, EDX.
12337 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12338 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12339 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12340 for (int i = 0; i < X86::AddrNumOperands; ++i)
12341 MIB.addOperand(MI->getOperand(i));
12343 unsigned ValOps = X86::AddrNumOperands;
12344 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12345 .addReg(MI->getOperand(ValOps).getReg());
12346 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12347 .addReg(MI->getOperand(ValOps+1).getReg());
12349 // The instruction doesn't actually take any operands though.
12350 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12352 MI->eraseFromParent(); // The pseudo is gone now.
12356 MachineBasicBlock *
12357 X86TargetLowering::EmitVAARG64WithCustomInserter(
12359 MachineBasicBlock *MBB) const {
12360 // Emit va_arg instruction on X86-64.
12362 // Operands to this pseudo-instruction:
12363 // 0 ) Output : destination address (reg)
12364 // 1-5) Input : va_list address (addr, i64mem)
12365 // 6 ) ArgSize : Size (in bytes) of vararg type
12366 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12367 // 8 ) Align : Alignment of type
12368 // 9 ) EFLAGS (implicit-def)
12370 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12371 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12373 unsigned DestReg = MI->getOperand(0).getReg();
12374 MachineOperand &Base = MI->getOperand(1);
12375 MachineOperand &Scale = MI->getOperand(2);
12376 MachineOperand &Index = MI->getOperand(3);
12377 MachineOperand &Disp = MI->getOperand(4);
12378 MachineOperand &Segment = MI->getOperand(5);
12379 unsigned ArgSize = MI->getOperand(6).getImm();
12380 unsigned ArgMode = MI->getOperand(7).getImm();
12381 unsigned Align = MI->getOperand(8).getImm();
12383 // Memory Reference
12384 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12385 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12386 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12388 // Machine Information
12389 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12390 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12391 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12392 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12393 DebugLoc DL = MI->getDebugLoc();
12395 // struct va_list {
12398 // i64 overflow_area (address)
12399 // i64 reg_save_area (address)
12401 // sizeof(va_list) = 24
12402 // alignment(va_list) = 8
12404 unsigned TotalNumIntRegs = 6;
12405 unsigned TotalNumXMMRegs = 8;
12406 bool UseGPOffset = (ArgMode == 1);
12407 bool UseFPOffset = (ArgMode == 2);
12408 unsigned MaxOffset = TotalNumIntRegs * 8 +
12409 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12411 /* Align ArgSize to a multiple of 8 */
12412 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12413 bool NeedsAlign = (Align > 8);
12415 MachineBasicBlock *thisMBB = MBB;
12416 MachineBasicBlock *overflowMBB;
12417 MachineBasicBlock *offsetMBB;
12418 MachineBasicBlock *endMBB;
12420 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12421 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12422 unsigned OffsetReg = 0;
12424 if (!UseGPOffset && !UseFPOffset) {
12425 // If we only pull from the overflow region, we don't create a branch.
12426 // We don't need to alter control flow.
12427 OffsetDestReg = 0; // unused
12428 OverflowDestReg = DestReg;
12431 overflowMBB = thisMBB;
12434 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12435 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12436 // If not, pull from overflow_area. (branch to overflowMBB)
12441 // offsetMBB overflowMBB
12446 // Registers for the PHI in endMBB
12447 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12448 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12450 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12451 MachineFunction *MF = MBB->getParent();
12452 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12453 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12454 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12456 MachineFunction::iterator MBBIter = MBB;
12459 // Insert the new basic blocks
12460 MF->insert(MBBIter, offsetMBB);
12461 MF->insert(MBBIter, overflowMBB);
12462 MF->insert(MBBIter, endMBB);
12464 // Transfer the remainder of MBB and its successor edges to endMBB.
12465 endMBB->splice(endMBB->begin(), thisMBB,
12466 llvm::next(MachineBasicBlock::iterator(MI)),
12468 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12470 // Make offsetMBB and overflowMBB successors of thisMBB
12471 thisMBB->addSuccessor(offsetMBB);
12472 thisMBB->addSuccessor(overflowMBB);
12474 // endMBB is a successor of both offsetMBB and overflowMBB
12475 offsetMBB->addSuccessor(endMBB);
12476 overflowMBB->addSuccessor(endMBB);
12478 // Load the offset value into a register
12479 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12480 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12484 .addDisp(Disp, UseFPOffset ? 4 : 0)
12485 .addOperand(Segment)
12486 .setMemRefs(MMOBegin, MMOEnd);
12488 // Check if there is enough room left to pull this argument.
12489 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12491 .addImm(MaxOffset + 8 - ArgSizeA8);
12493 // Branch to "overflowMBB" if offset >= max
12494 // Fall through to "offsetMBB" otherwise
12495 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12496 .addMBB(overflowMBB);
12499 // In offsetMBB, emit code to use the reg_save_area.
12501 assert(OffsetReg != 0);
12503 // Read the reg_save_area address.
12504 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12505 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12510 .addOperand(Segment)
12511 .setMemRefs(MMOBegin, MMOEnd);
12513 // Zero-extend the offset
12514 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12515 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12518 .addImm(X86::sub_32bit);
12520 // Add the offset to the reg_save_area to get the final address.
12521 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12522 .addReg(OffsetReg64)
12523 .addReg(RegSaveReg);
12525 // Compute the offset for the next argument
12526 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12527 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12529 .addImm(UseFPOffset ? 16 : 8);
12531 // Store it back into the va_list.
12532 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12536 .addDisp(Disp, UseFPOffset ? 4 : 0)
12537 .addOperand(Segment)
12538 .addReg(NextOffsetReg)
12539 .setMemRefs(MMOBegin, MMOEnd);
12542 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12547 // Emit code to use overflow area
12550 // Load the overflow_area address into a register.
12551 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12552 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12557 .addOperand(Segment)
12558 .setMemRefs(MMOBegin, MMOEnd);
12560 // If we need to align it, do so. Otherwise, just copy the address
12561 // to OverflowDestReg.
12563 // Align the overflow address
12564 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12565 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12567 // aligned_addr = (addr + (align-1)) & ~(align-1)
12568 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12569 .addReg(OverflowAddrReg)
12572 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12574 .addImm(~(uint64_t)(Align-1));
12576 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12577 .addReg(OverflowAddrReg);
12580 // Compute the next overflow address after this argument.
12581 // (the overflow address should be kept 8-byte aligned)
12582 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12583 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12584 .addReg(OverflowDestReg)
12585 .addImm(ArgSizeA8);
12587 // Store the new overflow address.
12588 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12593 .addOperand(Segment)
12594 .addReg(NextAddrReg)
12595 .setMemRefs(MMOBegin, MMOEnd);
12597 // If we branched, emit the PHI to the front of endMBB.
12599 BuildMI(*endMBB, endMBB->begin(), DL,
12600 TII->get(X86::PHI), DestReg)
12601 .addReg(OffsetDestReg).addMBB(offsetMBB)
12602 .addReg(OverflowDestReg).addMBB(overflowMBB);
12605 // Erase the pseudo instruction
12606 MI->eraseFromParent();
12611 MachineBasicBlock *
12612 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12614 MachineBasicBlock *MBB) const {
12615 // Emit code to save XMM registers to the stack. The ABI says that the
12616 // number of registers to save is given in %al, so it's theoretically
12617 // possible to do an indirect jump trick to avoid saving all of them,
12618 // however this code takes a simpler approach and just executes all
12619 // of the stores if %al is non-zero. It's less code, and it's probably
12620 // easier on the hardware branch predictor, and stores aren't all that
12621 // expensive anyway.
12623 // Create the new basic blocks. One block contains all the XMM stores,
12624 // and one block is the final destination regardless of whether any
12625 // stores were performed.
12626 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12627 MachineFunction *F = MBB->getParent();
12628 MachineFunction::iterator MBBIter = MBB;
12630 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12631 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12632 F->insert(MBBIter, XMMSaveMBB);
12633 F->insert(MBBIter, EndMBB);
12635 // Transfer the remainder of MBB and its successor edges to EndMBB.
12636 EndMBB->splice(EndMBB->begin(), MBB,
12637 llvm::next(MachineBasicBlock::iterator(MI)),
12639 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12641 // The original block will now fall through to the XMM save block.
12642 MBB->addSuccessor(XMMSaveMBB);
12643 // The XMMSaveMBB will fall through to the end block.
12644 XMMSaveMBB->addSuccessor(EndMBB);
12646 // Now add the instructions.
12647 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12648 DebugLoc DL = MI->getDebugLoc();
12650 unsigned CountReg = MI->getOperand(0).getReg();
12651 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12652 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12654 if (!Subtarget->isTargetWin64()) {
12655 // If %al is 0, branch around the XMM save block.
12656 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12657 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12658 MBB->addSuccessor(EndMBB);
12661 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12662 // In the XMM save block, save all the XMM argument registers.
12663 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12664 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12665 MachineMemOperand *MMO =
12666 F->getMachineMemOperand(
12667 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12668 MachineMemOperand::MOStore,
12669 /*Size=*/16, /*Align=*/16);
12670 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12671 .addFrameIndex(RegSaveFrameIndex)
12672 .addImm(/*Scale=*/1)
12673 .addReg(/*IndexReg=*/0)
12674 .addImm(/*Disp=*/Offset)
12675 .addReg(/*Segment=*/0)
12676 .addReg(MI->getOperand(i).getReg())
12677 .addMemOperand(MMO);
12680 MI->eraseFromParent(); // The pseudo instruction is gone now.
12685 // The EFLAGS operand of SelectItr might be missing a kill marker
12686 // because there were multiple uses of EFLAGS, and ISel didn't know
12687 // which to mark. Figure out whether SelectItr should have had a
12688 // kill marker, and set it if it should. Returns the correct kill
12690 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12691 MachineBasicBlock* BB,
12692 const TargetRegisterInfo* TRI) {
12693 // Scan forward through BB for a use/def of EFLAGS.
12694 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12695 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12696 const MachineInstr& mi = *miI;
12697 if (mi.readsRegister(X86::EFLAGS))
12699 if (mi.definesRegister(X86::EFLAGS))
12700 break; // Should have kill-flag - update below.
12703 // If we hit the end of the block, check whether EFLAGS is live into a
12705 if (miI == BB->end()) {
12706 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12707 sEnd = BB->succ_end();
12708 sItr != sEnd; ++sItr) {
12709 MachineBasicBlock* succ = *sItr;
12710 if (succ->isLiveIn(X86::EFLAGS))
12715 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12716 // out. SelectMI should have a kill flag on EFLAGS.
12717 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12721 MachineBasicBlock *
12722 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12723 MachineBasicBlock *BB) const {
12724 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12725 DebugLoc DL = MI->getDebugLoc();
12727 // To "insert" a SELECT_CC instruction, we actually have to insert the
12728 // diamond control-flow pattern. The incoming instruction knows the
12729 // destination vreg to set, the condition code register to branch on, the
12730 // true/false values to select between, and a branch opcode to use.
12731 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12732 MachineFunction::iterator It = BB;
12738 // cmpTY ccX, r1, r2
12740 // fallthrough --> copy0MBB
12741 MachineBasicBlock *thisMBB = BB;
12742 MachineFunction *F = BB->getParent();
12743 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12744 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12745 F->insert(It, copy0MBB);
12746 F->insert(It, sinkMBB);
12748 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12749 // live into the sink and copy blocks.
12750 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12751 if (!MI->killsRegister(X86::EFLAGS) &&
12752 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12753 copy0MBB->addLiveIn(X86::EFLAGS);
12754 sinkMBB->addLiveIn(X86::EFLAGS);
12757 // Transfer the remainder of BB and its successor edges to sinkMBB.
12758 sinkMBB->splice(sinkMBB->begin(), BB,
12759 llvm::next(MachineBasicBlock::iterator(MI)),
12761 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12763 // Add the true and fallthrough blocks as its successors.
12764 BB->addSuccessor(copy0MBB);
12765 BB->addSuccessor(sinkMBB);
12767 // Create the conditional branch instruction.
12769 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12770 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12773 // %FalseValue = ...
12774 // # fallthrough to sinkMBB
12775 copy0MBB->addSuccessor(sinkMBB);
12778 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12780 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12781 TII->get(X86::PHI), MI->getOperand(0).getReg())
12782 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12783 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12785 MI->eraseFromParent(); // The pseudo instruction is gone now.
12789 MachineBasicBlock *
12790 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12791 bool Is64Bit) const {
12792 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12793 DebugLoc DL = MI->getDebugLoc();
12794 MachineFunction *MF = BB->getParent();
12795 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12797 assert(getTargetMachine().Options.EnableSegmentedStacks);
12799 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12800 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12803 // ... [Till the alloca]
12804 // If stacklet is not large enough, jump to mallocMBB
12807 // Allocate by subtracting from RSP
12808 // Jump to continueMBB
12811 // Allocate by call to runtime
12815 // [rest of original BB]
12818 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12819 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12820 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12822 MachineRegisterInfo &MRI = MF->getRegInfo();
12823 const TargetRegisterClass *AddrRegClass =
12824 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12826 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12827 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12828 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12829 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12830 sizeVReg = MI->getOperand(1).getReg(),
12831 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12833 MachineFunction::iterator MBBIter = BB;
12836 MF->insert(MBBIter, bumpMBB);
12837 MF->insert(MBBIter, mallocMBB);
12838 MF->insert(MBBIter, continueMBB);
12840 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12841 (MachineBasicBlock::iterator(MI)), BB->end());
12842 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12844 // Add code to the main basic block to check if the stack limit has been hit,
12845 // and if so, jump to mallocMBB otherwise to bumpMBB.
12846 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12847 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12848 .addReg(tmpSPVReg).addReg(sizeVReg);
12849 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12850 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12851 .addReg(SPLimitVReg);
12852 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12854 // bumpMBB simply decreases the stack pointer, since we know the current
12855 // stacklet has enough space.
12856 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12857 .addReg(SPLimitVReg);
12858 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12859 .addReg(SPLimitVReg);
12860 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12862 // Calls into a routine in libgcc to allocate more space from the heap.
12863 const uint32_t *RegMask =
12864 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12866 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12868 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12869 .addExternalSymbol("__morestack_allocate_stack_space")
12870 .addRegMask(RegMask)
12871 .addReg(X86::RDI, RegState::Implicit)
12872 .addReg(X86::RAX, RegState::ImplicitDefine);
12874 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12876 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12877 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12878 .addExternalSymbol("__morestack_allocate_stack_space")
12879 .addRegMask(RegMask)
12880 .addReg(X86::EAX, RegState::ImplicitDefine);
12884 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12887 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12888 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12889 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12891 // Set up the CFG correctly.
12892 BB->addSuccessor(bumpMBB);
12893 BB->addSuccessor(mallocMBB);
12894 mallocMBB->addSuccessor(continueMBB);
12895 bumpMBB->addSuccessor(continueMBB);
12897 // Take care of the PHI nodes.
12898 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12899 MI->getOperand(0).getReg())
12900 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12901 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12903 // Delete the original pseudo instruction.
12904 MI->eraseFromParent();
12907 return continueMBB;
12910 MachineBasicBlock *
12911 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12912 MachineBasicBlock *BB) const {
12913 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12914 DebugLoc DL = MI->getDebugLoc();
12916 assert(!Subtarget->isTargetEnvMacho());
12918 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12919 // non-trivial part is impdef of ESP.
12921 if (Subtarget->isTargetWin64()) {
12922 if (Subtarget->isTargetCygMing()) {
12923 // ___chkstk(Mingw64):
12924 // Clobbers R10, R11, RAX and EFLAGS.
12926 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12927 .addExternalSymbol("___chkstk")
12928 .addReg(X86::RAX, RegState::Implicit)
12929 .addReg(X86::RSP, RegState::Implicit)
12930 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12931 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12932 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12934 // __chkstk(MSVCRT): does not update stack pointer.
12935 // Clobbers R10, R11 and EFLAGS.
12936 // FIXME: RAX(allocated size) might be reused and not killed.
12937 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12938 .addExternalSymbol("__chkstk")
12939 .addReg(X86::RAX, RegState::Implicit)
12940 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12941 // RAX has the offset to subtracted from RSP.
12942 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12947 const char *StackProbeSymbol =
12948 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12950 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12951 .addExternalSymbol(StackProbeSymbol)
12952 .addReg(X86::EAX, RegState::Implicit)
12953 .addReg(X86::ESP, RegState::Implicit)
12954 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12955 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12956 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12959 MI->eraseFromParent(); // The pseudo instruction is gone now.
12963 MachineBasicBlock *
12964 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12965 MachineBasicBlock *BB) const {
12966 // This is pretty easy. We're taking the value that we received from
12967 // our load from the relocation, sticking it in either RDI (x86-64)
12968 // or EAX and doing an indirect call. The return value will then
12969 // be in the normal return register.
12970 const X86InstrInfo *TII
12971 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12972 DebugLoc DL = MI->getDebugLoc();
12973 MachineFunction *F = BB->getParent();
12975 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12976 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12978 // Get a register mask for the lowered call.
12979 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12980 // proper register mask.
12981 const uint32_t *RegMask =
12982 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12983 if (Subtarget->is64Bit()) {
12984 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12985 TII->get(X86::MOV64rm), X86::RDI)
12987 .addImm(0).addReg(0)
12988 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12989 MI->getOperand(3).getTargetFlags())
12991 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12992 addDirectMem(MIB, X86::RDI);
12993 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12994 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12995 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12996 TII->get(X86::MOV32rm), X86::EAX)
12998 .addImm(0).addReg(0)
12999 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13000 MI->getOperand(3).getTargetFlags())
13002 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13003 addDirectMem(MIB, X86::EAX);
13004 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13006 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13007 TII->get(X86::MOV32rm), X86::EAX)
13008 .addReg(TII->getGlobalBaseReg(F))
13009 .addImm(0).addReg(0)
13010 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13011 MI->getOperand(3).getTargetFlags())
13013 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13014 addDirectMem(MIB, X86::EAX);
13015 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13018 MI->eraseFromParent(); // The pseudo instruction is gone now.
13022 MachineBasicBlock *
13023 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13024 MachineBasicBlock *BB) const {
13025 switch (MI->getOpcode()) {
13026 default: llvm_unreachable("Unexpected instr type to insert");
13027 case X86::TAILJMPd64:
13028 case X86::TAILJMPr64:
13029 case X86::TAILJMPm64:
13030 llvm_unreachable("TAILJMP64 would not be touched here.");
13031 case X86::TCRETURNdi64:
13032 case X86::TCRETURNri64:
13033 case X86::TCRETURNmi64:
13035 case X86::WIN_ALLOCA:
13036 return EmitLoweredWinAlloca(MI, BB);
13037 case X86::SEG_ALLOCA_32:
13038 return EmitLoweredSegAlloca(MI, BB, false);
13039 case X86::SEG_ALLOCA_64:
13040 return EmitLoweredSegAlloca(MI, BB, true);
13041 case X86::TLSCall_32:
13042 case X86::TLSCall_64:
13043 return EmitLoweredTLSCall(MI, BB);
13044 case X86::CMOV_GR8:
13045 case X86::CMOV_FR32:
13046 case X86::CMOV_FR64:
13047 case X86::CMOV_V4F32:
13048 case X86::CMOV_V2F64:
13049 case X86::CMOV_V2I64:
13050 case X86::CMOV_V8F32:
13051 case X86::CMOV_V4F64:
13052 case X86::CMOV_V4I64:
13053 case X86::CMOV_GR16:
13054 case X86::CMOV_GR32:
13055 case X86::CMOV_RFP32:
13056 case X86::CMOV_RFP64:
13057 case X86::CMOV_RFP80:
13058 return EmitLoweredSelect(MI, BB);
13060 case X86::FP32_TO_INT16_IN_MEM:
13061 case X86::FP32_TO_INT32_IN_MEM:
13062 case X86::FP32_TO_INT64_IN_MEM:
13063 case X86::FP64_TO_INT16_IN_MEM:
13064 case X86::FP64_TO_INT32_IN_MEM:
13065 case X86::FP64_TO_INT64_IN_MEM:
13066 case X86::FP80_TO_INT16_IN_MEM:
13067 case X86::FP80_TO_INT32_IN_MEM:
13068 case X86::FP80_TO_INT64_IN_MEM: {
13069 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13070 DebugLoc DL = MI->getDebugLoc();
13072 // Change the floating point control register to use "round towards zero"
13073 // mode when truncating to an integer value.
13074 MachineFunction *F = BB->getParent();
13075 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13076 addFrameReference(BuildMI(*BB, MI, DL,
13077 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13079 // Load the old value of the high byte of the control word...
13081 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13082 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13085 // Set the high part to be round to zero...
13086 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13089 // Reload the modified control word now...
13090 addFrameReference(BuildMI(*BB, MI, DL,
13091 TII->get(X86::FLDCW16m)), CWFrameIdx);
13093 // Restore the memory image of control word to original value
13094 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13097 // Get the X86 opcode to use.
13099 switch (MI->getOpcode()) {
13100 default: llvm_unreachable("illegal opcode!");
13101 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13102 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13103 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13104 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13105 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13106 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13107 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13108 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13109 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13113 MachineOperand &Op = MI->getOperand(0);
13115 AM.BaseType = X86AddressMode::RegBase;
13116 AM.Base.Reg = Op.getReg();
13118 AM.BaseType = X86AddressMode::FrameIndexBase;
13119 AM.Base.FrameIndex = Op.getIndex();
13121 Op = MI->getOperand(1);
13123 AM.Scale = Op.getImm();
13124 Op = MI->getOperand(2);
13126 AM.IndexReg = Op.getImm();
13127 Op = MI->getOperand(3);
13128 if (Op.isGlobal()) {
13129 AM.GV = Op.getGlobal();
13131 AM.Disp = Op.getImm();
13133 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13134 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13136 // Reload the original control word now.
13137 addFrameReference(BuildMI(*BB, MI, DL,
13138 TII->get(X86::FLDCW16m)), CWFrameIdx);
13140 MI->eraseFromParent(); // The pseudo instruction is gone now.
13143 // String/text processing lowering.
13144 case X86::PCMPISTRM128REG:
13145 case X86::VPCMPISTRM128REG:
13146 case X86::PCMPISTRM128MEM:
13147 case X86::VPCMPISTRM128MEM:
13148 case X86::PCMPESTRM128REG:
13149 case X86::VPCMPESTRM128REG:
13150 case X86::PCMPESTRM128MEM:
13151 case X86::VPCMPESTRM128MEM: {
13154 switch (MI->getOpcode()) {
13155 default: llvm_unreachable("illegal opcode!");
13156 case X86::PCMPISTRM128REG:
13157 case X86::VPCMPISTRM128REG:
13158 NumArgs = 3; MemArg = false; break;
13159 case X86::PCMPISTRM128MEM:
13160 case X86::VPCMPISTRM128MEM:
13161 NumArgs = 3; MemArg = true; break;
13162 case X86::PCMPESTRM128REG:
13163 case X86::VPCMPESTRM128REG:
13164 NumArgs = 5; MemArg = false; break;
13165 case X86::PCMPESTRM128MEM:
13166 case X86::VPCMPESTRM128MEM:
13167 NumArgs = 5; MemArg = true; break;
13169 return EmitPCMP(MI, BB, NumArgs, MemArg);
13172 // Thread synchronization.
13174 return EmitMonitor(MI, BB);
13176 // Atomic Lowering.
13177 case X86::ATOMMIN32:
13178 case X86::ATOMMAX32:
13179 case X86::ATOMUMIN32:
13180 case X86::ATOMUMAX32:
13181 case X86::ATOMMIN16:
13182 case X86::ATOMMAX16:
13183 case X86::ATOMUMIN16:
13184 case X86::ATOMUMAX16:
13185 case X86::ATOMMIN64:
13186 case X86::ATOMMAX64:
13187 case X86::ATOMUMIN64:
13188 case X86::ATOMUMAX64: {
13190 switch (MI->getOpcode()) {
13191 default: llvm_unreachable("illegal opcode!");
13192 case X86::ATOMMIN32: Opc = X86::CMOVL32rr; break;
13193 case X86::ATOMMAX32: Opc = X86::CMOVG32rr; break;
13194 case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13195 case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13196 case X86::ATOMMIN16: Opc = X86::CMOVL16rr; break;
13197 case X86::ATOMMAX16: Opc = X86::CMOVG16rr; break;
13198 case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13199 case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13200 case X86::ATOMMIN64: Opc = X86::CMOVL64rr; break;
13201 case X86::ATOMMAX64: Opc = X86::CMOVG64rr; break;
13202 case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13203 case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13204 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13206 return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13209 case X86::ATOMAND32:
13210 case X86::ATOMOR32:
13211 case X86::ATOMXOR32:
13212 case X86::ATOMNAND32: {
13213 bool Invert = false;
13214 unsigned RegOpc, ImmOpc;
13215 switch (MI->getOpcode()) {
13216 default: llvm_unreachable("illegal opcode!");
13217 case X86::ATOMAND32:
13218 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13219 case X86::ATOMOR32:
13220 RegOpc = X86::OR32rr; ImmOpc = X86::OR32ri; break;
13221 case X86::ATOMXOR32:
13222 RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13223 case X86::ATOMNAND32:
13224 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13226 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13227 X86::MOV32rm, X86::LCMPXCHG32,
13228 X86::NOT32r, X86::EAX,
13229 &X86::GR32RegClass, Invert);
13232 case X86::ATOMAND16:
13233 case X86::ATOMOR16:
13234 case X86::ATOMXOR16:
13235 case X86::ATOMNAND16: {
13236 bool Invert = false;
13237 unsigned RegOpc, ImmOpc;
13238 switch (MI->getOpcode()) {
13239 default: llvm_unreachable("illegal opcode!");
13240 case X86::ATOMAND16:
13241 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13242 case X86::ATOMOR16:
13243 RegOpc = X86::OR16rr; ImmOpc = X86::OR16ri; break;
13244 case X86::ATOMXOR16:
13245 RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13246 case X86::ATOMNAND16:
13247 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13249 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13250 X86::MOV16rm, X86::LCMPXCHG16,
13251 X86::NOT16r, X86::AX,
13252 &X86::GR16RegClass, Invert);
13255 case X86::ATOMAND8:
13257 case X86::ATOMXOR8:
13258 case X86::ATOMNAND8: {
13259 bool Invert = false;
13260 unsigned RegOpc, ImmOpc;
13261 switch (MI->getOpcode()) {
13262 default: llvm_unreachable("illegal opcode!");
13263 case X86::ATOMAND8:
13264 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13266 RegOpc = X86::OR8rr; ImmOpc = X86::OR8ri; break;
13267 case X86::ATOMXOR8:
13268 RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13269 case X86::ATOMNAND8:
13270 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13272 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13273 X86::MOV8rm, X86::LCMPXCHG8,
13274 X86::NOT8r, X86::AL,
13275 &X86::GR8RegClass, Invert);
13278 // This group is for 64-bit host.
13279 case X86::ATOMAND64:
13280 case X86::ATOMOR64:
13281 case X86::ATOMXOR64:
13282 case X86::ATOMNAND64: {
13283 bool Invert = false;
13284 unsigned RegOpc, ImmOpc;
13285 switch (MI->getOpcode()) {
13286 default: llvm_unreachable("illegal opcode!");
13287 case X86::ATOMAND64:
13288 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13289 case X86::ATOMOR64:
13290 RegOpc = X86::OR64rr; ImmOpc = X86::OR64ri32; break;
13291 case X86::ATOMXOR64:
13292 RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13293 case X86::ATOMNAND64:
13294 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13296 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13297 X86::MOV64rm, X86::LCMPXCHG64,
13298 X86::NOT64r, X86::RAX,
13299 &X86::GR64RegClass, Invert);
13302 // This group does 64-bit operations on a 32-bit host.
13303 case X86::ATOMAND6432:
13304 case X86::ATOMOR6432:
13305 case X86::ATOMXOR6432:
13306 case X86::ATOMNAND6432:
13307 case X86::ATOMADD6432:
13308 case X86::ATOMSUB6432:
13309 case X86::ATOMSWAP6432: {
13310 bool Invert = false;
13311 unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13312 switch (MI->getOpcode()) {
13313 default: llvm_unreachable("illegal opcode!");
13314 case X86::ATOMAND6432:
13315 RegOpcL = RegOpcH = X86::AND32rr;
13316 ImmOpcL = ImmOpcH = X86::AND32ri;
13318 case X86::ATOMOR6432:
13319 RegOpcL = RegOpcH = X86::OR32rr;
13320 ImmOpcL = ImmOpcH = X86::OR32ri;
13322 case X86::ATOMXOR6432:
13323 RegOpcL = RegOpcH = X86::XOR32rr;
13324 ImmOpcL = ImmOpcH = X86::XOR32ri;
13326 case X86::ATOMNAND6432:
13327 RegOpcL = RegOpcH = X86::AND32rr;
13328 ImmOpcL = ImmOpcH = X86::AND32ri;
13331 case X86::ATOMADD6432:
13332 RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13333 ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13335 case X86::ATOMSUB6432:
13336 RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13337 ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13339 case X86::ATOMSWAP6432:
13340 RegOpcL = RegOpcH = X86::MOV32rr;
13341 ImmOpcL = ImmOpcH = X86::MOV32ri;
13344 return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13345 ImmOpcL, ImmOpcH, Invert);
13348 case X86::VASTART_SAVE_XMM_REGS:
13349 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13351 case X86::VAARG_64:
13352 return EmitVAARG64WithCustomInserter(MI, BB);
13356 //===----------------------------------------------------------------------===//
13357 // X86 Optimization Hooks
13358 //===----------------------------------------------------------------------===//
13360 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13363 const SelectionDAG &DAG,
13364 unsigned Depth) const {
13365 unsigned BitWidth = KnownZero.getBitWidth();
13366 unsigned Opc = Op.getOpcode();
13367 assert((Opc >= ISD::BUILTIN_OP_END ||
13368 Opc == ISD::INTRINSIC_WO_CHAIN ||
13369 Opc == ISD::INTRINSIC_W_CHAIN ||
13370 Opc == ISD::INTRINSIC_VOID) &&
13371 "Should use MaskedValueIsZero if you don't know whether Op"
13372 " is a target node!");
13374 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13388 // These nodes' second result is a boolean.
13389 if (Op.getResNo() == 0)
13392 case X86ISD::SETCC:
13393 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13395 case ISD::INTRINSIC_WO_CHAIN: {
13396 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13397 unsigned NumLoBits = 0;
13400 case Intrinsic::x86_sse_movmsk_ps:
13401 case Intrinsic::x86_avx_movmsk_ps_256:
13402 case Intrinsic::x86_sse2_movmsk_pd:
13403 case Intrinsic::x86_avx_movmsk_pd_256:
13404 case Intrinsic::x86_mmx_pmovmskb:
13405 case Intrinsic::x86_sse2_pmovmskb_128:
13406 case Intrinsic::x86_avx2_pmovmskb: {
13407 // High bits of movmskp{s|d}, pmovmskb are known zero.
13409 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13410 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13411 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13412 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13413 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13414 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13415 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13416 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13418 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13427 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13428 unsigned Depth) const {
13429 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13430 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13431 return Op.getValueType().getScalarType().getSizeInBits();
13437 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13438 /// node is a GlobalAddress + offset.
13439 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13440 const GlobalValue* &GA,
13441 int64_t &Offset) const {
13442 if (N->getOpcode() == X86ISD::Wrapper) {
13443 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13444 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13445 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13449 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13452 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13453 /// same as extracting the high 128-bit part of 256-bit vector and then
13454 /// inserting the result into the low part of a new 256-bit vector
13455 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13456 EVT VT = SVOp->getValueType(0);
13457 unsigned NumElems = VT.getVectorNumElements();
13459 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13460 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13461 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13462 SVOp->getMaskElt(j) >= 0)
13468 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13469 /// same as extracting the low 128-bit part of 256-bit vector and then
13470 /// inserting the result into the high part of a new 256-bit vector
13471 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13472 EVT VT = SVOp->getValueType(0);
13473 unsigned NumElems = VT.getVectorNumElements();
13475 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13476 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13477 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13478 SVOp->getMaskElt(j) >= 0)
13484 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13485 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13486 TargetLowering::DAGCombinerInfo &DCI,
13487 const X86Subtarget* Subtarget) {
13488 DebugLoc dl = N->getDebugLoc();
13489 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13490 SDValue V1 = SVOp->getOperand(0);
13491 SDValue V2 = SVOp->getOperand(1);
13492 EVT VT = SVOp->getValueType(0);
13493 unsigned NumElems = VT.getVectorNumElements();
13495 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13496 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13500 // V UNDEF BUILD_VECTOR UNDEF
13502 // CONCAT_VECTOR CONCAT_VECTOR
13505 // RESULT: V + zero extended
13507 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13508 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13509 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13512 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13515 // To match the shuffle mask, the first half of the mask should
13516 // be exactly the first vector, and all the rest a splat with the
13517 // first element of the second one.
13518 for (unsigned i = 0; i != NumElems/2; ++i)
13519 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13520 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13523 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13524 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13525 if (Ld->hasNUsesOfValue(1, 0)) {
13526 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13527 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13529 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13531 Ld->getPointerInfo(),
13532 Ld->getAlignment(),
13533 false/*isVolatile*/, true/*ReadMem*/,
13534 false/*WriteMem*/);
13535 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13539 // Emit a zeroed vector and insert the desired subvector on its
13541 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13542 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13543 return DCI.CombineTo(N, InsV);
13546 //===--------------------------------------------------------------------===//
13547 // Combine some shuffles into subvector extracts and inserts:
13550 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13551 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13552 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13553 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13554 return DCI.CombineTo(N, InsV);
13557 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13558 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13559 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13560 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13561 return DCI.CombineTo(N, InsV);
13567 /// PerformShuffleCombine - Performs several different shuffle combines.
13568 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13569 TargetLowering::DAGCombinerInfo &DCI,
13570 const X86Subtarget *Subtarget) {
13571 DebugLoc dl = N->getDebugLoc();
13572 EVT VT = N->getValueType(0);
13574 // Don't create instructions with illegal types after legalize types has run.
13575 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13576 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13579 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13580 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13581 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13582 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13584 // Only handle 128 wide vector from here on.
13585 if (!VT.is128BitVector())
13588 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13589 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13590 // consecutive, non-overlapping, and in the right order.
13591 SmallVector<SDValue, 16> Elts;
13592 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13593 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13595 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13599 /// PerformTruncateCombine - Converts truncate operation to
13600 /// a sequence of vector shuffle operations.
13601 /// It is possible when we truncate 256-bit vector to 128-bit vector
13602 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13603 TargetLowering::DAGCombinerInfo &DCI,
13604 const X86Subtarget *Subtarget) {
13605 if (!DCI.isBeforeLegalizeOps())
13608 if (!Subtarget->hasAVX())
13611 EVT VT = N->getValueType(0);
13612 SDValue Op = N->getOperand(0);
13613 EVT OpVT = Op.getValueType();
13614 DebugLoc dl = N->getDebugLoc();
13616 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13618 if (Subtarget->hasAVX2()) {
13619 // AVX2: v4i64 -> v4i32
13622 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13624 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13625 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13628 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13629 DAG.getIntPtrConstant(0));
13632 // AVX: v4i64 -> v4i32
13633 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13634 DAG.getIntPtrConstant(0));
13636 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13637 DAG.getIntPtrConstant(2));
13639 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13640 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13643 static const int ShufMask1[] = {0, 2, 0, 0};
13645 SDValue Undef = DAG.getUNDEF(VT);
13646 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13647 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13650 static const int ShufMask2[] = {0, 1, 4, 5};
13652 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13655 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13657 if (Subtarget->hasAVX2()) {
13658 // AVX2: v8i32 -> v8i16
13660 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13663 SmallVector<SDValue,32> pshufbMask;
13664 for (unsigned i = 0; i < 2; ++i) {
13665 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13666 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13667 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13668 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13669 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13670 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13671 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13672 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13673 for (unsigned j = 0; j < 8; ++j)
13674 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13676 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13677 &pshufbMask[0], 32);
13678 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13680 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13682 static const int ShufMask[] = {0, 2, -1, -1};
13683 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13686 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13687 DAG.getIntPtrConstant(0));
13689 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13692 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13693 DAG.getIntPtrConstant(0));
13695 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13696 DAG.getIntPtrConstant(4));
13698 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13699 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13702 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13703 -1, -1, -1, -1, -1, -1, -1, -1};
13705 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13706 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13707 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13709 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13710 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13713 static const int ShufMask2[] = {0, 1, 4, 5};
13715 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13716 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13722 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13723 /// specific shuffle of a load can be folded into a single element load.
13724 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13725 /// shuffles have been customed lowered so we need to handle those here.
13726 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13727 TargetLowering::DAGCombinerInfo &DCI) {
13728 if (DCI.isBeforeLegalizeOps())
13731 SDValue InVec = N->getOperand(0);
13732 SDValue EltNo = N->getOperand(1);
13734 if (!isa<ConstantSDNode>(EltNo))
13737 EVT VT = InVec.getValueType();
13739 bool HasShuffleIntoBitcast = false;
13740 if (InVec.getOpcode() == ISD::BITCAST) {
13741 // Don't duplicate a load with other uses.
13742 if (!InVec.hasOneUse())
13744 EVT BCVT = InVec.getOperand(0).getValueType();
13745 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13747 InVec = InVec.getOperand(0);
13748 HasShuffleIntoBitcast = true;
13751 if (!isTargetShuffle(InVec.getOpcode()))
13754 // Don't duplicate a load with other uses.
13755 if (!InVec.hasOneUse())
13758 SmallVector<int, 16> ShuffleMask;
13760 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13764 // Select the input vector, guarding against out of range extract vector.
13765 unsigned NumElems = VT.getVectorNumElements();
13766 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13767 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13768 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13769 : InVec.getOperand(1);
13771 // If inputs to shuffle are the same for both ops, then allow 2 uses
13772 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13774 if (LdNode.getOpcode() == ISD::BITCAST) {
13775 // Don't duplicate a load with other uses.
13776 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13779 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13780 LdNode = LdNode.getOperand(0);
13783 if (!ISD::isNormalLoad(LdNode.getNode()))
13786 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13788 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13791 if (HasShuffleIntoBitcast) {
13792 // If there's a bitcast before the shuffle, check if the load type and
13793 // alignment is valid.
13794 unsigned Align = LN0->getAlignment();
13795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13796 unsigned NewAlign = TLI.getTargetData()->
13797 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13799 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13803 // All checks match so transform back to vector_shuffle so that DAG combiner
13804 // can finish the job
13805 DebugLoc dl = N->getDebugLoc();
13807 // Create shuffle node taking into account the case that its a unary shuffle
13808 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13809 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13810 InVec.getOperand(0), Shuffle,
13812 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13817 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13818 /// generation and convert it from being a bunch of shuffles and extracts
13819 /// to a simple store and scalar loads to extract the elements.
13820 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13821 TargetLowering::DAGCombinerInfo &DCI) {
13822 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13823 if (NewOp.getNode())
13826 SDValue InputVector = N->getOperand(0);
13828 // Only operate on vectors of 4 elements, where the alternative shuffling
13829 // gets to be more expensive.
13830 if (InputVector.getValueType() != MVT::v4i32)
13833 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13834 // single use which is a sign-extend or zero-extend, and all elements are
13836 SmallVector<SDNode *, 4> Uses;
13837 unsigned ExtractedElements = 0;
13838 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13839 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13840 if (UI.getUse().getResNo() != InputVector.getResNo())
13843 SDNode *Extract = *UI;
13844 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13847 if (Extract->getValueType(0) != MVT::i32)
13849 if (!Extract->hasOneUse())
13851 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13852 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13854 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13857 // Record which element was extracted.
13858 ExtractedElements |=
13859 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13861 Uses.push_back(Extract);
13864 // If not all the elements were used, this may not be worthwhile.
13865 if (ExtractedElements != 15)
13868 // Ok, we've now decided to do the transformation.
13869 DebugLoc dl = InputVector.getDebugLoc();
13871 // Store the value to a temporary stack slot.
13872 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13873 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13874 MachinePointerInfo(), false, false, 0);
13876 // Replace each use (extract) with a load of the appropriate element.
13877 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13878 UE = Uses.end(); UI != UE; ++UI) {
13879 SDNode *Extract = *UI;
13881 // cOMpute the element's address.
13882 SDValue Idx = Extract->getOperand(1);
13884 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13885 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13886 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13887 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13889 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13890 StackPtr, OffsetVal);
13892 // Load the scalar.
13893 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13894 ScalarAddr, MachinePointerInfo(),
13895 false, false, false, 0);
13897 // Replace the exact with the load.
13898 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13901 // The replacement was made in place; don't return anything.
13905 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13907 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13908 TargetLowering::DAGCombinerInfo &DCI,
13909 const X86Subtarget *Subtarget) {
13910 DebugLoc DL = N->getDebugLoc();
13911 SDValue Cond = N->getOperand(0);
13912 // Get the LHS/RHS of the select.
13913 SDValue LHS = N->getOperand(1);
13914 SDValue RHS = N->getOperand(2);
13915 EVT VT = LHS.getValueType();
13917 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13918 // instructions match the semantics of the common C idiom x<y?x:y but not
13919 // x<=y?x:y, because of how they handle negative zero (which can be
13920 // ignored in unsafe-math mode).
13921 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13922 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13923 (Subtarget->hasSSE2() ||
13924 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13925 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13927 unsigned Opcode = 0;
13928 // Check for x CC y ? x : y.
13929 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13930 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13934 // Converting this to a min would handle NaNs incorrectly, and swapping
13935 // the operands would cause it to handle comparisons between positive
13936 // and negative zero incorrectly.
13937 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13938 if (!DAG.getTarget().Options.UnsafeFPMath &&
13939 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13941 std::swap(LHS, RHS);
13943 Opcode = X86ISD::FMIN;
13946 // Converting this to a min would handle comparisons between positive
13947 // and negative zero incorrectly.
13948 if (!DAG.getTarget().Options.UnsafeFPMath &&
13949 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13951 Opcode = X86ISD::FMIN;
13954 // Converting this to a min would handle both negative zeros and NaNs
13955 // incorrectly, but we can swap the operands to fix both.
13956 std::swap(LHS, RHS);
13960 Opcode = X86ISD::FMIN;
13964 // Converting this to a max would handle comparisons between positive
13965 // and negative zero incorrectly.
13966 if (!DAG.getTarget().Options.UnsafeFPMath &&
13967 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13969 Opcode = X86ISD::FMAX;
13972 // Converting this to a max would handle NaNs incorrectly, and swapping
13973 // the operands would cause it to handle comparisons between positive
13974 // and negative zero incorrectly.
13975 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13976 if (!DAG.getTarget().Options.UnsafeFPMath &&
13977 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13979 std::swap(LHS, RHS);
13981 Opcode = X86ISD::FMAX;
13984 // Converting this to a max would handle both negative zeros and NaNs
13985 // incorrectly, but we can swap the operands to fix both.
13986 std::swap(LHS, RHS);
13990 Opcode = X86ISD::FMAX;
13993 // Check for x CC y ? y : x -- a min/max with reversed arms.
13994 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13995 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13999 // Converting this to a min would handle comparisons between positive
14000 // and negative zero incorrectly, and swapping the operands would
14001 // cause it to handle NaNs incorrectly.
14002 if (!DAG.getTarget().Options.UnsafeFPMath &&
14003 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14004 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14006 std::swap(LHS, RHS);
14008 Opcode = X86ISD::FMIN;
14011 // Converting this to a min would handle NaNs incorrectly.
14012 if (!DAG.getTarget().Options.UnsafeFPMath &&
14013 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14015 Opcode = X86ISD::FMIN;
14018 // Converting this to a min would handle both negative zeros and NaNs
14019 // incorrectly, but we can swap the operands to fix both.
14020 std::swap(LHS, RHS);
14024 Opcode = X86ISD::FMIN;
14028 // Converting this to a max would handle NaNs incorrectly.
14029 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14031 Opcode = X86ISD::FMAX;
14034 // Converting this to a max would handle comparisons between positive
14035 // and negative zero incorrectly, and swapping the operands would
14036 // cause it to handle NaNs incorrectly.
14037 if (!DAG.getTarget().Options.UnsafeFPMath &&
14038 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14039 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14041 std::swap(LHS, RHS);
14043 Opcode = X86ISD::FMAX;
14046 // Converting this to a max would handle both negative zeros and NaNs
14047 // incorrectly, but we can swap the operands to fix both.
14048 std::swap(LHS, RHS);
14052 Opcode = X86ISD::FMAX;
14058 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14061 // If this is a select between two integer constants, try to do some
14063 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14064 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14065 // Don't do this for crazy integer types.
14066 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14067 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14068 // so that TrueC (the true value) is larger than FalseC.
14069 bool NeedsCondInvert = false;
14071 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14072 // Efficiently invertible.
14073 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14074 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14075 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14076 NeedsCondInvert = true;
14077 std::swap(TrueC, FalseC);
14080 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14081 if (FalseC->getAPIntValue() == 0 &&
14082 TrueC->getAPIntValue().isPowerOf2()) {
14083 if (NeedsCondInvert) // Invert the condition if needed.
14084 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14085 DAG.getConstant(1, Cond.getValueType()));
14087 // Zero extend the condition if needed.
14088 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14090 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14091 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14092 DAG.getConstant(ShAmt, MVT::i8));
14095 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14096 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14097 if (NeedsCondInvert) // Invert the condition if needed.
14098 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14099 DAG.getConstant(1, Cond.getValueType()));
14101 // Zero extend the condition if needed.
14102 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14103 FalseC->getValueType(0), Cond);
14104 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14105 SDValue(FalseC, 0));
14108 // Optimize cases that will turn into an LEA instruction. This requires
14109 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14110 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14111 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14112 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14114 bool isFastMultiplier = false;
14116 switch ((unsigned char)Diff) {
14118 case 1: // result = add base, cond
14119 case 2: // result = lea base( , cond*2)
14120 case 3: // result = lea base(cond, cond*2)
14121 case 4: // result = lea base( , cond*4)
14122 case 5: // result = lea base(cond, cond*4)
14123 case 8: // result = lea base( , cond*8)
14124 case 9: // result = lea base(cond, cond*8)
14125 isFastMultiplier = true;
14130 if (isFastMultiplier) {
14131 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14132 if (NeedsCondInvert) // Invert the condition if needed.
14133 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14134 DAG.getConstant(1, Cond.getValueType()));
14136 // Zero extend the condition if needed.
14137 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14139 // Scale the condition by the difference.
14141 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14142 DAG.getConstant(Diff, Cond.getValueType()));
14144 // Add the base if non-zero.
14145 if (FalseC->getAPIntValue() != 0)
14146 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14147 SDValue(FalseC, 0));
14154 // Canonicalize max and min:
14155 // (x > y) ? x : y -> (x >= y) ? x : y
14156 // (x < y) ? x : y -> (x <= y) ? x : y
14157 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14158 // the need for an extra compare
14159 // against zero. e.g.
14160 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14162 // testl %edi, %edi
14164 // cmovgl %edi, %eax
14168 // cmovsl %eax, %edi
14169 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14170 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14171 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14172 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14177 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14178 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14179 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14180 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14185 // If we know that this node is legal then we know that it is going to be
14186 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14187 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14188 // to simplify previous instructions.
14189 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14190 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14191 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14192 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14194 // Don't optimize vector selects that map to mask-registers.
14198 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14199 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14201 APInt KnownZero, KnownOne;
14202 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14203 DCI.isBeforeLegalizeOps());
14204 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14205 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14206 DCI.CommitTargetLoweringOpt(TLO);
14212 // Check whether a boolean test is testing a boolean value generated by
14213 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14216 // Simplify the following patterns:
14217 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14218 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14219 // to (Op EFLAGS Cond)
14221 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14222 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14223 // to (Op EFLAGS !Cond)
14225 // where Op could be BRCOND or CMOV.
14227 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14228 // Quit if not CMP and SUB with its value result used.
14229 if (Cmp.getOpcode() != X86ISD::CMP &&
14230 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14233 // Quit if not used as a boolean value.
14234 if (CC != X86::COND_E && CC != X86::COND_NE)
14237 // Check CMP operands. One of them should be 0 or 1 and the other should be
14238 // an SetCC or extended from it.
14239 SDValue Op1 = Cmp.getOperand(0);
14240 SDValue Op2 = Cmp.getOperand(1);
14243 const ConstantSDNode* C = 0;
14244 bool needOppositeCond = (CC == X86::COND_E);
14246 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14248 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14250 else // Quit if all operands are not constants.
14253 if (C->getZExtValue() == 1)
14254 needOppositeCond = !needOppositeCond;
14255 else if (C->getZExtValue() != 0)
14256 // Quit if the constant is neither 0 or 1.
14259 // Skip 'zext' node.
14260 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14261 SetCC = SetCC.getOperand(0);
14263 switch (SetCC.getOpcode()) {
14264 case X86ISD::SETCC:
14265 // Set the condition code or opposite one if necessary.
14266 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14267 if (needOppositeCond)
14268 CC = X86::GetOppositeBranchCondition(CC);
14269 return SetCC.getOperand(1);
14270 case X86ISD::CMOV: {
14271 // Check whether false/true value has canonical one, i.e. 0 or 1.
14272 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14273 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14274 // Quit if true value is not a constant.
14277 // Quit if false value is not a constant.
14279 // A special case for rdrand, where 0 is set if false cond is found.
14280 SDValue Op = SetCC.getOperand(0);
14281 if (Op.getOpcode() != X86ISD::RDRAND)
14284 // Quit if false value is not the constant 0 or 1.
14285 bool FValIsFalse = true;
14286 if (FVal && FVal->getZExtValue() != 0) {
14287 if (FVal->getZExtValue() != 1)
14289 // If FVal is 1, opposite cond is needed.
14290 needOppositeCond = !needOppositeCond;
14291 FValIsFalse = false;
14293 // Quit if TVal is not the constant opposite of FVal.
14294 if (FValIsFalse && TVal->getZExtValue() != 1)
14296 if (!FValIsFalse && TVal->getZExtValue() != 0)
14298 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14299 if (needOppositeCond)
14300 CC = X86::GetOppositeBranchCondition(CC);
14301 return SetCC.getOperand(3);
14308 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14309 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14310 TargetLowering::DAGCombinerInfo &DCI,
14311 const X86Subtarget *Subtarget) {
14312 DebugLoc DL = N->getDebugLoc();
14314 // If the flag operand isn't dead, don't touch this CMOV.
14315 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14318 SDValue FalseOp = N->getOperand(0);
14319 SDValue TrueOp = N->getOperand(1);
14320 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14321 SDValue Cond = N->getOperand(3);
14323 if (CC == X86::COND_E || CC == X86::COND_NE) {
14324 switch (Cond.getOpcode()) {
14328 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14329 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14330 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14336 Flags = checkBoolTestSetCCCombine(Cond, CC);
14337 if (Flags.getNode() &&
14338 // Extra check as FCMOV only supports a subset of X86 cond.
14339 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14340 SDValue Ops[] = { FalseOp, TrueOp,
14341 DAG.getConstant(CC, MVT::i8), Flags };
14342 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14343 Ops, array_lengthof(Ops));
14346 // If this is a select between two integer constants, try to do some
14347 // optimizations. Note that the operands are ordered the opposite of SELECT
14349 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14350 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14351 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14352 // larger than FalseC (the false value).
14353 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14354 CC = X86::GetOppositeBranchCondition(CC);
14355 std::swap(TrueC, FalseC);
14358 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14359 // This is efficient for any integer data type (including i8/i16) and
14361 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14362 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14363 DAG.getConstant(CC, MVT::i8), Cond);
14365 // Zero extend the condition if needed.
14366 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14368 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14369 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14370 DAG.getConstant(ShAmt, MVT::i8));
14371 if (N->getNumValues() == 2) // Dead flag value?
14372 return DCI.CombineTo(N, Cond, SDValue());
14376 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14377 // for any integer data type, including i8/i16.
14378 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14379 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14380 DAG.getConstant(CC, MVT::i8), Cond);
14382 // Zero extend the condition if needed.
14383 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14384 FalseC->getValueType(0), Cond);
14385 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14386 SDValue(FalseC, 0));
14388 if (N->getNumValues() == 2) // Dead flag value?
14389 return DCI.CombineTo(N, Cond, SDValue());
14393 // Optimize cases that will turn into an LEA instruction. This requires
14394 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14395 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14396 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14397 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14399 bool isFastMultiplier = false;
14401 switch ((unsigned char)Diff) {
14403 case 1: // result = add base, cond
14404 case 2: // result = lea base( , cond*2)
14405 case 3: // result = lea base(cond, cond*2)
14406 case 4: // result = lea base( , cond*4)
14407 case 5: // result = lea base(cond, cond*4)
14408 case 8: // result = lea base( , cond*8)
14409 case 9: // result = lea base(cond, cond*8)
14410 isFastMultiplier = true;
14415 if (isFastMultiplier) {
14416 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14417 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14418 DAG.getConstant(CC, MVT::i8), Cond);
14419 // Zero extend the condition if needed.
14420 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14422 // Scale the condition by the difference.
14424 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14425 DAG.getConstant(Diff, Cond.getValueType()));
14427 // Add the base if non-zero.
14428 if (FalseC->getAPIntValue() != 0)
14429 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14430 SDValue(FalseC, 0));
14431 if (N->getNumValues() == 2) // Dead flag value?
14432 return DCI.CombineTo(N, Cond, SDValue());
14442 /// PerformMulCombine - Optimize a single multiply with constant into two
14443 /// in order to implement it with two cheaper instructions, e.g.
14444 /// LEA + SHL, LEA + LEA.
14445 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14446 TargetLowering::DAGCombinerInfo &DCI) {
14447 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14450 EVT VT = N->getValueType(0);
14451 if (VT != MVT::i64)
14454 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14457 uint64_t MulAmt = C->getZExtValue();
14458 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14461 uint64_t MulAmt1 = 0;
14462 uint64_t MulAmt2 = 0;
14463 if ((MulAmt % 9) == 0) {
14465 MulAmt2 = MulAmt / 9;
14466 } else if ((MulAmt % 5) == 0) {
14468 MulAmt2 = MulAmt / 5;
14469 } else if ((MulAmt % 3) == 0) {
14471 MulAmt2 = MulAmt / 3;
14474 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14475 DebugLoc DL = N->getDebugLoc();
14477 if (isPowerOf2_64(MulAmt2) &&
14478 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14479 // If second multiplifer is pow2, issue it first. We want the multiply by
14480 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14482 std::swap(MulAmt1, MulAmt2);
14485 if (isPowerOf2_64(MulAmt1))
14486 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14487 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14489 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14490 DAG.getConstant(MulAmt1, VT));
14492 if (isPowerOf2_64(MulAmt2))
14493 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14494 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14496 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14497 DAG.getConstant(MulAmt2, VT));
14499 // Do not add new nodes to DAG combiner worklist.
14500 DCI.CombineTo(N, NewMul, false);
14505 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14506 SDValue N0 = N->getOperand(0);
14507 SDValue N1 = N->getOperand(1);
14508 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14509 EVT VT = N0.getValueType();
14511 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14512 // since the result of setcc_c is all zero's or all ones.
14513 if (VT.isInteger() && !VT.isVector() &&
14514 N1C && N0.getOpcode() == ISD::AND &&
14515 N0.getOperand(1).getOpcode() == ISD::Constant) {
14516 SDValue N00 = N0.getOperand(0);
14517 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14518 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14519 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14520 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14521 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14522 APInt ShAmt = N1C->getAPIntValue();
14523 Mask = Mask.shl(ShAmt);
14525 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14526 N00, DAG.getConstant(Mask, VT));
14531 // Hardware support for vector shifts is sparse which makes us scalarize the
14532 // vector operations in many cases. Also, on sandybridge ADD is faster than
14534 // (shl V, 1) -> add V,V
14535 if (isSplatVector(N1.getNode())) {
14536 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14537 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14538 // We shift all of the values by one. In many cases we do not have
14539 // hardware support for this operation. This is better expressed as an ADD
14541 if (N1C && (1 == N1C->getZExtValue())) {
14542 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14549 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14551 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14552 TargetLowering::DAGCombinerInfo &DCI,
14553 const X86Subtarget *Subtarget) {
14554 EVT VT = N->getValueType(0);
14555 if (N->getOpcode() == ISD::SHL) {
14556 SDValue V = PerformSHLCombine(N, DAG);
14557 if (V.getNode()) return V;
14560 // On X86 with SSE2 support, we can transform this to a vector shift if
14561 // all elements are shifted by the same amount. We can't do this in legalize
14562 // because the a constant vector is typically transformed to a constant pool
14563 // so we have no knowledge of the shift amount.
14564 if (!Subtarget->hasSSE2())
14567 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14568 (!Subtarget->hasAVX2() ||
14569 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14572 SDValue ShAmtOp = N->getOperand(1);
14573 EVT EltVT = VT.getVectorElementType();
14574 DebugLoc DL = N->getDebugLoc();
14575 SDValue BaseShAmt = SDValue();
14576 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14577 unsigned NumElts = VT.getVectorNumElements();
14579 for (; i != NumElts; ++i) {
14580 SDValue Arg = ShAmtOp.getOperand(i);
14581 if (Arg.getOpcode() == ISD::UNDEF) continue;
14585 // Handle the case where the build_vector is all undef
14586 // FIXME: Should DAG allow this?
14590 for (; i != NumElts; ++i) {
14591 SDValue Arg = ShAmtOp.getOperand(i);
14592 if (Arg.getOpcode() == ISD::UNDEF) continue;
14593 if (Arg != BaseShAmt) {
14597 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14598 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14599 SDValue InVec = ShAmtOp.getOperand(0);
14600 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14601 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14603 for (; i != NumElts; ++i) {
14604 SDValue Arg = InVec.getOperand(i);
14605 if (Arg.getOpcode() == ISD::UNDEF) continue;
14609 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14610 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14611 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14612 if (C->getZExtValue() == SplatIdx)
14613 BaseShAmt = InVec.getOperand(1);
14616 if (BaseShAmt.getNode() == 0) {
14617 // Don't create instructions with illegal types after legalize
14619 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14620 !DCI.isBeforeLegalize())
14623 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14624 DAG.getIntPtrConstant(0));
14629 // The shift amount is an i32.
14630 if (EltVT.bitsGT(MVT::i32))
14631 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14632 else if (EltVT.bitsLT(MVT::i32))
14633 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14635 // The shift amount is identical so we can do a vector shift.
14636 SDValue ValOp = N->getOperand(0);
14637 switch (N->getOpcode()) {
14639 llvm_unreachable("Unknown shift opcode!");
14641 switch (VT.getSimpleVT().SimpleTy) {
14642 default: return SDValue();
14649 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14652 switch (VT.getSimpleVT().SimpleTy) {
14653 default: return SDValue();
14658 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14661 switch (VT.getSimpleVT().SimpleTy) {
14662 default: return SDValue();
14669 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14675 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14676 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14677 // and friends. Likewise for OR -> CMPNEQSS.
14678 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14679 TargetLowering::DAGCombinerInfo &DCI,
14680 const X86Subtarget *Subtarget) {
14683 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14684 // we're requiring SSE2 for both.
14685 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14686 SDValue N0 = N->getOperand(0);
14687 SDValue N1 = N->getOperand(1);
14688 SDValue CMP0 = N0->getOperand(1);
14689 SDValue CMP1 = N1->getOperand(1);
14690 DebugLoc DL = N->getDebugLoc();
14692 // The SETCCs should both refer to the same CMP.
14693 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14696 SDValue CMP00 = CMP0->getOperand(0);
14697 SDValue CMP01 = CMP0->getOperand(1);
14698 EVT VT = CMP00.getValueType();
14700 if (VT == MVT::f32 || VT == MVT::f64) {
14701 bool ExpectingFlags = false;
14702 // Check for any users that want flags:
14703 for (SDNode::use_iterator UI = N->use_begin(),
14705 !ExpectingFlags && UI != UE; ++UI)
14706 switch (UI->getOpcode()) {
14711 ExpectingFlags = true;
14713 case ISD::CopyToReg:
14714 case ISD::SIGN_EXTEND:
14715 case ISD::ZERO_EXTEND:
14716 case ISD::ANY_EXTEND:
14720 if (!ExpectingFlags) {
14721 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14722 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14724 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14725 X86::CondCode tmp = cc0;
14730 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14731 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14732 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14733 X86ISD::NodeType NTOperator = is64BitFP ?
14734 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14735 // FIXME: need symbolic constants for these magic numbers.
14736 // See X86ATTInstPrinter.cpp:printSSECC().
14737 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14738 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14739 DAG.getConstant(x86cc, MVT::i8));
14740 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14742 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14743 DAG.getConstant(1, MVT::i32));
14744 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14745 return OneBitOfTruth;
14753 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14754 /// so it can be folded inside ANDNP.
14755 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14756 EVT VT = N->getValueType(0);
14758 // Match direct AllOnes for 128 and 256-bit vectors
14759 if (ISD::isBuildVectorAllOnes(N))
14762 // Look through a bit convert.
14763 if (N->getOpcode() == ISD::BITCAST)
14764 N = N->getOperand(0).getNode();
14766 // Sometimes the operand may come from a insert_subvector building a 256-bit
14768 if (VT.is256BitVector() &&
14769 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14770 SDValue V1 = N->getOperand(0);
14771 SDValue V2 = N->getOperand(1);
14773 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14774 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14775 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14776 ISD::isBuildVectorAllOnes(V2.getNode()))
14783 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14784 TargetLowering::DAGCombinerInfo &DCI,
14785 const X86Subtarget *Subtarget) {
14786 if (DCI.isBeforeLegalizeOps())
14789 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14793 EVT VT = N->getValueType(0);
14795 // Create ANDN, BLSI, and BLSR instructions
14796 // BLSI is X & (-X)
14797 // BLSR is X & (X-1)
14798 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14799 SDValue N0 = N->getOperand(0);
14800 SDValue N1 = N->getOperand(1);
14801 DebugLoc DL = N->getDebugLoc();
14803 // Check LHS for not
14804 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14805 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14806 // Check RHS for not
14807 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14808 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14810 // Check LHS for neg
14811 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14812 isZero(N0.getOperand(0)))
14813 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14815 // Check RHS for neg
14816 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14817 isZero(N1.getOperand(0)))
14818 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14820 // Check LHS for X-1
14821 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14822 isAllOnes(N0.getOperand(1)))
14823 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14825 // Check RHS for X-1
14826 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14827 isAllOnes(N1.getOperand(1)))
14828 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14833 // Want to form ANDNP nodes:
14834 // 1) In the hopes of then easily combining them with OR and AND nodes
14835 // to form PBLEND/PSIGN.
14836 // 2) To match ANDN packed intrinsics
14837 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14840 SDValue N0 = N->getOperand(0);
14841 SDValue N1 = N->getOperand(1);
14842 DebugLoc DL = N->getDebugLoc();
14844 // Check LHS for vnot
14845 if (N0.getOpcode() == ISD::XOR &&
14846 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14847 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14848 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14850 // Check RHS for vnot
14851 if (N1.getOpcode() == ISD::XOR &&
14852 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14853 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14854 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14859 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14860 TargetLowering::DAGCombinerInfo &DCI,
14861 const X86Subtarget *Subtarget) {
14862 if (DCI.isBeforeLegalizeOps())
14865 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14869 EVT VT = N->getValueType(0);
14871 SDValue N0 = N->getOperand(0);
14872 SDValue N1 = N->getOperand(1);
14874 // look for psign/blend
14875 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14876 if (!Subtarget->hasSSSE3() ||
14877 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14880 // Canonicalize pandn to RHS
14881 if (N0.getOpcode() == X86ISD::ANDNP)
14883 // or (and (m, y), (pandn m, x))
14884 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14885 SDValue Mask = N1.getOperand(0);
14886 SDValue X = N1.getOperand(1);
14888 if (N0.getOperand(0) == Mask)
14889 Y = N0.getOperand(1);
14890 if (N0.getOperand(1) == Mask)
14891 Y = N0.getOperand(0);
14893 // Check to see if the mask appeared in both the AND and ANDNP and
14897 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14898 // Look through mask bitcast.
14899 if (Mask.getOpcode() == ISD::BITCAST)
14900 Mask = Mask.getOperand(0);
14901 if (X.getOpcode() == ISD::BITCAST)
14902 X = X.getOperand(0);
14903 if (Y.getOpcode() == ISD::BITCAST)
14904 Y = Y.getOperand(0);
14906 EVT MaskVT = Mask.getValueType();
14908 // Validate that the Mask operand is a vector sra node.
14909 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14910 // there is no psrai.b
14911 if (Mask.getOpcode() != X86ISD::VSRAI)
14914 // Check that the SRA is all signbits.
14915 SDValue SraC = Mask.getOperand(1);
14916 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14917 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14918 if ((SraAmt + 1) != EltBits)
14921 DebugLoc DL = N->getDebugLoc();
14923 // Now we know we at least have a plendvb with the mask val. See if
14924 // we can form a psignb/w/d.
14925 // psign = x.type == y.type == mask.type && y = sub(0, x);
14926 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14927 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14928 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14929 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14930 "Unsupported VT for PSIGN");
14931 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14932 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14934 // PBLENDVB only available on SSE 4.1
14935 if (!Subtarget->hasSSE41())
14938 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14940 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14941 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14942 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14943 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14944 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14948 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14951 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14952 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14954 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14956 if (!N0.hasOneUse() || !N1.hasOneUse())
14959 SDValue ShAmt0 = N0.getOperand(1);
14960 if (ShAmt0.getValueType() != MVT::i8)
14962 SDValue ShAmt1 = N1.getOperand(1);
14963 if (ShAmt1.getValueType() != MVT::i8)
14965 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14966 ShAmt0 = ShAmt0.getOperand(0);
14967 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14968 ShAmt1 = ShAmt1.getOperand(0);
14970 DebugLoc DL = N->getDebugLoc();
14971 unsigned Opc = X86ISD::SHLD;
14972 SDValue Op0 = N0.getOperand(0);
14973 SDValue Op1 = N1.getOperand(0);
14974 if (ShAmt0.getOpcode() == ISD::SUB) {
14975 Opc = X86ISD::SHRD;
14976 std::swap(Op0, Op1);
14977 std::swap(ShAmt0, ShAmt1);
14980 unsigned Bits = VT.getSizeInBits();
14981 if (ShAmt1.getOpcode() == ISD::SUB) {
14982 SDValue Sum = ShAmt1.getOperand(0);
14983 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14984 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14985 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14986 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14987 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14988 return DAG.getNode(Opc, DL, VT,
14990 DAG.getNode(ISD::TRUNCATE, DL,
14993 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14994 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14996 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14997 return DAG.getNode(Opc, DL, VT,
14998 N0.getOperand(0), N1.getOperand(0),
14999 DAG.getNode(ISD::TRUNCATE, DL,
15006 // Generate NEG and CMOV for integer abs.
15007 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15008 EVT VT = N->getValueType(0);
15010 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15011 // 8-bit integer abs to NEG and CMOV.
15012 if (VT.isInteger() && VT.getSizeInBits() == 8)
15015 SDValue N0 = N->getOperand(0);
15016 SDValue N1 = N->getOperand(1);
15017 DebugLoc DL = N->getDebugLoc();
15019 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15020 // and change it to SUB and CMOV.
15021 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15022 N0.getOpcode() == ISD::ADD &&
15023 N0.getOperand(1) == N1 &&
15024 N1.getOpcode() == ISD::SRA &&
15025 N1.getOperand(0) == N0.getOperand(0))
15026 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15027 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15028 // Generate SUB & CMOV.
15029 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15030 DAG.getConstant(0, VT), N0.getOperand(0));
15032 SDValue Ops[] = { N0.getOperand(0), Neg,
15033 DAG.getConstant(X86::COND_GE, MVT::i8),
15034 SDValue(Neg.getNode(), 1) };
15035 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15036 Ops, array_lengthof(Ops));
15041 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15042 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15043 TargetLowering::DAGCombinerInfo &DCI,
15044 const X86Subtarget *Subtarget) {
15045 if (DCI.isBeforeLegalizeOps())
15048 if (Subtarget->hasCMov()) {
15049 SDValue RV = performIntegerAbsCombine(N, DAG);
15054 // Try forming BMI if it is available.
15055 if (!Subtarget->hasBMI())
15058 EVT VT = N->getValueType(0);
15060 if (VT != MVT::i32 && VT != MVT::i64)
15063 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15065 // Create BLSMSK instructions by finding X ^ (X-1)
15066 SDValue N0 = N->getOperand(0);
15067 SDValue N1 = N->getOperand(1);
15068 DebugLoc DL = N->getDebugLoc();
15070 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15071 isAllOnes(N0.getOperand(1)))
15072 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15074 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15075 isAllOnes(N1.getOperand(1)))
15076 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15081 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15082 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15083 TargetLowering::DAGCombinerInfo &DCI,
15084 const X86Subtarget *Subtarget) {
15085 LoadSDNode *Ld = cast<LoadSDNode>(N);
15086 EVT RegVT = Ld->getValueType(0);
15087 EVT MemVT = Ld->getMemoryVT();
15088 DebugLoc dl = Ld->getDebugLoc();
15089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15091 ISD::LoadExtType Ext = Ld->getExtensionType();
15093 // If this is a vector EXT Load then attempt to optimize it using a
15094 // shuffle. We need SSE4 for the shuffles.
15095 // TODO: It is possible to support ZExt by zeroing the undef values
15096 // during the shuffle phase or after the shuffle.
15097 if (RegVT.isVector() && RegVT.isInteger() &&
15098 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15099 assert(MemVT != RegVT && "Cannot extend to the same type");
15100 assert(MemVT.isVector() && "Must load a vector from memory");
15102 unsigned NumElems = RegVT.getVectorNumElements();
15103 unsigned RegSz = RegVT.getSizeInBits();
15104 unsigned MemSz = MemVT.getSizeInBits();
15105 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15107 // All sizes must be a power of two.
15108 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15111 // Attempt to load the original value using scalar loads.
15112 // Find the largest scalar type that divides the total loaded size.
15113 MVT SclrLoadTy = MVT::i8;
15114 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15115 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15116 MVT Tp = (MVT::SimpleValueType)tp;
15117 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15122 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15123 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15125 SclrLoadTy = MVT::f64;
15127 // Calculate the number of scalar loads that we need to perform
15128 // in order to load our vector from memory.
15129 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15131 // Represent our vector as a sequence of elements which are the
15132 // largest scalar that we can load.
15133 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15134 RegSz/SclrLoadTy.getSizeInBits());
15136 // Represent the data using the same element type that is stored in
15137 // memory. In practice, we ''widen'' MemVT.
15138 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15139 RegSz/MemVT.getScalarType().getSizeInBits());
15141 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15142 "Invalid vector type");
15144 // We can't shuffle using an illegal type.
15145 if (!TLI.isTypeLegal(WideVecVT))
15148 SmallVector<SDValue, 8> Chains;
15149 SDValue Ptr = Ld->getBasePtr();
15150 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15151 TLI.getPointerTy());
15152 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15154 for (unsigned i = 0; i < NumLoads; ++i) {
15155 // Perform a single load.
15156 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15157 Ptr, Ld->getPointerInfo(),
15158 Ld->isVolatile(), Ld->isNonTemporal(),
15159 Ld->isInvariant(), Ld->getAlignment());
15160 Chains.push_back(ScalarLoad.getValue(1));
15161 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15162 // another round of DAGCombining.
15164 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15166 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15167 ScalarLoad, DAG.getIntPtrConstant(i));
15169 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15172 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15175 // Bitcast the loaded value to a vector of the original element type, in
15176 // the size of the target vector type.
15177 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15178 unsigned SizeRatio = RegSz/MemSz;
15180 // Redistribute the loaded elements into the different locations.
15181 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15182 for (unsigned i = 0; i != NumElems; ++i)
15183 ShuffleVec[i*SizeRatio] = i;
15185 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15186 DAG.getUNDEF(WideVecVT),
15189 // Bitcast to the requested type.
15190 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15191 // Replace the original load with the new sequence
15192 // and return the new chain.
15193 return DCI.CombineTo(N, Shuff, TF, true);
15199 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15200 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15201 const X86Subtarget *Subtarget) {
15202 StoreSDNode *St = cast<StoreSDNode>(N);
15203 EVT VT = St->getValue().getValueType();
15204 EVT StVT = St->getMemoryVT();
15205 DebugLoc dl = St->getDebugLoc();
15206 SDValue StoredVal = St->getOperand(1);
15207 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15209 // If we are saving a concatenation of two XMM registers, perform two stores.
15210 // On Sandy Bridge, 256-bit memory operations are executed by two
15211 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15212 // memory operation.
15213 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15214 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15215 StoredVal.getNumOperands() == 2) {
15216 SDValue Value0 = StoredVal.getOperand(0);
15217 SDValue Value1 = StoredVal.getOperand(1);
15219 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15220 SDValue Ptr0 = St->getBasePtr();
15221 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15223 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15224 St->getPointerInfo(), St->isVolatile(),
15225 St->isNonTemporal(), St->getAlignment());
15226 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15227 St->getPointerInfo(), St->isVolatile(),
15228 St->isNonTemporal(), St->getAlignment());
15229 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15232 // Optimize trunc store (of multiple scalars) to shuffle and store.
15233 // First, pack all of the elements in one place. Next, store to memory
15234 // in fewer chunks.
15235 if (St->isTruncatingStore() && VT.isVector()) {
15236 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15237 unsigned NumElems = VT.getVectorNumElements();
15238 assert(StVT != VT && "Cannot truncate to the same type");
15239 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15240 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15242 // From, To sizes and ElemCount must be pow of two
15243 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15244 // We are going to use the original vector elt for storing.
15245 // Accumulated smaller vector elements must be a multiple of the store size.
15246 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15248 unsigned SizeRatio = FromSz / ToSz;
15250 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15252 // Create a type on which we perform the shuffle
15253 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15254 StVT.getScalarType(), NumElems*SizeRatio);
15256 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15258 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15259 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15260 for (unsigned i = 0; i != NumElems; ++i)
15261 ShuffleVec[i] = i * SizeRatio;
15263 // Can't shuffle using an illegal type.
15264 if (!TLI.isTypeLegal(WideVecVT))
15267 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15268 DAG.getUNDEF(WideVecVT),
15270 // At this point all of the data is stored at the bottom of the
15271 // register. We now need to save it to mem.
15273 // Find the largest store unit
15274 MVT StoreType = MVT::i8;
15275 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15276 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15277 MVT Tp = (MVT::SimpleValueType)tp;
15278 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15282 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15283 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15284 (64 <= NumElems * ToSz))
15285 StoreType = MVT::f64;
15287 // Bitcast the original vector into a vector of store-size units
15288 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15289 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15290 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15291 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15292 SmallVector<SDValue, 8> Chains;
15293 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15294 TLI.getPointerTy());
15295 SDValue Ptr = St->getBasePtr();
15297 // Perform one or more big stores into memory.
15298 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15299 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15300 StoreType, ShuffWide,
15301 DAG.getIntPtrConstant(i));
15302 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15303 St->getPointerInfo(), St->isVolatile(),
15304 St->isNonTemporal(), St->getAlignment());
15305 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15306 Chains.push_back(Ch);
15309 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15314 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15315 // the FP state in cases where an emms may be missing.
15316 // A preferable solution to the general problem is to figure out the right
15317 // places to insert EMMS. This qualifies as a quick hack.
15319 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15320 if (VT.getSizeInBits() != 64)
15323 const Function *F = DAG.getMachineFunction().getFunction();
15324 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15325 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15326 && Subtarget->hasSSE2();
15327 if ((VT.isVector() ||
15328 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15329 isa<LoadSDNode>(St->getValue()) &&
15330 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15331 St->getChain().hasOneUse() && !St->isVolatile()) {
15332 SDNode* LdVal = St->getValue().getNode();
15333 LoadSDNode *Ld = 0;
15334 int TokenFactorIndex = -1;
15335 SmallVector<SDValue, 8> Ops;
15336 SDNode* ChainVal = St->getChain().getNode();
15337 // Must be a store of a load. We currently handle two cases: the load
15338 // is a direct child, and it's under an intervening TokenFactor. It is
15339 // possible to dig deeper under nested TokenFactors.
15340 if (ChainVal == LdVal)
15341 Ld = cast<LoadSDNode>(St->getChain());
15342 else if (St->getValue().hasOneUse() &&
15343 ChainVal->getOpcode() == ISD::TokenFactor) {
15344 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15345 if (ChainVal->getOperand(i).getNode() == LdVal) {
15346 TokenFactorIndex = i;
15347 Ld = cast<LoadSDNode>(St->getValue());
15349 Ops.push_back(ChainVal->getOperand(i));
15353 if (!Ld || !ISD::isNormalLoad(Ld))
15356 // If this is not the MMX case, i.e. we are just turning i64 load/store
15357 // into f64 load/store, avoid the transformation if there are multiple
15358 // uses of the loaded value.
15359 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15362 DebugLoc LdDL = Ld->getDebugLoc();
15363 DebugLoc StDL = N->getDebugLoc();
15364 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15365 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15367 if (Subtarget->is64Bit() || F64IsLegal) {
15368 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15369 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15370 Ld->getPointerInfo(), Ld->isVolatile(),
15371 Ld->isNonTemporal(), Ld->isInvariant(),
15372 Ld->getAlignment());
15373 SDValue NewChain = NewLd.getValue(1);
15374 if (TokenFactorIndex != -1) {
15375 Ops.push_back(NewChain);
15376 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15379 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15380 St->getPointerInfo(),
15381 St->isVolatile(), St->isNonTemporal(),
15382 St->getAlignment());
15385 // Otherwise, lower to two pairs of 32-bit loads / stores.
15386 SDValue LoAddr = Ld->getBasePtr();
15387 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15388 DAG.getConstant(4, MVT::i32));
15390 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15391 Ld->getPointerInfo(),
15392 Ld->isVolatile(), Ld->isNonTemporal(),
15393 Ld->isInvariant(), Ld->getAlignment());
15394 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15395 Ld->getPointerInfo().getWithOffset(4),
15396 Ld->isVolatile(), Ld->isNonTemporal(),
15398 MinAlign(Ld->getAlignment(), 4));
15400 SDValue NewChain = LoLd.getValue(1);
15401 if (TokenFactorIndex != -1) {
15402 Ops.push_back(LoLd);
15403 Ops.push_back(HiLd);
15404 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15408 LoAddr = St->getBasePtr();
15409 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15410 DAG.getConstant(4, MVT::i32));
15412 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15413 St->getPointerInfo(),
15414 St->isVolatile(), St->isNonTemporal(),
15415 St->getAlignment());
15416 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15417 St->getPointerInfo().getWithOffset(4),
15419 St->isNonTemporal(),
15420 MinAlign(St->getAlignment(), 4));
15421 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15426 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15427 /// and return the operands for the horizontal operation in LHS and RHS. A
15428 /// horizontal operation performs the binary operation on successive elements
15429 /// of its first operand, then on successive elements of its second operand,
15430 /// returning the resulting values in a vector. For example, if
15431 /// A = < float a0, float a1, float a2, float a3 >
15433 /// B = < float b0, float b1, float b2, float b3 >
15434 /// then the result of doing a horizontal operation on A and B is
15435 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15436 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15437 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15438 /// set to A, RHS to B, and the routine returns 'true'.
15439 /// Note that the binary operation should have the property that if one of the
15440 /// operands is UNDEF then the result is UNDEF.
15441 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15442 // Look for the following pattern: if
15443 // A = < float a0, float a1, float a2, float a3 >
15444 // B = < float b0, float b1, float b2, float b3 >
15446 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15447 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15448 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15449 // which is A horizontal-op B.
15451 // At least one of the operands should be a vector shuffle.
15452 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15453 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15456 EVT VT = LHS.getValueType();
15458 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15459 "Unsupported vector type for horizontal add/sub");
15461 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15462 // operate independently on 128-bit lanes.
15463 unsigned NumElts = VT.getVectorNumElements();
15464 unsigned NumLanes = VT.getSizeInBits()/128;
15465 unsigned NumLaneElts = NumElts / NumLanes;
15466 assert((NumLaneElts % 2 == 0) &&
15467 "Vector type should have an even number of elements in each lane");
15468 unsigned HalfLaneElts = NumLaneElts/2;
15470 // View LHS in the form
15471 // LHS = VECTOR_SHUFFLE A, B, LMask
15472 // If LHS is not a shuffle then pretend it is the shuffle
15473 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15474 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15477 SmallVector<int, 16> LMask(NumElts);
15478 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15479 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15480 A = LHS.getOperand(0);
15481 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15482 B = LHS.getOperand(1);
15483 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15484 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15486 if (LHS.getOpcode() != ISD::UNDEF)
15488 for (unsigned i = 0; i != NumElts; ++i)
15492 // Likewise, view RHS in the form
15493 // RHS = VECTOR_SHUFFLE C, D, RMask
15495 SmallVector<int, 16> RMask(NumElts);
15496 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15497 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15498 C = RHS.getOperand(0);
15499 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15500 D = RHS.getOperand(1);
15501 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15502 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15504 if (RHS.getOpcode() != ISD::UNDEF)
15506 for (unsigned i = 0; i != NumElts; ++i)
15510 // Check that the shuffles are both shuffling the same vectors.
15511 if (!(A == C && B == D) && !(A == D && B == C))
15514 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15515 if (!A.getNode() && !B.getNode())
15518 // If A and B occur in reverse order in RHS, then "swap" them (which means
15519 // rewriting the mask).
15521 CommuteVectorShuffleMask(RMask, NumElts);
15523 // At this point LHS and RHS are equivalent to
15524 // LHS = VECTOR_SHUFFLE A, B, LMask
15525 // RHS = VECTOR_SHUFFLE A, B, RMask
15526 // Check that the masks correspond to performing a horizontal operation.
15527 for (unsigned i = 0; i != NumElts; ++i) {
15528 int LIdx = LMask[i], RIdx = RMask[i];
15530 // Ignore any UNDEF components.
15531 if (LIdx < 0 || RIdx < 0 ||
15532 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15533 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15536 // Check that successive elements are being operated on. If not, this is
15537 // not a horizontal operation.
15538 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15539 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15540 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15541 if (!(LIdx == Index && RIdx == Index + 1) &&
15542 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15546 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15547 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15551 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15552 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15553 const X86Subtarget *Subtarget) {
15554 EVT VT = N->getValueType(0);
15555 SDValue LHS = N->getOperand(0);
15556 SDValue RHS = N->getOperand(1);
15558 // Try to synthesize horizontal adds from adds of shuffles.
15559 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15560 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15561 isHorizontalBinOp(LHS, RHS, true))
15562 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15566 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15567 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15568 const X86Subtarget *Subtarget) {
15569 EVT VT = N->getValueType(0);
15570 SDValue LHS = N->getOperand(0);
15571 SDValue RHS = N->getOperand(1);
15573 // Try to synthesize horizontal subs from subs of shuffles.
15574 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15575 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15576 isHorizontalBinOp(LHS, RHS, false))
15577 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15581 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15582 /// X86ISD::FXOR nodes.
15583 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15584 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15585 // F[X]OR(0.0, x) -> x
15586 // F[X]OR(x, 0.0) -> x
15587 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15588 if (C->getValueAPF().isPosZero())
15589 return N->getOperand(1);
15590 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15591 if (C->getValueAPF().isPosZero())
15592 return N->getOperand(0);
15596 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15597 /// X86ISD::FMAX nodes.
15598 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15599 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15601 // Only perform optimizations if UnsafeMath is used.
15602 if (!DAG.getTarget().Options.UnsafeFPMath)
15605 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15606 // into FMINC and FMAXC, which are Commutative operations.
15607 unsigned NewOp = 0;
15608 switch (N->getOpcode()) {
15609 default: llvm_unreachable("unknown opcode");
15610 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15611 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15614 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15615 N->getOperand(0), N->getOperand(1));
15619 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15620 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15621 // FAND(0.0, x) -> 0.0
15622 // FAND(x, 0.0) -> 0.0
15623 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15624 if (C->getValueAPF().isPosZero())
15625 return N->getOperand(0);
15626 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15627 if (C->getValueAPF().isPosZero())
15628 return N->getOperand(1);
15632 static SDValue PerformBTCombine(SDNode *N,
15634 TargetLowering::DAGCombinerInfo &DCI) {
15635 // BT ignores high bits in the bit index operand.
15636 SDValue Op1 = N->getOperand(1);
15637 if (Op1.hasOneUse()) {
15638 unsigned BitWidth = Op1.getValueSizeInBits();
15639 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15640 APInt KnownZero, KnownOne;
15641 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15642 !DCI.isBeforeLegalizeOps());
15643 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15644 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15645 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15646 DCI.CommitTargetLoweringOpt(TLO);
15651 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15652 SDValue Op = N->getOperand(0);
15653 if (Op.getOpcode() == ISD::BITCAST)
15654 Op = Op.getOperand(0);
15655 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15656 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15657 VT.getVectorElementType().getSizeInBits() ==
15658 OpVT.getVectorElementType().getSizeInBits()) {
15659 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15664 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15665 TargetLowering::DAGCombinerInfo &DCI,
15666 const X86Subtarget *Subtarget) {
15667 if (!DCI.isBeforeLegalizeOps())
15670 if (!Subtarget->hasAVX())
15673 EVT VT = N->getValueType(0);
15674 SDValue Op = N->getOperand(0);
15675 EVT OpVT = Op.getValueType();
15676 DebugLoc dl = N->getDebugLoc();
15678 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15679 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15681 if (Subtarget->hasAVX2())
15682 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15684 // Optimize vectors in AVX mode
15685 // Sign extend v8i16 to v8i32 and
15688 // Divide input vector into two parts
15689 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15690 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15691 // concat the vectors to original VT
15693 unsigned NumElems = OpVT.getVectorNumElements();
15694 SDValue Undef = DAG.getUNDEF(OpVT);
15696 SmallVector<int,8> ShufMask1(NumElems, -1);
15697 for (unsigned i = 0; i != NumElems/2; ++i)
15700 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15702 SmallVector<int,8> ShufMask2(NumElems, -1);
15703 for (unsigned i = 0; i != NumElems/2; ++i)
15704 ShufMask2[i] = i + NumElems/2;
15706 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15708 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15709 VT.getVectorNumElements()/2);
15711 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15712 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15714 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15719 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15720 const X86Subtarget* Subtarget) {
15721 DebugLoc dl = N->getDebugLoc();
15722 EVT VT = N->getValueType(0);
15724 // Let legalize expand this if it isn't a legal type yet.
15725 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15728 EVT ScalarVT = VT.getScalarType();
15729 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15730 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15733 SDValue A = N->getOperand(0);
15734 SDValue B = N->getOperand(1);
15735 SDValue C = N->getOperand(2);
15737 bool NegA = (A.getOpcode() == ISD::FNEG);
15738 bool NegB = (B.getOpcode() == ISD::FNEG);
15739 bool NegC = (C.getOpcode() == ISD::FNEG);
15741 // Negative multiplication when NegA xor NegB
15742 bool NegMul = (NegA != NegB);
15744 A = A.getOperand(0);
15746 B = B.getOperand(0);
15748 C = C.getOperand(0);
15752 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15754 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15756 return DAG.getNode(Opcode, dl, VT, A, B, C);
15759 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15760 TargetLowering::DAGCombinerInfo &DCI,
15761 const X86Subtarget *Subtarget) {
15762 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15763 // (and (i32 x86isd::setcc_carry), 1)
15764 // This eliminates the zext. This transformation is necessary because
15765 // ISD::SETCC is always legalized to i8.
15766 DebugLoc dl = N->getDebugLoc();
15767 SDValue N0 = N->getOperand(0);
15768 EVT VT = N->getValueType(0);
15769 EVT OpVT = N0.getValueType();
15771 if (N0.getOpcode() == ISD::AND &&
15773 N0.getOperand(0).hasOneUse()) {
15774 SDValue N00 = N0.getOperand(0);
15775 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15777 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15778 if (!C || C->getZExtValue() != 1)
15780 return DAG.getNode(ISD::AND, dl, VT,
15781 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15782 N00.getOperand(0), N00.getOperand(1)),
15783 DAG.getConstant(1, VT));
15786 // Optimize vectors in AVX mode:
15789 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15790 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15791 // Concat upper and lower parts.
15794 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15795 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15796 // Concat upper and lower parts.
15798 if (!DCI.isBeforeLegalizeOps())
15801 if (!Subtarget->hasAVX())
15804 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15805 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15807 if (Subtarget->hasAVX2())
15808 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15810 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15811 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15812 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15814 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15815 VT.getVectorNumElements()/2);
15817 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15818 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15820 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15826 // Optimize x == -y --> x+y == 0
15827 // x != -y --> x+y != 0
15828 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15829 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15830 SDValue LHS = N->getOperand(0);
15831 SDValue RHS = N->getOperand(1);
15833 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15834 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15835 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15836 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15837 LHS.getValueType(), RHS, LHS.getOperand(1));
15838 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15839 addV, DAG.getConstant(0, addV.getValueType()), CC);
15841 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15842 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15843 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15844 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15845 RHS.getValueType(), LHS, RHS.getOperand(1));
15846 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15847 addV, DAG.getConstant(0, addV.getValueType()), CC);
15852 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15853 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15854 TargetLowering::DAGCombinerInfo &DCI,
15855 const X86Subtarget *Subtarget) {
15856 DebugLoc DL = N->getDebugLoc();
15857 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15858 SDValue EFLAGS = N->getOperand(1);
15860 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15861 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15863 if (CC == X86::COND_B)
15864 return DAG.getNode(ISD::AND, DL, MVT::i8,
15865 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15866 DAG.getConstant(CC, MVT::i8), EFLAGS),
15867 DAG.getConstant(1, MVT::i8));
15871 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15872 if (Flags.getNode()) {
15873 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15874 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15880 // Optimize branch condition evaluation.
15882 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15883 TargetLowering::DAGCombinerInfo &DCI,
15884 const X86Subtarget *Subtarget) {
15885 DebugLoc DL = N->getDebugLoc();
15886 SDValue Chain = N->getOperand(0);
15887 SDValue Dest = N->getOperand(1);
15888 SDValue EFLAGS = N->getOperand(3);
15889 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15893 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15894 if (Flags.getNode()) {
15895 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15896 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15903 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15904 SDValue Op0 = N->getOperand(0);
15905 EVT InVT = Op0->getValueType(0);
15907 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15908 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15909 DebugLoc dl = N->getDebugLoc();
15910 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15911 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15912 // Notice that we use SINT_TO_FP because we know that the high bits
15913 // are zero and SINT_TO_FP is better supported by the hardware.
15914 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15920 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15921 const X86TargetLowering *XTLI) {
15922 SDValue Op0 = N->getOperand(0);
15923 EVT InVT = Op0->getValueType(0);
15925 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15926 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15927 DebugLoc dl = N->getDebugLoc();
15928 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15929 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15930 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15933 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15934 // a 32-bit target where SSE doesn't support i64->FP operations.
15935 if (Op0.getOpcode() == ISD::LOAD) {
15936 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15937 EVT VT = Ld->getValueType(0);
15938 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15939 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15940 !XTLI->getSubtarget()->is64Bit() &&
15941 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15942 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15943 Ld->getChain(), Op0, DAG);
15944 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15951 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15952 EVT VT = N->getValueType(0);
15954 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15955 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15956 DebugLoc dl = N->getDebugLoc();
15957 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15958 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15959 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15965 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15966 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15967 X86TargetLowering::DAGCombinerInfo &DCI) {
15968 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15969 // the result is either zero or one (depending on the input carry bit).
15970 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15971 if (X86::isZeroNode(N->getOperand(0)) &&
15972 X86::isZeroNode(N->getOperand(1)) &&
15973 // We don't have a good way to replace an EFLAGS use, so only do this when
15975 SDValue(N, 1).use_empty()) {
15976 DebugLoc DL = N->getDebugLoc();
15977 EVT VT = N->getValueType(0);
15978 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15979 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15980 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15981 DAG.getConstant(X86::COND_B,MVT::i8),
15983 DAG.getConstant(1, VT));
15984 return DCI.CombineTo(N, Res1, CarryOut);
15990 // fold (add Y, (sete X, 0)) -> adc 0, Y
15991 // (add Y, (setne X, 0)) -> sbb -1, Y
15992 // (sub (sete X, 0), Y) -> sbb 0, Y
15993 // (sub (setne X, 0), Y) -> adc -1, Y
15994 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15995 DebugLoc DL = N->getDebugLoc();
15997 // Look through ZExts.
15998 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15999 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16002 SDValue SetCC = Ext.getOperand(0);
16003 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16006 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16007 if (CC != X86::COND_E && CC != X86::COND_NE)
16010 SDValue Cmp = SetCC.getOperand(1);
16011 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16012 !X86::isZeroNode(Cmp.getOperand(1)) ||
16013 !Cmp.getOperand(0).getValueType().isInteger())
16016 SDValue CmpOp0 = Cmp.getOperand(0);
16017 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16018 DAG.getConstant(1, CmpOp0.getValueType()));
16020 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16021 if (CC == X86::COND_NE)
16022 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16023 DL, OtherVal.getValueType(), OtherVal,
16024 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16025 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16026 DL, OtherVal.getValueType(), OtherVal,
16027 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16030 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16031 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16032 const X86Subtarget *Subtarget) {
16033 EVT VT = N->getValueType(0);
16034 SDValue Op0 = N->getOperand(0);
16035 SDValue Op1 = N->getOperand(1);
16037 // Try to synthesize horizontal adds from adds of shuffles.
16038 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16039 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16040 isHorizontalBinOp(Op0, Op1, true))
16041 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16043 return OptimizeConditionalInDecrement(N, DAG);
16046 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16047 const X86Subtarget *Subtarget) {
16048 SDValue Op0 = N->getOperand(0);
16049 SDValue Op1 = N->getOperand(1);
16051 // X86 can't encode an immediate LHS of a sub. See if we can push the
16052 // negation into a preceding instruction.
16053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16054 // If the RHS of the sub is a XOR with one use and a constant, invert the
16055 // immediate. Then add one to the LHS of the sub so we can turn
16056 // X-Y -> X+~Y+1, saving one register.
16057 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16058 isa<ConstantSDNode>(Op1.getOperand(1))) {
16059 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16060 EVT VT = Op0.getValueType();
16061 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16063 DAG.getConstant(~XorC, VT));
16064 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16065 DAG.getConstant(C->getAPIntValue()+1, VT));
16069 // Try to synthesize horizontal adds from adds of shuffles.
16070 EVT VT = N->getValueType(0);
16071 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16072 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16073 isHorizontalBinOp(Op0, Op1, true))
16074 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16076 return OptimizeConditionalInDecrement(N, DAG);
16079 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16080 DAGCombinerInfo &DCI) const {
16081 SelectionDAG &DAG = DCI.DAG;
16082 switch (N->getOpcode()) {
16084 case ISD::EXTRACT_VECTOR_ELT:
16085 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16087 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16088 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16089 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16090 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16091 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16092 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16095 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16096 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16097 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16098 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16099 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16100 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16101 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16102 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16103 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
16104 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16105 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16107 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16109 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16110 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16111 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16112 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16113 case ISD::ANY_EXTEND:
16114 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16115 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16116 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16117 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16118 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16119 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16120 case X86ISD::SHUFP: // Handle all target specific shuffles
16121 case X86ISD::PALIGN:
16122 case X86ISD::UNPCKH:
16123 case X86ISD::UNPCKL:
16124 case X86ISD::MOVHLPS:
16125 case X86ISD::MOVLHPS:
16126 case X86ISD::PSHUFD:
16127 case X86ISD::PSHUFHW:
16128 case X86ISD::PSHUFLW:
16129 case X86ISD::MOVSS:
16130 case X86ISD::MOVSD:
16131 case X86ISD::VPERMILP:
16132 case X86ISD::VPERM2X128:
16133 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16134 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16140 /// isTypeDesirableForOp - Return true if the target has native support for
16141 /// the specified value type and it is 'desirable' to use the type for the
16142 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16143 /// instruction encodings are longer and some i16 instructions are slow.
16144 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16145 if (!isTypeLegal(VT))
16147 if (VT != MVT::i16)
16154 case ISD::SIGN_EXTEND:
16155 case ISD::ZERO_EXTEND:
16156 case ISD::ANY_EXTEND:
16169 /// IsDesirableToPromoteOp - This method query the target whether it is
16170 /// beneficial for dag combiner to promote the specified node. If true, it
16171 /// should return the desired promotion type by reference.
16172 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16173 EVT VT = Op.getValueType();
16174 if (VT != MVT::i16)
16177 bool Promote = false;
16178 bool Commute = false;
16179 switch (Op.getOpcode()) {
16182 LoadSDNode *LD = cast<LoadSDNode>(Op);
16183 // If the non-extending load has a single use and it's not live out, then it
16184 // might be folded.
16185 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16186 Op.hasOneUse()*/) {
16187 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16188 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16189 // The only case where we'd want to promote LOAD (rather then it being
16190 // promoted as an operand is when it's only use is liveout.
16191 if (UI->getOpcode() != ISD::CopyToReg)
16198 case ISD::SIGN_EXTEND:
16199 case ISD::ZERO_EXTEND:
16200 case ISD::ANY_EXTEND:
16205 SDValue N0 = Op.getOperand(0);
16206 // Look out for (store (shl (load), x)).
16207 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16220 SDValue N0 = Op.getOperand(0);
16221 SDValue N1 = Op.getOperand(1);
16222 if (!Commute && MayFoldLoad(N1))
16224 // Avoid disabling potential load folding opportunities.
16225 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16227 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16237 //===----------------------------------------------------------------------===//
16238 // X86 Inline Assembly Support
16239 //===----------------------------------------------------------------------===//
16242 // Helper to match a string separated by whitespace.
16243 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16244 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16246 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16247 StringRef piece(*args[i]);
16248 if (!s.startswith(piece)) // Check if the piece matches.
16251 s = s.substr(piece.size());
16252 StringRef::size_type pos = s.find_first_not_of(" \t");
16253 if (pos == 0) // We matched a prefix.
16261 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16264 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16265 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16267 std::string AsmStr = IA->getAsmString();
16269 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16270 if (!Ty || Ty->getBitWidth() % 16 != 0)
16273 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16274 SmallVector<StringRef, 4> AsmPieces;
16275 SplitString(AsmStr, AsmPieces, ";\n");
16277 switch (AsmPieces.size()) {
16278 default: return false;
16280 // FIXME: this should verify that we are targeting a 486 or better. If not,
16281 // we will turn this bswap into something that will be lowered to logical
16282 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16283 // lower so don't worry about this.
16285 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16286 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16287 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16288 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16289 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16290 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16291 // No need to check constraints, nothing other than the equivalent of
16292 // "=r,0" would be valid here.
16293 return IntrinsicLowering::LowerToByteSwap(CI);
16296 // rorw $$8, ${0:w} --> llvm.bswap.i16
16297 if (CI->getType()->isIntegerTy(16) &&
16298 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16299 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16300 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16302 const std::string &ConstraintsStr = IA->getConstraintString();
16303 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16304 std::sort(AsmPieces.begin(), AsmPieces.end());
16305 if (AsmPieces.size() == 4 &&
16306 AsmPieces[0] == "~{cc}" &&
16307 AsmPieces[1] == "~{dirflag}" &&
16308 AsmPieces[2] == "~{flags}" &&
16309 AsmPieces[3] == "~{fpsr}")
16310 return IntrinsicLowering::LowerToByteSwap(CI);
16314 if (CI->getType()->isIntegerTy(32) &&
16315 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16316 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16317 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16318 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16320 const std::string &ConstraintsStr = IA->getConstraintString();
16321 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16322 std::sort(AsmPieces.begin(), AsmPieces.end());
16323 if (AsmPieces.size() == 4 &&
16324 AsmPieces[0] == "~{cc}" &&
16325 AsmPieces[1] == "~{dirflag}" &&
16326 AsmPieces[2] == "~{flags}" &&
16327 AsmPieces[3] == "~{fpsr}")
16328 return IntrinsicLowering::LowerToByteSwap(CI);
16331 if (CI->getType()->isIntegerTy(64)) {
16332 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16333 if (Constraints.size() >= 2 &&
16334 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16335 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16336 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16337 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16338 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16339 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16340 return IntrinsicLowering::LowerToByteSwap(CI);
16350 /// getConstraintType - Given a constraint letter, return the type of
16351 /// constraint it is for this target.
16352 X86TargetLowering::ConstraintType
16353 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16354 if (Constraint.size() == 1) {
16355 switch (Constraint[0]) {
16366 return C_RegisterClass;
16390 return TargetLowering::getConstraintType(Constraint);
16393 /// Examine constraint type and operand type and determine a weight value.
16394 /// This object must already have been set up with the operand type
16395 /// and the current alternative constraint selected.
16396 TargetLowering::ConstraintWeight
16397 X86TargetLowering::getSingleConstraintMatchWeight(
16398 AsmOperandInfo &info, const char *constraint) const {
16399 ConstraintWeight weight = CW_Invalid;
16400 Value *CallOperandVal = info.CallOperandVal;
16401 // If we don't have a value, we can't do a match,
16402 // but allow it at the lowest weight.
16403 if (CallOperandVal == NULL)
16405 Type *type = CallOperandVal->getType();
16406 // Look at the constraint type.
16407 switch (*constraint) {
16409 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16420 if (CallOperandVal->getType()->isIntegerTy())
16421 weight = CW_SpecificReg;
16426 if (type->isFloatingPointTy())
16427 weight = CW_SpecificReg;
16430 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16431 weight = CW_SpecificReg;
16435 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16436 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16437 weight = CW_Register;
16440 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16441 if (C->getZExtValue() <= 31)
16442 weight = CW_Constant;
16446 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16447 if (C->getZExtValue() <= 63)
16448 weight = CW_Constant;
16452 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16453 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16454 weight = CW_Constant;
16458 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16459 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16460 weight = CW_Constant;
16464 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16465 if (C->getZExtValue() <= 3)
16466 weight = CW_Constant;
16470 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16471 if (C->getZExtValue() <= 0xff)
16472 weight = CW_Constant;
16477 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16478 weight = CW_Constant;
16482 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16483 if ((C->getSExtValue() >= -0x80000000LL) &&
16484 (C->getSExtValue() <= 0x7fffffffLL))
16485 weight = CW_Constant;
16489 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16490 if (C->getZExtValue() <= 0xffffffff)
16491 weight = CW_Constant;
16498 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16499 /// with another that has more specific requirements based on the type of the
16500 /// corresponding operand.
16501 const char *X86TargetLowering::
16502 LowerXConstraint(EVT ConstraintVT) const {
16503 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16504 // 'f' like normal targets.
16505 if (ConstraintVT.isFloatingPoint()) {
16506 if (Subtarget->hasSSE2())
16508 if (Subtarget->hasSSE1())
16512 return TargetLowering::LowerXConstraint(ConstraintVT);
16515 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16516 /// vector. If it is invalid, don't add anything to Ops.
16517 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16518 std::string &Constraint,
16519 std::vector<SDValue>&Ops,
16520 SelectionDAG &DAG) const {
16521 SDValue Result(0, 0);
16523 // Only support length 1 constraints for now.
16524 if (Constraint.length() > 1) return;
16526 char ConstraintLetter = Constraint[0];
16527 switch (ConstraintLetter) {
16530 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16531 if (C->getZExtValue() <= 31) {
16532 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16538 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16539 if (C->getZExtValue() <= 63) {
16540 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16547 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16548 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16555 if (C->getZExtValue() <= 255) {
16556 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16562 // 32-bit signed value
16563 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16564 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16565 C->getSExtValue())) {
16566 // Widen to 64 bits here to get it sign extended.
16567 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16570 // FIXME gcc accepts some relocatable values here too, but only in certain
16571 // memory models; it's complicated.
16576 // 32-bit unsigned value
16577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16578 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16579 C->getZExtValue())) {
16580 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16584 // FIXME gcc accepts some relocatable values here too, but only in certain
16585 // memory models; it's complicated.
16589 // Literal immediates are always ok.
16590 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16591 // Widen to 64 bits here to get it sign extended.
16592 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16596 // In any sort of PIC mode addresses need to be computed at runtime by
16597 // adding in a register or some sort of table lookup. These can't
16598 // be used as immediates.
16599 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16602 // If we are in non-pic codegen mode, we allow the address of a global (with
16603 // an optional displacement) to be used with 'i'.
16604 GlobalAddressSDNode *GA = 0;
16605 int64_t Offset = 0;
16607 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16609 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16610 Offset += GA->getOffset();
16612 } else if (Op.getOpcode() == ISD::ADD) {
16613 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16614 Offset += C->getZExtValue();
16615 Op = Op.getOperand(0);
16618 } else if (Op.getOpcode() == ISD::SUB) {
16619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16620 Offset += -C->getZExtValue();
16621 Op = Op.getOperand(0);
16626 // Otherwise, this isn't something we can handle, reject it.
16630 const GlobalValue *GV = GA->getGlobal();
16631 // If we require an extra load to get this address, as in PIC mode, we
16632 // can't accept it.
16633 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16634 getTargetMachine())))
16637 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16638 GA->getValueType(0), Offset);
16643 if (Result.getNode()) {
16644 Ops.push_back(Result);
16647 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16650 std::pair<unsigned, const TargetRegisterClass*>
16651 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16653 // First, see if this is a constraint that directly corresponds to an LLVM
16655 if (Constraint.size() == 1) {
16656 // GCC Constraint Letters
16657 switch (Constraint[0]) {
16659 // TODO: Slight differences here in allocation order and leaving
16660 // RIP in the class. Do they matter any more here than they do
16661 // in the normal allocation?
16662 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16663 if (Subtarget->is64Bit()) {
16664 if (VT == MVT::i32 || VT == MVT::f32)
16665 return std::make_pair(0U, &X86::GR32RegClass);
16666 if (VT == MVT::i16)
16667 return std::make_pair(0U, &X86::GR16RegClass);
16668 if (VT == MVT::i8 || VT == MVT::i1)
16669 return std::make_pair(0U, &X86::GR8RegClass);
16670 if (VT == MVT::i64 || VT == MVT::f64)
16671 return std::make_pair(0U, &X86::GR64RegClass);
16674 // 32-bit fallthrough
16675 case 'Q': // Q_REGS
16676 if (VT == MVT::i32 || VT == MVT::f32)
16677 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16678 if (VT == MVT::i16)
16679 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16680 if (VT == MVT::i8 || VT == MVT::i1)
16681 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16682 if (VT == MVT::i64)
16683 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16685 case 'r': // GENERAL_REGS
16686 case 'l': // INDEX_REGS
16687 if (VT == MVT::i8 || VT == MVT::i1)
16688 return std::make_pair(0U, &X86::GR8RegClass);
16689 if (VT == MVT::i16)
16690 return std::make_pair(0U, &X86::GR16RegClass);
16691 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16692 return std::make_pair(0U, &X86::GR32RegClass);
16693 return std::make_pair(0U, &X86::GR64RegClass);
16694 case 'R': // LEGACY_REGS
16695 if (VT == MVT::i8 || VT == MVT::i1)
16696 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16697 if (VT == MVT::i16)
16698 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16699 if (VT == MVT::i32 || !Subtarget->is64Bit())
16700 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16701 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16702 case 'f': // FP Stack registers.
16703 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16704 // value to the correct fpstack register class.
16705 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16706 return std::make_pair(0U, &X86::RFP32RegClass);
16707 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16708 return std::make_pair(0U, &X86::RFP64RegClass);
16709 return std::make_pair(0U, &X86::RFP80RegClass);
16710 case 'y': // MMX_REGS if MMX allowed.
16711 if (!Subtarget->hasMMX()) break;
16712 return std::make_pair(0U, &X86::VR64RegClass);
16713 case 'Y': // SSE_REGS if SSE2 allowed
16714 if (!Subtarget->hasSSE2()) break;
16716 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16717 if (!Subtarget->hasSSE1()) break;
16719 switch (VT.getSimpleVT().SimpleTy) {
16721 // Scalar SSE types.
16724 return std::make_pair(0U, &X86::FR32RegClass);
16727 return std::make_pair(0U, &X86::FR64RegClass);
16735 return std::make_pair(0U, &X86::VR128RegClass);
16743 return std::make_pair(0U, &X86::VR256RegClass);
16749 // Use the default implementation in TargetLowering to convert the register
16750 // constraint into a member of a register class.
16751 std::pair<unsigned, const TargetRegisterClass*> Res;
16752 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16754 // Not found as a standard register?
16755 if (Res.second == 0) {
16756 // Map st(0) -> st(7) -> ST0
16757 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16758 tolower(Constraint[1]) == 's' &&
16759 tolower(Constraint[2]) == 't' &&
16760 Constraint[3] == '(' &&
16761 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16762 Constraint[5] == ')' &&
16763 Constraint[6] == '}') {
16765 Res.first = X86::ST0+Constraint[4]-'0';
16766 Res.second = &X86::RFP80RegClass;
16770 // GCC allows "st(0)" to be called just plain "st".
16771 if (StringRef("{st}").equals_lower(Constraint)) {
16772 Res.first = X86::ST0;
16773 Res.second = &X86::RFP80RegClass;
16778 if (StringRef("{flags}").equals_lower(Constraint)) {
16779 Res.first = X86::EFLAGS;
16780 Res.second = &X86::CCRRegClass;
16784 // 'A' means EAX + EDX.
16785 if (Constraint == "A") {
16786 Res.first = X86::EAX;
16787 Res.second = &X86::GR32_ADRegClass;
16793 // Otherwise, check to see if this is a register class of the wrong value
16794 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16795 // turn into {ax},{dx}.
16796 if (Res.second->hasType(VT))
16797 return Res; // Correct type already, nothing to do.
16799 // All of the single-register GCC register classes map their values onto
16800 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16801 // really want an 8-bit or 32-bit register, map to the appropriate register
16802 // class and return the appropriate register.
16803 if (Res.second == &X86::GR16RegClass) {
16804 if (VT == MVT::i8) {
16805 unsigned DestReg = 0;
16806 switch (Res.first) {
16808 case X86::AX: DestReg = X86::AL; break;
16809 case X86::DX: DestReg = X86::DL; break;
16810 case X86::CX: DestReg = X86::CL; break;
16811 case X86::BX: DestReg = X86::BL; break;
16814 Res.first = DestReg;
16815 Res.second = &X86::GR8RegClass;
16817 } else if (VT == MVT::i32) {
16818 unsigned DestReg = 0;
16819 switch (Res.first) {
16821 case X86::AX: DestReg = X86::EAX; break;
16822 case X86::DX: DestReg = X86::EDX; break;
16823 case X86::CX: DestReg = X86::ECX; break;
16824 case X86::BX: DestReg = X86::EBX; break;
16825 case X86::SI: DestReg = X86::ESI; break;
16826 case X86::DI: DestReg = X86::EDI; break;
16827 case X86::BP: DestReg = X86::EBP; break;
16828 case X86::SP: DestReg = X86::ESP; break;
16831 Res.first = DestReg;
16832 Res.second = &X86::GR32RegClass;
16834 } else if (VT == MVT::i64) {
16835 unsigned DestReg = 0;
16836 switch (Res.first) {
16838 case X86::AX: DestReg = X86::RAX; break;
16839 case X86::DX: DestReg = X86::RDX; break;
16840 case X86::CX: DestReg = X86::RCX; break;
16841 case X86::BX: DestReg = X86::RBX; break;
16842 case X86::SI: DestReg = X86::RSI; break;
16843 case X86::DI: DestReg = X86::RDI; break;
16844 case X86::BP: DestReg = X86::RBP; break;
16845 case X86::SP: DestReg = X86::RSP; break;
16848 Res.first = DestReg;
16849 Res.second = &X86::GR64RegClass;
16852 } else if (Res.second == &X86::FR32RegClass ||
16853 Res.second == &X86::FR64RegClass ||
16854 Res.second == &X86::VR128RegClass) {
16855 // Handle references to XMM physical registers that got mapped into the
16856 // wrong class. This can happen with constraints like {xmm0} where the
16857 // target independent register mapper will just pick the first match it can
16858 // find, ignoring the required type.
16860 if (VT == MVT::f32 || VT == MVT::i32)
16861 Res.second = &X86::FR32RegClass;
16862 else if (VT == MVT::f64 || VT == MVT::i64)
16863 Res.second = &X86::FR64RegClass;
16864 else if (X86::VR128RegClass.hasType(VT))
16865 Res.second = &X86::VR128RegClass;
16866 else if (X86::VR256RegClass.hasType(VT))
16867 Res.second = &X86::VR256RegClass;